stratal 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +4 -0
  2. package/dist/bin/cloudflare-workers-loader.mjs +33 -1
  3. package/dist/bin/cloudflare-workers-loader.mjs.map +1 -1
  4. package/dist/bin/quarry.mjs +183 -55
  5. package/dist/bin/quarry.mjs.map +1 -1
  6. package/dist/cache/index.d.mts +2 -2
  7. package/dist/cache/index.d.mts.map +1 -1
  8. package/dist/cache/index.mjs +3 -11
  9. package/dist/cache/index.mjs.map +1 -1
  10. package/dist/{colors-DJaRDXoS.mjs → colors-BTAnQRGU.mjs} +1 -1
  11. package/dist/{colors-DJaRDXoS.mjs.map → colors-BTAnQRGU.mjs.map} +1 -1
  12. package/dist/{command-B-QH-Vu3.d.mts → command-B1YuV-UZ.d.mts} +2 -2
  13. package/dist/{command-B-QH-Vu3.d.mts.map → command-B1YuV-UZ.d.mts.map} +1 -1
  14. package/dist/{command-BvCOD6df.mjs → command-DjGqCYHv.mjs} +7 -4
  15. package/dist/command-DjGqCYHv.mjs.map +1 -0
  16. package/dist/config/index.d.mts +2 -2
  17. package/dist/config/index.mjs +12 -20
  18. package/dist/config/index.mjs.map +1 -1
  19. package/dist/consumer-registry-BkuHXR_u.d.mts +142 -0
  20. package/dist/consumer-registry-BkuHXR_u.d.mts.map +1 -0
  21. package/dist/cron/index.d.mts +3 -116
  22. package/dist/cron/index.d.mts.map +1 -1
  23. package/dist/cron/index.mjs +1 -4
  24. package/dist/{cron-manager-DR7fiG6o.mjs → cron-manager-1KnZvojs.mjs} +3 -3
  25. package/dist/{cron-manager-DR7fiG6o.mjs.map → cron-manager-1KnZvojs.mjs.map} +1 -1
  26. package/dist/cron-manager-BnEZquBL.d.mts +117 -0
  27. package/dist/cron-manager-BnEZquBL.d.mts.map +1 -0
  28. package/dist/di/index.d.mts +2 -2
  29. package/dist/di/index.mjs +3 -4
  30. package/dist/email/index.d.mts +3 -3
  31. package/dist/email/index.mjs +8 -17
  32. package/dist/email/index.mjs.map +1 -1
  33. package/dist/{en-DaewN8hc.mjs → en-3QnZwP-u.mjs} +10 -1
  34. package/dist/en-3QnZwP-u.mjs.map +1 -0
  35. package/dist/errors/index.d.mts +2 -2
  36. package/dist/errors/index.mjs +2 -4
  37. package/dist/errors--RBIvDXr.mjs +1560 -0
  38. package/dist/errors--RBIvDXr.mjs.map +1 -0
  39. package/dist/{errors-H3TZnVeX.mjs → errors-B7hCnXgB.mjs} +2 -2
  40. package/dist/{errors-H3TZnVeX.mjs.map → errors-B7hCnXgB.mjs.map} +1 -1
  41. package/dist/events/index.d.mts +2 -2
  42. package/dist/events/index.mjs +1 -3
  43. package/dist/{events-CXl-o1Ad.mjs → events-UTJliZhl.mjs} +2 -3
  44. package/dist/{events-CXl-o1Ad.mjs.map → events-UTJliZhl.mjs.map} +1 -1
  45. package/dist/{gateway-context-BkZ4UKaX.mjs → gateway-context-BdBFoQd8.mjs} +66 -10
  46. package/dist/gateway-context-BdBFoQd8.mjs.map +1 -0
  47. package/dist/guards/index.d.mts +3 -3
  48. package/dist/guards/index.d.mts.map +1 -1
  49. package/dist/guards/index.mjs +1 -1
  50. package/dist/{guards-DUk_Kzst.mjs → guards-MtDgcHnF.mjs} +1 -1
  51. package/dist/{guards-DUk_Kzst.mjs.map → guards-MtDgcHnF.mjs.map} +1 -1
  52. package/dist/i18n/index.d.mts +3 -3
  53. package/dist/i18n/index.mjs +3 -16
  54. package/dist/i18n/messages/en/index.d.mts +1 -1
  55. package/dist/i18n/messages/en/index.mjs +1 -1
  56. package/dist/i18n/utils/index.d.mts +30 -0
  57. package/dist/i18n/utils/index.d.mts.map +1 -0
  58. package/dist/i18n/utils/index.mjs +2 -0
  59. package/dist/i18n/validation/index.d.mts +1 -1
  60. package/dist/i18n/validation/index.mjs +1 -1
  61. package/dist/i18n.module-BpLLLCTg.mjs +2462 -0
  62. package/dist/i18n.module-BpLLLCTg.mjs.map +1 -0
  63. package/dist/{index-D_w_Rmtd.d.mts → index-BDh9J2KD.d.mts} +10 -1
  64. package/dist/{index-D_w_Rmtd.d.mts.map → index-BDh9J2KD.d.mts.map} +1 -1
  65. package/dist/{index-Dp6A5ywM.d.mts → index-BR23zDMy.d.mts} +1 -1
  66. package/dist/{index-Dp6A5ywM.d.mts.map → index-BR23zDMy.d.mts.map} +1 -1
  67. package/dist/index-BrmS34sa.d.mts +4287 -0
  68. package/dist/index-BrmS34sa.d.mts.map +1 -0
  69. package/dist/{index-D9iYu2Yc.d.mts → index-DPxmo6AY.d.mts} +5 -144
  70. package/dist/index-DPxmo6AY.d.mts.map +1 -0
  71. package/dist/{index-DVhdhLvE.d.mts → index-Dfpd_ypO.d.mts} +38 -9
  72. package/dist/index-Dfpd_ypO.d.mts.map +1 -0
  73. package/dist/index.d.mts +4 -3
  74. package/dist/index.d.mts.map +1 -1
  75. package/dist/index.mjs +1 -20
  76. package/dist/{is-command-BfCgWAcQ.mjs → is-command-PvULqiTa.mjs} +2 -2
  77. package/dist/{is-command-BfCgWAcQ.mjs.map → is-command-PvULqiTa.mjs.map} +1 -1
  78. package/dist/{is-seeder-CebjZCDn.mjs → is-seeder-BN9Ej1r7.mjs} +1 -1
  79. package/dist/{is-seeder-CebjZCDn.mjs.map → is-seeder-BN9Ej1r7.mjs.map} +1 -1
  80. package/dist/logger/index.d.mts +1 -1
  81. package/dist/logger/index.mjs +1 -2
  82. package/dist/{logger-BR1-s1Um.mjs → logger-c0ftIK4G.mjs} +170 -4
  83. package/dist/logger-c0ftIK4G.mjs.map +1 -0
  84. package/dist/module/index.d.mts +3 -119
  85. package/dist/module/index.d.mts.map +1 -1
  86. package/dist/module/index.mjs +1 -11
  87. package/dist/module-C3YZ-kZN.mjs +719 -0
  88. package/dist/module-C3YZ-kZN.mjs.map +1 -0
  89. package/dist/openapi/index.d.mts +54 -54
  90. package/dist/openapi/index.d.mts.map +1 -1
  91. package/dist/openapi/index.mjs +3 -16
  92. package/dist/openapi-tools.service-B77QXD56.mjs +197 -0
  93. package/dist/openapi-tools.service-B77QXD56.mjs.map +1 -0
  94. package/dist/openapi.service-6yj0BUY4.d.mts +50 -0
  95. package/dist/openapi.service-6yj0BUY4.d.mts.map +1 -0
  96. package/dist/quarry/index.d.mts +124 -29
  97. package/dist/quarry/index.d.mts.map +1 -1
  98. package/dist/quarry/index.mjs +5 -7
  99. package/dist/quarry-registry-CQCIlYTO.mjs +686 -0
  100. package/dist/quarry-registry-CQCIlYTO.mjs.map +1 -0
  101. package/dist/queue/index.d.mts +2 -1
  102. package/dist/queue/index.mjs +3 -14
  103. package/dist/queue/index.mjs.map +1 -1
  104. package/dist/{queue.module-BZvmeAMj.mjs → queue.module-DIjD6nr-.mjs} +39 -42
  105. package/dist/queue.module-DIjD6nr-.mjs.map +1 -0
  106. package/dist/{resend.provider-BCCACQAU.mjs → resend.provider-Bvw36rQy.mjs} +1 -4
  107. package/dist/{resend.provider-BCCACQAU.mjs.map → resend.provider-Bvw36rQy.mjs.map} +1 -1
  108. package/dist/router/index.d.mts +2 -2
  109. package/dist/router/index.mjs +5 -16
  110. package/dist/{s3-storage.provider-BLlzQYiJ.mjs → s3-storage.provider-BAhHDMI3.mjs} +16 -9
  111. package/dist/s3-storage.provider-BAhHDMI3.mjs.map +1 -0
  112. package/dist/seeder/index.d.mts +3 -4
  113. package/dist/seeder/index.d.mts.map +1 -1
  114. package/dist/seeder/index.mjs +2 -7
  115. package/dist/{seeder-Cupi5jl-.mjs → seeder-D7VXULXB.mjs} +20 -17
  116. package/dist/seeder-D7VXULXB.mjs.map +1 -0
  117. package/dist/setup-BRIN-iYT.mjs +37 -0
  118. package/dist/setup-BRIN-iYT.mjs.map +1 -0
  119. package/dist/{smtp.provider-B8XtOcHU.mjs → smtp.provider-CAwpvzvD.mjs} +1 -4
  120. package/dist/{smtp.provider-B8XtOcHU.mjs.map → smtp.provider-CAwpvzvD.mjs.map} +1 -1
  121. package/dist/storage/index.d.mts +2 -195
  122. package/dist/storage/index.d.mts.map +1 -1
  123. package/dist/storage/index.mjs +2 -14
  124. package/dist/storage/providers/index.d.mts +273 -0
  125. package/dist/storage/providers/index.d.mts.map +1 -0
  126. package/dist/storage/providers/index.mjs +2 -0
  127. package/dist/{storage-By_ow2o_.mjs → storage-CJ-QOwNv.mjs} +8 -9
  128. package/dist/storage-CJ-QOwNv.mjs.map +1 -0
  129. package/dist/storage-provider.interface-YRtyYBxV.d.mts +203 -0
  130. package/dist/storage-provider.interface-YRtyYBxV.d.mts.map +1 -0
  131. package/dist/stratal-B7G4i9-N.mjs +502 -0
  132. package/dist/stratal-B7G4i9-N.mjs.map +1 -0
  133. package/dist/{types-DahElfUw.d.mts → types-CN0zONAZ.d.mts} +2 -2
  134. package/dist/types-CN0zONAZ.d.mts.map +1 -0
  135. package/dist/{usage-generator-C9hWziY4.mjs → usage-generator-Cl1HPlUp.mjs} +2 -2
  136. package/dist/{usage-generator-C9hWziY4.mjs.map → usage-generator-Cl1HPlUp.mjs.map} +1 -1
  137. package/dist/{validation-Bh875Lyg.mjs → validation-B4bePOa_.mjs} +5 -5
  138. package/dist/{validation-Bh875Lyg.mjs.map → validation-B4bePOa_.mjs.map} +1 -1
  139. package/dist/websocket/index.d.mts +2 -2
  140. package/dist/websocket/index.d.mts.map +1 -1
  141. package/dist/websocket/index.mjs +1 -5
  142. package/dist/workers/index.d.mts +1 -1
  143. package/dist/workers/index.d.mts.map +1 -1
  144. package/dist/workers/index.mjs +2 -20
  145. package/dist/workers/index.mjs.map +1 -1
  146. package/package.json +39 -31
  147. package/dist/application-zG8b-pol.d.mts +0 -116
  148. package/dist/application-zG8b-pol.d.mts.map +0 -1
  149. package/dist/command-BvCOD6df.mjs.map +0 -1
  150. package/dist/decorate-D5j-d9_z.mjs +0 -171
  151. package/dist/decorate-D5j-d9_z.mjs.map +0 -1
  152. package/dist/en-DaewN8hc.mjs.map +0 -1
  153. package/dist/errors-CtCi1wn6.mjs +0 -707
  154. package/dist/errors-CtCi1wn6.mjs.map +0 -1
  155. package/dist/gateway-context-BkZ4UKaX.mjs.map +0 -1
  156. package/dist/i18n.module-W8OJxg3d.mjs +0 -1791
  157. package/dist/i18n.module-W8OJxg3d.mjs.map +0 -1
  158. package/dist/index-BJWm863C.d.mts +0 -2616
  159. package/dist/index-BJWm863C.d.mts.map +0 -1
  160. package/dist/index-D9iYu2Yc.d.mts.map +0 -1
  161. package/dist/index-DVhdhLvE.d.mts.map +0 -1
  162. package/dist/logger-BR1-s1Um.mjs.map +0 -1
  163. package/dist/middleware/index.d.mts +0 -2
  164. package/dist/middleware/index.mjs +0 -6
  165. package/dist/middleware-C0Ebzswy.mjs +0 -362
  166. package/dist/middleware-C0Ebzswy.mjs.map +0 -1
  167. package/dist/module-BgdxxzBe.mjs +0 -370
  168. package/dist/module-BgdxxzBe.mjs.map +0 -1
  169. package/dist/quarry-registry-DCwqVcRp.mjs +0 -310
  170. package/dist/quarry-registry-DCwqVcRp.mjs.map +0 -1
  171. package/dist/queue.module-BZvmeAMj.mjs.map +0 -1
  172. package/dist/router-context-BEJe9HEB.mjs +0 -264
  173. package/dist/router-context-BEJe9HEB.mjs.map +0 -1
  174. package/dist/s3-storage.provider-BLlzQYiJ.mjs.map +0 -1
  175. package/dist/seeder-Cupi5jl-.mjs.map +0 -1
  176. package/dist/storage-By_ow2o_.mjs.map +0 -1
  177. package/dist/stratal-CE0iTz4f.mjs +0 -305
  178. package/dist/stratal-CE0iTz4f.mjs.map +0 -1
  179. package/dist/types-CLhOhYsQ.d.mts +0 -64
  180. package/dist/types-CLhOhYsQ.d.mts.map +0 -1
  181. package/dist/types-DahElfUw.d.mts.map +0 -1
@@ -0,0 +1,2462 @@
1
+ import { A as Scope, D as runWithContainer, E as getContainer, H as ApplicationError, V as ROUTER_TOKENS, a as createHttpExceptionContext, c as DEFAULT_CONTENT_TYPE, d as ROUTER_CONTEXT_KEYS, f as ROUTE_METADATA_KEYS, k as ERROR_CODES, l as HTTP_METHODS, m as VERSION_NEUTRAL, p as SECURITY_SCHEMES, s as RouterContext, u as METHOD_STATUS_CODES, w as I18N_TOKENS } from "./errors--RBIvDXr.mjs";
2
+ import { a as __decorate, d as CONTAINER_TOKEN, f as DI_TOKENS, g as getMethodInjections, o as __decorateParam, p as Transient, s as __decorateMetadata, u as LOGGER_TOKENS } from "./logger-c0ftIK4G.mjs";
3
+ import { S as Module, _ as OpenAPIRouteRegistrationError, b as ControllerMethodNotFoundError, c as InvalidSignatureError, d as ResponseValidationError, f as RouteNameNotFoundError, h as RouteNotFoundError, l as MissingEnvironmentVariableError, m as SchemaValidationError, o as DomainMismatchError, s as DuplicateRouteNameError, u as MissingRouteParamError, v as HonoAppAlreadyConfiguredError, y as ControllerRegistrationError } from "./module-C3YZ-kZN.mjs";
4
+ import { i as z, o as backendErrorMap, r as validation_exports, s as runWithErrorMapContext, t as OpenAPIHono } from "./validation-B4bePOa_.mjs";
5
+ import { n as OPENAPI_TOKENS } from "./openapi-tools.service-B77QXD56.mjs";
6
+ import { t as en_exports } from "./en-3QnZwP-u.mjs";
7
+ import { i as getMethodGuards, r as getControllerGuards, t as GuardExecutionService } from "./guards-MtDgcHnF.mjs";
8
+ import { c as getWsOnMessageMethod, d as isGateway, m as getControllerRoute, o as getWsOnCloseMethod, p as getControllerOptions, s as getWsOnErrorMethod, t as GatewayContext } from "./gateway-context-BdBFoQd8.mjs";
9
+ import { t as setupI18nCompiler } from "./setup-BRIN-iYT.mjs";
10
+ import { inject } from "tsyringe";
11
+ import { createCoreContext, translate } from "@intlify/core-base";
12
+ import { swaggerUI } from "@hono/swagger-ui";
13
+ import { languageDetector } from "hono/language";
14
+ //#region src/i18n/middleware/i18n-context.middleware.ts
15
+ /**
16
+ * I18n Context Middleware
17
+ *
18
+ * Sets up AsyncLocalStorage context for Zod i18n validation.
19
+ * Must run after LocaleExtractionMiddleware sets the locale.
20
+ */
21
+ let I18nContextMiddleware = class I18nContextMiddleware {
22
+ constructor(i18n) {
23
+ this.i18n = i18n;
24
+ }
25
+ async handle(ctx, next) {
26
+ await runWithErrorMapContext({
27
+ t: (key, params) => this.i18n.t(key, params),
28
+ locale: ctx.getLocale()
29
+ }, () => next());
30
+ }
31
+ };
32
+ I18nContextMiddleware = __decorate([
33
+ Transient(),
34
+ __decorateParam(0, inject(I18N_TOKENS.I18nService)),
35
+ __decorateMetadata("design:paramtypes", [Object])
36
+ ], I18nContextMiddleware);
37
+ //#endregion
38
+ //#region src/openapi/services/openapi-config.service.ts
39
+ let OpenAPIConfigService = class OpenAPIConfigService {
40
+ overrides = [];
41
+ constructor(baseOptions) {
42
+ this.baseOptions = baseOptions;
43
+ }
44
+ /**
45
+ * Add configuration override for this request.
46
+ * Overrides are merged in the order they are added.
47
+ */
48
+ override(config) {
49
+ this.overrides.push(config);
50
+ }
51
+ /** Get effective configuration (base merged with all overrides) */
52
+ getEffectiveConfig() {
53
+ let effective = {
54
+ jsonPath: this.baseOptions?.jsonPath ?? "/api/openapi.json",
55
+ ui: this.baseOptions?.ui,
56
+ info: {
57
+ title: this.baseOptions?.info?.title ?? "API",
58
+ version: this.baseOptions?.info?.version ?? "1.0.0",
59
+ description: this.baseOptions?.info?.description
60
+ },
61
+ securitySchemes: this.baseOptions?.securitySchemes
62
+ };
63
+ for (const override of this.overrides) effective = this.mergeConfig(effective, override);
64
+ return effective;
65
+ }
66
+ /**
67
+ * Merge override into effective config.
68
+ * Info is shallow-merged, routeFilter is replaced.
69
+ */
70
+ mergeConfig(base, override) {
71
+ return {
72
+ ...base,
73
+ info: {
74
+ ...base.info,
75
+ ...override.info && {
76
+ title: override.info.title ?? base.info.title,
77
+ version: override.info.version ?? base.info.version,
78
+ description: override.info.description ?? base.info.description
79
+ }
80
+ },
81
+ routeFilter: override.routeFilter ?? base.routeFilter
82
+ };
83
+ }
84
+ };
85
+ OpenAPIConfigService = __decorate([
86
+ Transient(OPENAPI_TOKENS.ConfigService),
87
+ __decorateParam(0, inject(OPENAPI_TOKENS.Options, { isOptional: true })),
88
+ __decorateMetadata("design:paramtypes", [Object])
89
+ ], OpenAPIConfigService);
90
+ //#endregion
91
+ //#region src/i18n/errors/locale-not-supported.error.ts
92
+ /**
93
+ * Locale Not Supported Error
94
+ * Thrown when an unsupported locale is requested
95
+ *
96
+ * HTTP Status: 500 Internal Server Error
97
+ * Error Code: 9301
98
+ */
99
+ var LocaleNotSupportedError = class extends ApplicationError {
100
+ constructor(locale, supportedLocales) {
101
+ super("errors.localeNotSupported", ERROR_CODES.I18N.LOCALE_NOT_SUPPORTED, {
102
+ locale,
103
+ supportedLocales: supportedLocales.join(", ")
104
+ });
105
+ }
106
+ };
107
+ //#endregion
108
+ //#region src/i18n/errors/translation-missing.error.ts
109
+ /**
110
+ * Translation Missing Error
111
+ * Thrown when a translation key is missing from all locales
112
+ *
113
+ * HTTP Status: 500 Internal Server Error
114
+ * Error Code: 9300
115
+ */
116
+ var TranslationMissingError = class extends ApplicationError {
117
+ constructor(key, locale) {
118
+ super("errors.translationMissing", ERROR_CODES.I18N.TRANSLATION_MISSING, {
119
+ key,
120
+ locale
121
+ });
122
+ }
123
+ };
124
+ //#endregion
125
+ //#region src/i18n/i18n.options.ts
126
+ /**
127
+ * Resolve I18n options with defaults
128
+ */
129
+ function resolveI18nOptions(options) {
130
+ const detection = options?.detection;
131
+ const enabled = detection ? detection.enabled !== false : true;
132
+ const strategy = detection && "strategy" in detection ? detection.strategy ?? "cookie" : "cookie";
133
+ const prefixDefaultLocale = detection && "prefixDefaultLocale" in detection && detection.prefixDefaultLocale !== void 0 ? detection.prefixDefaultLocale : false;
134
+ return {
135
+ defaultLocale: options?.defaultLocale ?? "en",
136
+ fallbackLocale: options?.fallbackLocale ?? "en",
137
+ locales: options?.locales ?? ["en"],
138
+ detection: {
139
+ enabled,
140
+ strategy,
141
+ prefixDefaultLocale
142
+ }
143
+ };
144
+ }
145
+ /**
146
+ * Build Hono languageDetector options from I18n module options
147
+ */
148
+ function buildDetectorOptions(options) {
149
+ const resolved = resolveI18nOptions(options);
150
+ const strategy = resolved.detection.strategy;
151
+ const detectorOptions = {
152
+ order: [strategy],
153
+ fallbackLanguage: resolved.defaultLocale,
154
+ supportedLanguages: resolved.locales,
155
+ lookupCookie: "locale",
156
+ lookupQueryString: "locale",
157
+ lookupFromPathIndex: 0,
158
+ ignoreCase: true
159
+ };
160
+ if (strategy === "cookie") {
161
+ detectorOptions.caches = ["cookie"];
162
+ if (options?.detection && "cookieOptions" in options.detection && options.detection.cookieOptions) detectorOptions.cookieOptions = options.detection.cookieOptions;
163
+ } else detectorOptions.caches = false;
164
+ return detectorOptions;
165
+ }
166
+ //#endregion
167
+ //#region src/i18n/messages/index.ts
168
+ /**
169
+ * Core Messages
170
+ *
171
+ * Messages used by packages/modules infrastructure.
172
+ * These are automatically merged with application-specific messages.
173
+ */
174
+ /**
175
+ * All locale messages
176
+ * Explicitly import and export (no filesystem scanning - Cloudflare Workers compatible)
177
+ */
178
+ const messages = { en: en_exports };
179
+ /**
180
+ * Get messages for all locales
181
+ */
182
+ function getMessages() {
183
+ return messages;
184
+ }
185
+ /**
186
+ * Get available locales
187
+ */
188
+ function getLocales() {
189
+ return Object.keys(messages);
190
+ }
191
+ //#endregion
192
+ //#region src/i18n/utils/deep-merge.ts
193
+ /**
194
+ * Deep merge two objects. Source values override target at leaf level.
195
+ */
196
+ function deepMerge(target, source) {
197
+ const result = { ...target };
198
+ for (const key of Object.keys(source)) {
199
+ const targetValue = target[key];
200
+ const sourceValue = source[key];
201
+ if (typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue) && typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue)) result[key] = deepMerge(targetValue, sourceValue);
202
+ else result[key] = sourceValue;
203
+ }
204
+ return result;
205
+ }
206
+ //#endregion
207
+ //#region src/i18n/services/message-loader.service.ts
208
+ let MessageLoaderService = class MessageLoaderService {
209
+ cache;
210
+ contextCache;
211
+ locales;
212
+ defaultLocale;
213
+ constructor(registry, options) {
214
+ this.registry = registry;
215
+ this.options = options;
216
+ this.defaultLocale = this.options?.defaultLocale ?? "en";
217
+ this.cache = /* @__PURE__ */ new Map();
218
+ this.contextCache = /* @__PURE__ */ new Map();
219
+ const coreMessages = getMessages();
220
+ const coreLocales = getLocales();
221
+ const registryMessages = this.registry.getMergedMessages();
222
+ const registryLocales = Object.keys(registryMessages);
223
+ const allLocales = [...new Set([...coreLocales, ...registryLocales])];
224
+ this.locales = allLocales;
225
+ for (const locale of allLocales) {
226
+ const merged = deepMerge(coreMessages[locale] ?? {}, registryMessages[locale] ?? {});
227
+ this.cache.set(locale, merged);
228
+ }
229
+ }
230
+ /**
231
+ * Get CoreContext for a locale (lazily built and cached on first access)
232
+ * Falls back to default locale if locale not found
233
+ */
234
+ getCoreContext(locale) {
235
+ const cached = this.contextCache.get(locale);
236
+ if (cached) return cached;
237
+ const effectiveLocale = this.cache.has(locale) ? locale : this.defaultLocale;
238
+ const cachedEffective = this.contextCache.get(effectiveLocale);
239
+ if (cachedEffective) return cachedEffective;
240
+ const messages = this.cache.get(effectiveLocale) ?? {};
241
+ const flattened = this.flattenMessages(messages);
242
+ const ctx = createCoreContext({
243
+ locale: effectiveLocale,
244
+ messages: { [effectiveLocale]: flattened },
245
+ missingWarn: false,
246
+ fallbackWarn: false
247
+ });
248
+ this.contextCache.set(effectiveLocale, ctx);
249
+ return ctx;
250
+ }
251
+ /**
252
+ * Get messages for a specific locale.
253
+ * Falls back to default locale if not found.
254
+ */
255
+ getMessages(locale) {
256
+ return this.cache.get(locale) ?? this.cache.get(this.defaultLocale) ?? {};
257
+ }
258
+ /** Get list of available locale codes */
259
+ getAvailableLocales() {
260
+ return this.locales;
261
+ }
262
+ /** Check if a locale is supported */
263
+ isLocaleSupported(locale) {
264
+ return this.cache.has(locale);
265
+ }
266
+ /** Get default locale */
267
+ getDefaultLocale() {
268
+ return this.defaultLocale;
269
+ }
270
+ /**
271
+ * Get flattened (dot-notation) messages for a locale, optionally filtered by namespace prefixes.
272
+ *
273
+ * Returns flat key-value pairs matching the format used by `@intlify/core-base`'s
274
+ * `createCoreContext`. Requires `registerMessageCompiler(compile)` to be called
275
+ * before `translate()` can resolve these flat keys.
276
+ *
277
+ * @param locale - Locale code (falls back to default locale if not found)
278
+ * @param options - Optional filter configuration
279
+ * @param options.only - Dot-notation prefixes to include (e.g., `['common', 'nav.sidebar']`)
280
+ * @returns Flattened messages as `{ 'key.path': 'translated value' }`
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * // All messages for the locale
285
+ * loader.getFilteredMessages('en')
286
+ *
287
+ * // Only 'common' and 'nav' namespaces
288
+ * loader.getFilteredMessages('en', { only: ['common', 'nav'] })
289
+ *
290
+ * // Deeply nested prefix
291
+ * loader.getFilteredMessages('en', { only: ['common.actions'] })
292
+ * ```
293
+ */
294
+ getFilteredMessages(locale, options) {
295
+ const messages = this.getMessages(locale);
296
+ const flattened = this.flattenMessages(messages);
297
+ if (!options?.only?.length) return flattened;
298
+ const result = {};
299
+ for (const [key, value] of Object.entries(flattened)) if (options.only.some((prefix) => key === prefix || key.startsWith(`${prefix}.`))) result[key] = value;
300
+ return result;
301
+ }
302
+ /**
303
+ * Flatten nested messages to dot-notation.
304
+ * e.g. `{ a: { b: 'hello' } }` → `{ 'a.b': 'hello' }`
305
+ */
306
+ flattenMessages(messages, prefix = "") {
307
+ const result = {};
308
+ for (const key of Object.keys(messages)) {
309
+ const value = messages[key];
310
+ const newKey = prefix ? `${prefix}.${key}` : key;
311
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) Object.assign(result, this.flattenMessages(value, newKey));
312
+ else result[newKey] = String(value);
313
+ }
314
+ return result;
315
+ }
316
+ };
317
+ MessageLoaderService = __decorate([
318
+ Transient(I18N_TOKENS.MessageLoader),
319
+ __decorateParam(0, inject(I18N_TOKENS.MessageRegistry)),
320
+ __decorateParam(1, inject(I18N_TOKENS.Options, { isOptional: true })),
321
+ __decorateMetadata("design:paramtypes", [Object, Object])
322
+ ], MessageLoaderService);
323
+ //#endregion
324
+ //#region src/i18n/services/message-registry.ts
325
+ /**
326
+ * Global key for the shared contributions array.
327
+ *
328
+ * When stratal is installed via portal/symlink (e.g., in monorepos), bundlers
329
+ * like esbuild may inline multiple copies of this module. Each copy gets its
330
+ * own static class fields, so messages registered by one copy are invisible
331
+ * to another. Using a `Symbol.for()` key on `globalThis` ensures all copies
332
+ * share the same contributions array.
333
+ */
334
+ const CONTRIBUTIONS_KEY = Symbol.for("stratal:i18n:message-registry:contributions");
335
+ function getContributions() {
336
+ const g = globalThis;
337
+ g[CONTRIBUTIONS_KEY] ??= [];
338
+ return g[CONTRIBUTIONS_KEY];
339
+ }
340
+ let MessageRegistry = class MessageRegistry {
341
+ /**
342
+ * Add messages (called statically by I18nModule.registerMessages)
343
+ */
344
+ static addMessages(messages) {
345
+ if (Boolean(messages) && typeof messages === "object" && Object.keys(messages).length > 0) getContributions().push(messages);
346
+ }
347
+ /**
348
+ * Get all messages deep-merged in registration order
349
+ */
350
+ getMergedMessages() {
351
+ const merged = {};
352
+ for (const contribution of getContributions()) for (const locale of Object.keys(contribution)) merged[locale] = deepMerge(merged[locale] ?? {}, contribution[locale]);
353
+ return merged;
354
+ }
355
+ /**
356
+ * Reset registry (for testing)
357
+ * @internal
358
+ */
359
+ static reset() {
360
+ globalThis[CONTRIBUTIONS_KEY] = [];
361
+ }
362
+ };
363
+ MessageRegistry = __decorate([Transient(I18N_TOKENS.MessageRegistry)], MessageRegistry);
364
+ //#endregion
365
+ //#region src/openapi/services/openapi.service.ts
366
+ let OpenAPIService = class OpenAPIService {
367
+ /**
368
+ * Generate a filtered OpenAPI spec using the user's config.
369
+ * Usable from both HTTP handlers and CLI commands.
370
+ */
371
+ getSpec(app, container) {
372
+ const configService = container.resolve(OPENAPI_TOKENS.ConfigService);
373
+ const i18n = container.resolve(I18N_TOKENS.I18nService);
374
+ const config = configService.getEffectiveConfig();
375
+ const fullSpec = app.getOpenAPIDocument({
376
+ openapi: "3.0.0",
377
+ info: {
378
+ version: config.info.version,
379
+ title: config.info.title,
380
+ description: config.info.description
381
+ }
382
+ });
383
+ fullSpec.components ??= {};
384
+ fullSpec.components.securitySchemes = this.getSecuritySchemeDefinitions(i18n);
385
+ if (config.routeFilter) fullSpec.paths = this.filterRoutes(fullSpec.paths, config);
386
+ if (fullSpec.components.schemas) fullSpec.components.schemas = this.filterSchemas(fullSpec);
387
+ return fullSpec;
388
+ }
389
+ /**
390
+ * Setup OpenAPI documentation endpoints
391
+ */
392
+ setupEndpoints(app, container) {
393
+ const config = container.resolve(OPENAPI_TOKENS.ConfigService).getEffectiveConfig();
394
+ app.get(config.jsonPath, (c) => {
395
+ const requestContainer = c.get(ROUTER_CONTEXT_KEYS.REQUEST_CONTAINER);
396
+ const fullSpec = this.getSpec(app, requestContainer);
397
+ const url = new URL(c.req.raw.url);
398
+ const i18n = requestContainer.resolve(I18N_TOKENS.I18nService);
399
+ fullSpec.servers = [{
400
+ url: `${url.protocol}//${url.host}`,
401
+ description: i18n.t("common.api.serverDescription")
402
+ }];
403
+ return c.json(fullSpec);
404
+ });
405
+ this.nameLastHandler(app, "OpenAPI", "spec");
406
+ if (config.ui !== false) {
407
+ const uiPath = config.ui?.path ?? "/api/docs";
408
+ const uiRenderer = config.ui?.renderer;
409
+ app.get(uiPath, (c, next) => {
410
+ const effectiveConfig = c.get(ROUTER_CONTEXT_KEYS.REQUEST_CONTAINER).resolve(OPENAPI_TOKENS.ConfigService).getEffectiveConfig();
411
+ const uiContext = {
412
+ specUrl: effectiveConfig.jsonPath,
413
+ title: effectiveConfig.info.title
414
+ };
415
+ if (uiRenderer) return uiRenderer(uiContext)(c, next);
416
+ return swaggerUI({ url: uiContext.specUrl })(c, next);
417
+ });
418
+ this.nameLastHandler(app, "OpenAPI", "docs");
419
+ }
420
+ }
421
+ nameLastHandler(app, controller, method) {
422
+ const last = app.routes[app.routes.length - 1];
423
+ Object.defineProperty(last.handler, "name", { value: `http:${controller}.${method}` });
424
+ }
425
+ /**
426
+ * Get localized security scheme definitions
427
+ */
428
+ getSecuritySchemeDefinitions(i18n) {
429
+ return {
430
+ [SECURITY_SCHEMES.BEARER_AUTH]: {
431
+ type: "http",
432
+ scheme: "bearer",
433
+ bearerFormat: "JWT",
434
+ description: i18n.t("common.api.security.bearerAuth")
435
+ },
436
+ [SECURITY_SCHEMES.API_KEY]: {
437
+ type: "apiKey",
438
+ in: "header",
439
+ name: "X-API-Key",
440
+ description: i18n.t("common.api.security.apiKey")
441
+ },
442
+ [SECURITY_SCHEMES.SESSION_COOKIE]: {
443
+ type: "apiKey",
444
+ in: "cookie",
445
+ name: "session",
446
+ description: i18n.t("common.api.security.sessionCookie")
447
+ }
448
+ };
449
+ }
450
+ /**
451
+ * Filter OpenAPI paths using custom routeFilter
452
+ */
453
+ filterRoutes(paths, config) {
454
+ const filteredPaths = {};
455
+ for (const [path, pathItem] of Object.entries(paths)) {
456
+ if (config.routeFilter && !config.routeFilter(path, pathItem)) continue;
457
+ filteredPaths[path] = pathItem;
458
+ }
459
+ return filteredPaths;
460
+ }
461
+ /**
462
+ * Filter unreferenced schemas from OpenAPI spec
463
+ */
464
+ filterSchemas(spec) {
465
+ const referencedSchemas = /* @__PURE__ */ new Set();
466
+ this.collectSchemaRefs(spec.paths, referencedSchemas);
467
+ const filteredSchemas = {};
468
+ const components = spec.components;
469
+ if (components?.schemas) {
470
+ const allSchemas = components.schemas;
471
+ let prevSize = 0;
472
+ while (referencedSchemas.size > prevSize) {
473
+ prevSize = referencedSchemas.size;
474
+ for (const [schemaName, schemaValue] of Object.entries(allSchemas)) if (referencedSchemas.has(schemaName) && !filteredSchemas[schemaName]) {
475
+ filteredSchemas[schemaName] = schemaValue;
476
+ this.collectSchemaRefs(schemaValue, referencedSchemas);
477
+ }
478
+ }
479
+ }
480
+ return filteredSchemas;
481
+ }
482
+ /**
483
+ * Recursively collect all schema references from an object
484
+ */
485
+ collectSchemaRefs(obj, refs) {
486
+ if (!obj || typeof obj !== "object") return;
487
+ const record = obj;
488
+ if (record.$ref && typeof record.$ref === "string") {
489
+ const match = /^#\/components\/schemas\/(.+)$/.exec(record.$ref);
490
+ if (match) refs.add(match[1]);
491
+ }
492
+ if (Array.isArray(obj)) for (const item of obj) this.collectSchemaRefs(item, refs);
493
+ else for (const value of Object.values(record)) this.collectSchemaRefs(value, refs);
494
+ }
495
+ };
496
+ OpenAPIService = __decorate([Transient(OPENAPI_TOKENS.OpenAPIService)], OpenAPIService);
497
+ //#endregion
498
+ //#region src/openapi/openapi.module.ts
499
+ /**
500
+ * OpenAPI Module
501
+ *
502
+ * Provides configurable OpenAPI documentation endpoints with runtime override support.
503
+ *
504
+ * Features:
505
+ * - Configurable paths for /openapi.json and /docs
506
+ * - Runtime config overrides via middleware
507
+ * - i18n support for titles and descriptions
508
+ * - Route filtering via hideFromDocs and custom routeFilter
509
+ *
510
+ * @example Basic usage
511
+ * ```typescript
512
+ * @Module({
513
+ * imports: [
514
+ * OpenAPIModule.forRoot({
515
+ * info: { title: 'My API', version: '1.0.0' }
516
+ * })
517
+ * ]
518
+ * })
519
+ * export class AppModule {}
520
+ * ```
521
+ *
522
+ * @example With runtime override in middleware
523
+ * ```typescript
524
+ * // In RouteAccessMiddleware
525
+ * constructor(
526
+ * @inject(OPENAPI_TOKENS.ConfigService) private openAPIConfig: IOpenAPIConfigService
527
+ * ) {}
528
+ *
529
+ * async handle(ctx, next) {
530
+ * this.openAPIConfig.override({
531
+ * info: { title: 'Custom API' },
532
+ * routeFilter: (path) => this.shouldInclude(path)
533
+ * })
534
+ * await next()
535
+ * }
536
+ * ```
537
+ */
538
+ var _OpenAPIModule;
539
+ /** Default options when none provided */
540
+ const DEFAULT_OPTIONS = {
541
+ jsonPath: "/api/openapi.json",
542
+ info: {
543
+ title: "API",
544
+ version: "1.0.0"
545
+ }
546
+ };
547
+ let OpenAPIModule = _OpenAPIModule = class OpenAPIModule {
548
+ /**
549
+ * Configure OpenAPI module with static options
550
+ *
551
+ * @param options - OpenAPI configuration (paths, info, security schemes)
552
+ * @returns DynamicModule with options provider
553
+ */
554
+ static forRoot(options = {}) {
555
+ const mergedOptions = {
556
+ ...DEFAULT_OPTIONS,
557
+ ...options,
558
+ info: {
559
+ ...DEFAULT_OPTIONS.info,
560
+ ...options.info,
561
+ title: options.info?.title ?? DEFAULT_OPTIONS.info?.title ?? "API",
562
+ version: options.info?.version ?? DEFAULT_OPTIONS.info?.version ?? "1.0.0"
563
+ }
564
+ };
565
+ return {
566
+ module: _OpenAPIModule,
567
+ providers: [{
568
+ provide: OPENAPI_TOKENS.Options,
569
+ useValue: mergedOptions
570
+ }]
571
+ };
572
+ }
573
+ static forRootAsync(options) {
574
+ return {
575
+ module: _OpenAPIModule,
576
+ providers: [{
577
+ provide: OPENAPI_TOKENS.Options,
578
+ useFactory: options.useFactory,
579
+ inject: options.inject
580
+ }]
581
+ };
582
+ }
583
+ };
584
+ OpenAPIModule = _OpenAPIModule = __decorate([Module({ providers: [{
585
+ provide: OPENAPI_TOKENS.ConfigService,
586
+ useClass: OpenAPIConfigService,
587
+ scope: Scope.Request
588
+ }, {
589
+ provide: OPENAPI_TOKENS.OpenAPIService,
590
+ useClass: OpenAPIService,
591
+ scope: Scope.Singleton
592
+ }] })], OpenAPIModule);
593
+ //#endregion
594
+ //#region src/router/middleware/logger.middleware.ts
595
+ /**
596
+ * Create a Hono middleware that logs HTTP requests using our Logger service
597
+ *
598
+ * Logs request method, path, status code, and duration in milliseconds.
599
+ * Format: [HTTP] METHOD /path -> STATUS (duration ms)
600
+ *
601
+ * @param logger - Logger service instance
602
+ * @returns Hono middleware handler
603
+ *
604
+ * @example
605
+ * ```typescript
606
+ * const logger = container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)
607
+ * app.use('*', createLoggerMiddleware(logger))
608
+ * ```
609
+ */
610
+ function createLoggerMiddleware(logger) {
611
+ return async (c, next) => {
612
+ const start = Date.now();
613
+ const method = c.req.method;
614
+ const path = c.req.path;
615
+ await next();
616
+ const duration = Date.now() - start;
617
+ const status = c.res.status;
618
+ logger.info(`[HTTP] ${method} ${path} -> ${status}`, {
619
+ method,
620
+ path,
621
+ status,
622
+ duration
623
+ });
624
+ };
625
+ }
626
+ //#endregion
627
+ //#region src/router/middleware/domain.middleware.ts
628
+ /**
629
+ * Parse a domain pattern into a regex and extract parameter names.
630
+ *
631
+ * @example
632
+ * parseDomainPattern('{tenant}.example.com')
633
+ * // => { regex: /^([^.]+)\.example\.com$/, paramNames: ['tenant'] }
634
+ *
635
+ * parseDomainPattern('{region}.{tenant}.example.com')
636
+ * // => { regex: /^([^.]+)\.([^.]+)\.example\.com$/, paramNames: ['region', 'tenant'] }
637
+ */
638
+ function parseDomainPattern(pattern) {
639
+ const paramNames = [];
640
+ const escaped = pattern.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_match, paramName) => {
641
+ paramNames.push(paramName);
642
+ return "([^.]+)";
643
+ }).replace(/\./g, "\\.");
644
+ return {
645
+ regex: new RegExp(`^${escaped}$`),
646
+ paramNames
647
+ };
648
+ }
649
+ /**
650
+ * Strip port number from a host header value.
651
+ * 'example.com:8787' => 'example.com'
652
+ */
653
+ function stripPort(host) {
654
+ const colonIdx = host.lastIndexOf(":");
655
+ if (colonIdx === -1) return host;
656
+ const afterColon = host.slice(colonIdx + 1);
657
+ return /^\d+$/.test(afterColon) ? host.slice(0, colonIdx) : host;
658
+ }
659
+ /**
660
+ * Create a Hono middleware that matches the request host against a domain pattern.
661
+ *
662
+ * When the host matches, domain parameters are extracted and stored in context
663
+ * variables accessible via `ctx.domain(key)`.
664
+ *
665
+ * When the host does NOT match, throws `DomainMismatchError` (404).
666
+ *
667
+ * @param pattern - Domain pattern with `{param}` placeholders (e.g., '{tenant}.myapp.com')
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // Applied automatically by RouteRegistrationService for controllers with domain config
672
+ * @Controller('/dashboard', { domain: '{tenant}.myapp.com' })
673
+ * export class DashboardController {
674
+ * async index(ctx: RouterContext) {
675
+ * const tenant = ctx.domain('tenant')
676
+ * }
677
+ * }
678
+ * ```
679
+ */
680
+ function createDomainMiddleware(pattern) {
681
+ const { regex, paramNames } = parseDomainPattern(pattern);
682
+ return async (c, next) => {
683
+ const host = stripPort(c.req.header("host") ?? "");
684
+ const match = regex.exec(host);
685
+ if (!match) throw new DomainMismatchError();
686
+ for (let i = 0; i < paramNames.length; i++) c.set(`domain:${paramNames[i]}`, match[i + 1]);
687
+ await next();
688
+ };
689
+ }
690
+ //#endregion
691
+ //#region src/router/middleware/middleware-chain.ts
692
+ /**
693
+ * Create a Hono middleware handler that executes a chain of Stratal middleware classes.
694
+ *
695
+ * Each middleware is resolved from the request-scoped container per request,
696
+ * then executed in order (first registered = outermost in the chain).
697
+ *
698
+ * @param classes - Middleware classes to chain
699
+ * @returns Hono middleware handler
700
+ */
701
+ function createMiddlewareChain(classes) {
702
+ return async (c, next) => {
703
+ const requestContainer = c.get(ROUTER_CONTEXT_KEYS.REQUEST_CONTAINER);
704
+ const ctx = new RouterContext(c);
705
+ let current = next;
706
+ for (let i = classes.length - 1; i >= 0; i--) {
707
+ const prevNext = current;
708
+ const middleware = requestContainer.resolve(classes[i]);
709
+ current = () => middleware.handle(ctx, prevNext);
710
+ }
711
+ const result = await current();
712
+ if (result instanceof Response) return result;
713
+ };
714
+ }
715
+ //#endregion
716
+ //#region src/router/decorators/http-method.decorator.ts
717
+ /**
718
+ * Creates an HTTP method decorator factory for the given HTTP method.
719
+ *
720
+ * The returned decorator stores {@link ExplicitRouteMetadata} on the method and
721
+ * tracks the method name under {@link ROUTE_METADATA_KEYS.DECORATED_METHODS}
722
+ * on the controller prototype so they can be discovered at registration time.
723
+ */
724
+ function createHttpMethodDecorator(method) {
725
+ return function(path, config) {
726
+ return function(target, propertyKey, descriptor) {
727
+ const metadata = {
728
+ type: "explicit",
729
+ method,
730
+ path,
731
+ config: config ?? { response: z.any() }
732
+ };
733
+ Reflect.defineMetadata(ROUTE_METADATA_KEYS.ROUTE_CONFIG, metadata, target, propertyKey);
734
+ const existing = Reflect.getOwnMetadata(ROUTE_METADATA_KEYS.DECORATED_METHODS, target) ?? [];
735
+ existing.push(propertyKey);
736
+ Reflect.defineMetadata(ROUTE_METADATA_KEYS.DECORATED_METHODS, existing, target);
737
+ return descriptor;
738
+ };
739
+ };
740
+ }
741
+ /**
742
+ * Registers a GET route on the controller method.
743
+ *
744
+ * @param path - Route path relative to the controller base path
745
+ * @param config - Optional route configuration (response schema, body, params, etc.)
746
+ *
747
+ * @example
748
+ * ```typescript
749
+ * @Controller('/api/v1/users')
750
+ * class UsersController {
751
+ * @Get('/', { response: z.array(userSchema), summary: 'List users' })
752
+ * async list(ctx: RouterContext) { ... }
753
+ *
754
+ * @Get('/:id', { params: z.object({ id: z.string().uuid() }), response: userSchema })
755
+ * async getUser(ctx: RouterContext) { ... }
756
+ * }
757
+ * ```
758
+ */
759
+ const Get = createHttpMethodDecorator("get");
760
+ /**
761
+ * Registers a POST route on the controller method.
762
+ *
763
+ * @param path - Route path relative to the controller base path
764
+ * @param config - Optional route configuration (response schema, body, params, etc.)
765
+ *
766
+ * @example
767
+ * ```typescript
768
+ * @Controller('/api/v1/users')
769
+ * class UsersController {
770
+ * @Post('/', { body: createUserSchema, response: userSchema, statusCode: 201 })
771
+ * async createUser(ctx: RouterContext) { ... }
772
+ * }
773
+ * ```
774
+ */
775
+ const Post = createHttpMethodDecorator("post");
776
+ /**
777
+ * Registers a PUT route on the controller method.
778
+ *
779
+ * @param path - Route path relative to the controller base path
780
+ * @param config - Optional route configuration
781
+ */
782
+ const Put = createHttpMethodDecorator("put");
783
+ /**
784
+ * Registers a PATCH route on the controller method.
785
+ *
786
+ * @param path - Route path relative to the controller base path
787
+ * @param config - Optional route configuration
788
+ */
789
+ const Patch = createHttpMethodDecorator("patch");
790
+ /**
791
+ * Registers a DELETE route on the controller method.
792
+ *
793
+ * @param path - Route path relative to the controller base path
794
+ * @param config - Optional route configuration
795
+ */
796
+ const Delete = createHttpMethodDecorator("delete");
797
+ /**
798
+ * Registers an ALL (any HTTP method) route on the controller method.
799
+ * Routes using @All are registered without OpenAPI validation
800
+ * since OpenAPI does not support a catch-all HTTP method.
801
+ *
802
+ * @param path - Route path relative to the controller base path
803
+ * @param config - Optional route configuration
804
+ */
805
+ const All = createHttpMethodDecorator("all");
806
+ //#endregion
807
+ //#region src/router/decorators/route.decorator.ts
808
+ /**
809
+ * Decorator to add OpenAPI metadata to a controller method using convention-based routing.
810
+ *
811
+ * **Cannot be mixed with HTTP method decorators** (`@Get`, `@Post`, `@Put`, `@Patch`,
812
+ * `@Delete`, `@All`) in the same controller. Use one pattern or the other.
813
+ *
814
+ * Stores route configuration (schemas, response, tags, security) in metadata.
815
+ * HTTP method, path, and success status code are auto-derived from the method name:
816
+ * - index() → GET /base-path → 200
817
+ * - show() → GET /base-path/:id → 200
818
+ * - create() → POST /base-path → 201
819
+ * - update() → PUT /base-path/:id → 200
820
+ * - patch() → PATCH /base-path/:id → 200
821
+ * - destroy() → DELETE /base-path/:id → 200
822
+ *
823
+ * @param config - Route configuration (schemas, response, tags, security)
824
+ *
825
+ * @example
826
+ * ```typescript
827
+ * @Controller('/api/v1/notes', {
828
+ * tags: ['Notes'],
829
+ * security: ['bearerAuth']
830
+ * })
831
+ * export class NotesController implements Controller {
832
+ * @Route({
833
+ * body: createNoteSchema,
834
+ * response: noteSchema, // 201 auto-derived from 'create' method
835
+ * tags: ['Mutations'],
836
+ * description: 'Create a new note'
837
+ * })
838
+ * async create(ctx: RouterContext): Promise<Response> {
839
+ * // POST /api/v1/notes (auto-derived from method name)
840
+ * // Body schema: createNoteSchema (auto-validated)
841
+ * // Response: 201 → noteSchema (status auto-derived)
842
+ * // Tags: ['Notes', 'Mutations'] (merged with controller)
843
+ * // Security: ['bearerAuth'] (inherited from controller)
844
+ * const body = ctx.body()
845
+ * const note = await this.notesService.create(body)
846
+ * return ctx.json(note, 201)
847
+ * }
848
+ *
849
+ * @Route({
850
+ * query: paginationSchema,
851
+ * response: z.array(noteSchema) // 200 auto-derived from 'index' method
852
+ * })
853
+ * async index(ctx: RouterContext): Promise<Response> {
854
+ * // GET /api/v1/notes (auto-derived)
855
+ * // Query params auto-validated
856
+ * const notes = await this.notesService.list()
857
+ * return ctx.json(notes)
858
+ * }
859
+ *
860
+ * @Route({
861
+ * params: z.object({ id: z.string().uuid() }),
862
+ * response: {
863
+ * schema: noteSchema,
864
+ * description: 'Note details'
865
+ * },
866
+ * security: [] // Override to make public
867
+ * })
868
+ * async show(ctx: RouterContext): Promise<Response> {
869
+ * // GET /api/v1/notes/:id (auto-derived)
870
+ * // URL params auto-validated
871
+ * // Response: 200 → noteSchema (status auto-derived)
872
+ * // Security: [] (public route, override controller security)
873
+ * const id = ctx.param('id')
874
+ * const note = await this.notesService.findById(id)
875
+ * return ctx.json(note)
876
+ * }
877
+ * }
878
+ * ```
879
+ */
880
+ function Route(config) {
881
+ return function(target, propertyKey, descriptor) {
882
+ const metadata = {
883
+ type: "convention",
884
+ config
885
+ };
886
+ Reflect.defineMetadata(ROUTE_METADATA_KEYS.ROUTE_CONFIG, metadata, target, propertyKey);
887
+ const existing = Reflect.getOwnMetadata(ROUTE_METADATA_KEYS.DECORATED_METHODS, target) ?? [];
888
+ existing.push(propertyKey);
889
+ Reflect.defineMetadata(ROUTE_METADATA_KEYS.DECORATED_METHODS, existing, target);
890
+ return descriptor;
891
+ };
892
+ }
893
+ /**
894
+ * Get the route metadata from a controller method
895
+ *
896
+ * @param target - Controller instance or prototype
897
+ * @param methodName - Name of the method
898
+ * @returns Route metadata or undefined if not decorated
899
+ */
900
+ function getRouteMetadata(target, methodName) {
901
+ return Reflect.getMetadata(ROUTE_METADATA_KEYS.ROUTE_CONFIG, target, methodName);
902
+ }
903
+ /**
904
+ * Get all methods with route decorators (@Route, @Get, @Post, etc.) from a controller
905
+ *
906
+ * @param ControllerClass - Controller class
907
+ * @returns Array of method names that have route metadata
908
+ */
909
+ function getRouteDecoratedMethods(ControllerClass) {
910
+ const methods = /* @__PURE__ */ new Set();
911
+ let proto = ControllerClass.prototype;
912
+ while (proto && proto !== Object.prototype) {
913
+ const own = Reflect.getOwnMetadata(ROUTE_METADATA_KEYS.DECORATED_METHODS, proto);
914
+ if (own) for (const m of own) methods.add(m);
915
+ proto = Object.getPrototypeOf(proto);
916
+ }
917
+ return [...methods];
918
+ }
919
+ //#endregion
920
+ //#region src/router/schemas/common.schemas.ts
921
+ /**
922
+ * Common OpenAPI Schemas
923
+ *
924
+ * Reusable schema definitions for common API patterns:
925
+ * - Error responses
926
+ * - Pagination
927
+ * - Common parameters
928
+ */
929
+ /**
930
+ * Generic error response schema
931
+ * Used for all error responses (4xx, 5xx)
932
+ * Matches ApplicationError.toErrorResponse() structure
933
+ */
934
+ const errorResponseSchema = z.object({
935
+ code: z.number().int().describe("Application error code"),
936
+ message: z.string().describe("Human-readable error message"),
937
+ timestamp: z.string().datetime().describe("ISO timestamp when error occurred"),
938
+ metadata: z.record(z.string(), z.unknown()).optional().describe("Additional error context"),
939
+ stack: z.string().optional().describe("Stack trace (development only)")
940
+ }).openapi("ErrorResponse");
941
+ /**
942
+ * Validation error response schema
943
+ * Used for 400 Bad Request with validation failures
944
+ * Matches ApplicationError.toErrorResponse() structure with validation-specific metadata
945
+ */
946
+ const validationErrorResponseSchema = z.object({
947
+ code: z.number().int().describe("Application error code"),
948
+ message: z.string().describe("Human-readable error message"),
949
+ timestamp: z.string().datetime().describe("ISO timestamp when error occurred"),
950
+ metadata: z.object({ issues: z.array(z.object({
951
+ path: z.string().describe("Field path that failed validation"),
952
+ message: z.string().describe("Validation failure message"),
953
+ code: z.string().describe("Zod validation error code")
954
+ })) }).describe("Validation error details"),
955
+ stack: z.string().optional().describe("Stack trace (development only)")
956
+ }).openapi("ValidationErrorResponse");
957
+ /**
958
+ * Pagination query parameters schema
959
+ * Used for list endpoints
960
+ */
961
+ const paginationQuerySchema = z.object({
962
+ page: z.coerce.number().int().positive().default(1).describe("Page number (1-indexed)"),
963
+ limit: z.coerce.number().int().positive().max(100).default(20).describe("Items per page (max 100)")
964
+ }).openapi("PaginationQuery");
965
+ /**
966
+ * Paginated response wrapper schema
967
+ * Generic wrapper for paginated list responses
968
+ */
969
+ const paginatedResponseSchema = (itemSchema) => z.object({
970
+ data: z.array(itemSchema).describe("Array of items for current page"),
971
+ pagination: z.object({
972
+ page: z.number().int().positive().describe("Current page number"),
973
+ limit: z.number().int().positive().describe("Items per page"),
974
+ total: z.number().int().nonnegative().describe("Total number of items"),
975
+ totalPages: z.number().int().nonnegative().describe("Total number of pages")
976
+ })
977
+ });
978
+ /**
979
+ * UUID parameter schema
980
+ * Used for :id parameters in RESTful routes
981
+ */
982
+ const uuidParamSchema = z.object({ id: z.string().uuid().describe("Resource UUID") }).openapi("UUIDParam");
983
+ /**
984
+ * Success message response schema
985
+ * Used for operations that don't return data (e.g., DELETE)
986
+ */
987
+ const successMessageSchema = z.object({
988
+ message: z.string().describe("Success message"),
989
+ data: z.record(z.string(), z.unknown()).optional().describe("Optional additional data")
990
+ }).openapi("SuccessMessage");
991
+ /**
992
+ * Common HTTP status error schemas
993
+ * Pre-configured for standard error responses
994
+ */
995
+ const commonErrorSchemas = {
996
+ 400: {
997
+ schema: validationErrorResponseSchema,
998
+ description: "Validation error"
999
+ },
1000
+ 401: {
1001
+ schema: errorResponseSchema,
1002
+ description: "Unauthorized"
1003
+ },
1004
+ 403: {
1005
+ schema: errorResponseSchema,
1006
+ description: "Forbidden"
1007
+ },
1008
+ 404: {
1009
+ schema: errorResponseSchema,
1010
+ description: "Not found"
1011
+ },
1012
+ 409: {
1013
+ schema: errorResponseSchema,
1014
+ description: "Conflict"
1015
+ },
1016
+ 500: {
1017
+ schema: errorResponseSchema,
1018
+ description: "Internal server error"
1019
+ }
1020
+ };
1021
+ //#endregion
1022
+ //#region src/router/utils/path.ts
1023
+ /**
1024
+ * Path normalization and route ordering utilities.
1025
+ *
1026
+ * Users always write Hono-style `:param` paths (`:companyId`, `:id`).
1027
+ * OpenAPI requires `{param}` style — conversion happens only at registration time.
1028
+ */
1029
+ /**
1030
+ * Convert Hono-style `:param` path segments to OpenAPI-style `{param}`.
1031
+ * Strips regex constraints (e.g., `:locale{sw}` → `{locale}`).
1032
+ *
1033
+ * @example
1034
+ * toOpenAPIPath('/users/:id') // '/users/{id}'
1035
+ * toOpenAPIPath('/:companyId/users/:userId') // '/{companyId}/users/{userId}'
1036
+ * toOpenAPIPath('/users/:id/posts') // '/users/{id}/posts'
1037
+ * toOpenAPIPath('/:locale{en|fr}/users') // '/{locale}/users'
1038
+ */
1039
+ function toOpenAPIPath(path) {
1040
+ return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)(\{[^}]*\})?/g, "{$1}");
1041
+ }
1042
+ /**
1043
+ * Convert Hono-style `:param` path segments to OpenAPI-style `{param}`,
1044
+ * preserving regex constraints.
1045
+ *
1046
+ * Used for Hono route registration via `app.openapi()`. The non-greedy
1047
+ * regex in `@hono/zod-openapi` (`\/{(.+?)}/g`) converts `{param}` back
1048
+ * to `:param` while leaving the constraint suffix intact.
1049
+ *
1050
+ * @example
1051
+ * toRoutingOpenAPIPath('/:locale{sw}/users/:id') // '/{locale}{sw}/users/{id}'
1052
+ * toRoutingOpenAPIPath('/users/:id') // '/users/{id}'
1053
+ */
1054
+ function toRoutingOpenAPIPath(path) {
1055
+ return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)(\{[^}]*\})?/g, (_, name, constraint) => constraint ? `{${name}}${constraint}` : `{${name}}`);
1056
+ }
1057
+ /**
1058
+ * Compute a packed specificity key for route ordering.
1059
+ * Encodes both score and segment count into a single number to avoid object allocation.
1060
+ *
1061
+ * Lower score = higher priority (registered first in Hono).
1062
+ * Scoring: static = 0, `:param{constraint}` = 5, `:param` = 10, wildcard `{.+}` / `{.*}` = 100.
1063
+ *
1064
+ * Packed as: score * 10000 - segmentCount (negative segment count so more segments = lower key = higher priority)
1065
+ */
1066
+ function getPathSpecificityKey(path) {
1067
+ let score = 0;
1068
+ let segmentCount = 0;
1069
+ let i = 0;
1070
+ while (i < path.length) {
1071
+ if (path.charCodeAt(i) === 47) {
1072
+ i++;
1073
+ continue;
1074
+ }
1075
+ let end = path.indexOf("/", i);
1076
+ if (end === -1) end = path.length;
1077
+ segmentCount++;
1078
+ const segment = path.substring(i, end);
1079
+ if (segment.includes("{.+}") || segment.includes("{.*}")) score += 100;
1080
+ else if (segment.charCodeAt(0) === 58) score += segment.includes("{") ? 5 : 10;
1081
+ i = end;
1082
+ }
1083
+ return score * 1e4 - segmentCount;
1084
+ }
1085
+ /**
1086
+ * Compute a specificity score for route ordering.
1087
+ * Lower score = higher priority (registered first in Hono).
1088
+ *
1089
+ * Scoring: static = 0, `:param{constraint}` = 5, `:param` = 10, wildcard `{.+}` / `{.*}` = 100.
1090
+ */
1091
+ function getPathSpecificityScore(path) {
1092
+ const segments = path.split("/").filter(Boolean);
1093
+ let score = 0;
1094
+ for (const segment of segments) if (segment.includes("{.+}") || segment.includes("{.*}")) score += 100;
1095
+ else if (segment.startsWith(":") && segment.includes("{")) score += 5;
1096
+ else if (segment.startsWith(":")) score += 10;
1097
+ return score;
1098
+ }
1099
+ /**
1100
+ * Sort routes by specificity so Hono registers them in the correct order.
1101
+ *
1102
+ * 1. Static paths before parameterized before wildcards
1103
+ * 2. More segments = more specific (tie-breaker)
1104
+ * 3. Primary paths before locale-prefixed variants
1105
+ */
1106
+ function sortRoutesBySpecificity(routes) {
1107
+ const keys = /* @__PURE__ */ new Map();
1108
+ for (const route of routes) keys.set(route, getPathSpecificityKey(route.path));
1109
+ const copy = routes.slice();
1110
+ copy.sort((a, b) => keys.get(a) - keys.get(b));
1111
+ return copy;
1112
+ }
1113
+ //#endregion
1114
+ //#region src/router/utils/route-name.ts
1115
+ /**
1116
+ * Route naming utilities.
1117
+ *
1118
+ * Extracts parameter names from paths and domains,
1119
+ * and generates convention-based route names.
1120
+ */
1121
+ /**
1122
+ * Extract parameter names from a Hono-style path.
1123
+ *
1124
+ * @example
1125
+ * extractParamNames('/users/:id') // ['id']
1126
+ * extractParamNames('/:companyId/users/:userId') // ['companyId', 'userId']
1127
+ * extractParamNames('/users') // []
1128
+ */
1129
+ function extractParamNames(path) {
1130
+ if (!path.includes(":")) return [];
1131
+ return [...path.matchAll(/:([a-zA-Z_][a-zA-Z0-9_]*)/g)].map((m) => m[1]);
1132
+ }
1133
+ /**
1134
+ * Extract parameter names from a domain pattern.
1135
+ *
1136
+ * @example
1137
+ * extractDomainParamNames('{tenant}.example.com') // ['tenant']
1138
+ * extractDomainParamNames('{region}.{tenant}.example.com') // ['region', 'tenant']
1139
+ * extractDomainParamNames('example.com') // []
1140
+ */
1141
+ function extractDomainParamNames(domain) {
1142
+ if (!domain.includes("{")) return [];
1143
+ return [...domain.matchAll(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g)].map((m) => m[1]);
1144
+ }
1145
+ /**
1146
+ * Auto-generate a route name for convention-based `@Route` methods.
1147
+ *
1148
+ * Strips common prefixes (`/api/`, `/v{N}/`) and parameter segments,
1149
+ * then joins remaining static segments with dots and appends the method name.
1150
+ *
1151
+ * @example
1152
+ * generateConventionRouteName('/users', 'index') // 'users.index'
1153
+ * generateConventionRouteName('/users', 'show') // 'users.show'
1154
+ * generateConventionRouteName('/api/v1/users', 'create') // 'users.create'
1155
+ * generateConventionRouteName('/api/v1/users/:userId/notes', 'index') // 'users.notes.index'
1156
+ * generateConventionRouteName('/:companyId/users', 'index') // 'users.index'
1157
+ * generateConventionRouteName('/users/:userId/notes/:noteId/tags', 'index') // 'users.notes.tags.index'
1158
+ */
1159
+ function generateConventionRouteName(basePath, methodName) {
1160
+ const parts = basePath.split("/");
1161
+ const segments = [];
1162
+ for (const s of parts) if (s && s !== "api" && !s.startsWith(":") && !/^v\d+$/.test(s)) segments.push(s);
1163
+ if (segments.length === 0) return methodName;
1164
+ return `${segments.join(".")}.${methodName}`;
1165
+ }
1166
+ //#endregion
1167
+ //#region src/router/services/route-registration.service.ts
1168
+ const invokeHandler = (instance, method, ...args) => {
1169
+ try {
1170
+ return Promise.resolve(instance[method](...args));
1171
+ } catch (err) {
1172
+ return Promise.reject(err);
1173
+ }
1174
+ };
1175
+ let RouteRegistrationService = class RouteRegistrationService {
1176
+ controllerClasses = /* @__PURE__ */ new Map();
1177
+ upgradeWebSocketFn = null;
1178
+ constructor(logger, registry, routerResolver, localePathService, app, moduleRegistry) {
1179
+ this.logger = logger;
1180
+ this.registry = registry;
1181
+ this.routerResolver = routerResolver;
1182
+ this.localePathService = localePathService;
1183
+ this.app = app;
1184
+ this.moduleRegistry = moduleRegistry;
1185
+ }
1186
+ /**
1187
+ * Configure router with controllers and global middleware.
1188
+ * Resolves controllers from ModuleRegistry and global middleware from RouterResolver.
1189
+ */
1190
+ async configure() {
1191
+ const controllers = this.moduleRegistry.getAllControllers();
1192
+ const globalMiddleware = this.routerResolver?.getGlobalMiddleware() ?? [];
1193
+ this.logger.info("Registering controllers", { controllerCount: controllers.length });
1194
+ if (globalMiddleware.length > 0) this.app.use("*", createMiddlewareChain(globalMiddleware));
1195
+ if (controllers.some(isGateway)) {
1196
+ const { upgradeWebSocket } = await import("hono/cloudflare-workers");
1197
+ this.upgradeWebSocketFn = upgradeWebSocket;
1198
+ }
1199
+ const actions = /* @__PURE__ */ new WeakMap();
1200
+ for (const ControllerClass of controllers) this.collectRoutes(ControllerClass, actions);
1201
+ for (const route of this.registry.all()) actions.get(route)?.();
1202
+ this.logger.info("Controller registration complete");
1203
+ }
1204
+ /**
1205
+ * Pass 1: Collect routes from a controller into RouteRegistry and store Hono actions.
1206
+ * Versioning and locale expansion are handled by RouteRegistry.register().
1207
+ */
1208
+ collectRoutes(ControllerClass, actions) {
1209
+ const isWsGateway = isGateway(ControllerClass);
1210
+ const controllerRoute = getControllerRoute(ControllerClass);
1211
+ if (!controllerRoute) throw new ControllerRegistrationError(ControllerClass.name, isWsGateway ? "Missing @Gateway decorator or route metadata" : "Missing @Controller decorator or route metadata");
1212
+ const controllerOpts = getControllerOptions(ControllerClass);
1213
+ const controllerGuards = getControllerGuards(ControllerClass)?.guards ?? [];
1214
+ const routerConfig = this.routerResolver?.resolveForController(ControllerClass) ?? { middleware: [] };
1215
+ const basePath = routerConfig.prefix ? this.joinPaths(routerConfig.prefix, controllerRoute) : controllerRoute;
1216
+ const effectiveVersion = controllerOpts?.version ?? routerConfig.version;
1217
+ const effectiveDomain = controllerOpts?.domain ?? routerConfig.domain;
1218
+ if (isWsGateway) {
1219
+ const expandedRoutes = this.registry.register({
1220
+ method: "ws",
1221
+ basePath,
1222
+ version: effectiveVersion,
1223
+ domain: effectiveDomain,
1224
+ controller: ControllerClass.name,
1225
+ action: "ws",
1226
+ hidden: routerConfig.hideFromDocs ?? false,
1227
+ middleware: routerConfig.middleware.map((m) => m.name)
1228
+ });
1229
+ for (const route of expandedRoutes) actions.set(route, () => {
1230
+ if (routerConfig.middleware.length > 0) this.app.use(`${route.path}/*`, createMiddlewareChain(routerConfig.middleware));
1231
+ if (effectiveDomain) {
1232
+ const domainHandler = createDomainMiddleware(effectiveDomain);
1233
+ this.app.use(route.path, domainHandler);
1234
+ this.app.use(`${route.path}/*`, domainHandler);
1235
+ }
1236
+ this.registerGatewayForPath(ControllerClass, route.path, controllerGuards);
1237
+ });
1238
+ return;
1239
+ }
1240
+ const className = ControllerClass.name;
1241
+ this.controllerClasses.set(className, ControllerClass);
1242
+ const prototype = ControllerClass.prototype;
1243
+ if (prototype.handle) {
1244
+ const expandedRoutes = this.registry.register({
1245
+ method: "all",
1246
+ basePath,
1247
+ version: effectiveVersion,
1248
+ domain: effectiveDomain,
1249
+ controller: className,
1250
+ action: "handle",
1251
+ hidden: routerConfig.hideFromDocs ?? false,
1252
+ middleware: routerConfig.middleware.map((m) => m.name)
1253
+ });
1254
+ for (const route of expandedRoutes) actions.set(route, () => {
1255
+ if (routerConfig.middleware.length > 0) this.app.use(`${route.path}/*`, createMiddlewareChain(routerConfig.middleware));
1256
+ this.registerWildcardRoute(ControllerClass, route.path);
1257
+ });
1258
+ return;
1259
+ }
1260
+ const decoratedMethods = getRouteDecoratedMethods(ControllerClass);
1261
+ if (decoratedMethods.length === 0) throw new ControllerRegistrationError(ControllerClass.name, "No route decorators found. Use @Route() or HTTP method decorators (@Get, @Post, etc.) on controller methods.");
1262
+ const methodMetadata = [];
1263
+ let hasConvention = false;
1264
+ let hasExplicit = false;
1265
+ for (const m of decoratedMethods) {
1266
+ const meta = getRouteMetadata(prototype, m);
1267
+ if (!meta) continue;
1268
+ methodMetadata.push({
1269
+ method: m,
1270
+ meta
1271
+ });
1272
+ if (meta.type === "convention") hasConvention = true;
1273
+ else if (meta.type === "explicit") hasExplicit = true;
1274
+ }
1275
+ if (hasConvention && hasExplicit) throw new ControllerRegistrationError(ControllerClass.name, "Cannot mix @Route() with HTTP method decorators (@Get, @Post, etc.) in the same controller. Use one pattern or the other.");
1276
+ let scopedMiddlewareApplied = false;
1277
+ const routerHidden = routerConfig.hideFromDocs;
1278
+ const controllerHidden = controllerOpts?.hideFromDocs ?? false;
1279
+ const effectiveNamePrefix = controllerOpts?.name ?? routerConfig.name;
1280
+ const middlewareNames = routerConfig.middleware.map((m) => m.name);
1281
+ for (const { method: methodName, meta } of methodMetadata) {
1282
+ const resolved = this.resolveMethodAndPath(meta, methodName, basePath, className);
1283
+ if (!resolved) continue;
1284
+ const { httpMethod, fullPath, routeConfig, statusCodeOverride } = resolved;
1285
+ if (routerConfig.params) routeConfig.params = routeConfig.params ? routerConfig.params.extend(routeConfig.params.shape) : routerConfig.params;
1286
+ const hideFromDocs = routeConfig.hideFromDocs ?? routerHidden ?? controllerHidden;
1287
+ let routeName;
1288
+ if (routeConfig.name) routeName = effectiveNamePrefix ? `${effectiveNamePrefix}${routeConfig.name}` : routeConfig.name;
1289
+ else if (meta.type === "convention") {
1290
+ const autoName = generateConventionRouteName(basePath, methodName);
1291
+ routeName = effectiveNamePrefix ? `${effectiveNamePrefix}${autoName}` : autoName;
1292
+ }
1293
+ const expandedRoutes = this.registry.register({
1294
+ name: routeName,
1295
+ method: httpMethod,
1296
+ basePath: fullPath,
1297
+ version: effectiveVersion,
1298
+ domain: effectiveDomain,
1299
+ controller: className,
1300
+ action: methodName,
1301
+ hidden: hideFromDocs,
1302
+ middleware: middlewareNames
1303
+ });
1304
+ const methodGuards = getMethodGuards(prototype, methodName)?.guards ?? [];
1305
+ const allGuards = methodGuards.length > 0 ? [...controllerGuards, ...methodGuards] : controllerGuards;
1306
+ const responseSchema = httpMethod !== "all" ? this.extractResponseSchema(routeConfig) : null;
1307
+ const handler = this.createControllerHandler(ControllerClass, methodName, responseSchema);
1308
+ for (const route of expandedRoutes) actions.set(route, () => {
1309
+ if (!scopedMiddlewareApplied && routerConfig.middleware.length > 0) {
1310
+ const primaryRoute = expandedRoutes.find((r) => !r.isLocaleVariant) ?? expandedRoutes[0];
1311
+ this.app.use(`${primaryRoute.path}/*`, createMiddlewareChain(routerConfig.middleware));
1312
+ scopedMiddlewareApplied = true;
1313
+ }
1314
+ if (effectiveDomain) {
1315
+ const domainHandler = createDomainMiddleware(effectiveDomain);
1316
+ this.app.use(route.path, domainHandler);
1317
+ this.app.use(`${route.path}/*`, domainHandler);
1318
+ }
1319
+ if (allGuards.length > 0) this.logger.info(`Route guards`, {
1320
+ controller: className,
1321
+ method: httpMethod.toUpperCase(),
1322
+ path: route.path,
1323
+ methodName,
1324
+ guardCount: allGuards.length
1325
+ });
1326
+ if (httpMethod === "all") {
1327
+ this.logger.info(`Registering @All route`, {
1328
+ controller: className,
1329
+ path: route.path,
1330
+ methodName
1331
+ });
1332
+ if (allGuards.length > 0) this.app.all(route.path, this.createGuardMiddleware(allGuards), handler);
1333
+ else this.app.all(route.path, handler);
1334
+ return;
1335
+ }
1336
+ const metadata = this.mergeMetadata(controllerOpts, routeConfig, ControllerClass, methodName);
1337
+ const openApiRoute = this.buildOpenAPIRoute(httpMethod, route.path, routeConfig, metadata, allGuards, meta.type === "convention" ? methodName : void 0, statusCodeOverride, route.isLocaleVariant ?? false);
1338
+ this.logger.info(`Registering route`, {
1339
+ controller: className,
1340
+ method: httpMethod.toUpperCase(),
1341
+ path: route.path,
1342
+ methodName,
1343
+ tags: metadata.tags,
1344
+ hidden: route.hidden
1345
+ });
1346
+ this.app.openapi(openApiRoute, handler);
1347
+ if (!route.hidden) {
1348
+ const { hide: _, ...specRoute } = openApiRoute;
1349
+ this.app.openAPIRegistry.registerPath({
1350
+ ...specRoute,
1351
+ path: toOpenAPIPath(route.path)
1352
+ });
1353
+ }
1354
+ });
1355
+ }
1356
+ }
1357
+ /**
1358
+ * Register a single WebSocket gateway route
1359
+ */
1360
+ registerGatewayForPath(GatewayClass, fullPath, guards) {
1361
+ const onMsgMethod = getWsOnMessageMethod(GatewayClass);
1362
+ const onCloseMethod = getWsOnCloseMethod(GatewayClass);
1363
+ const onErrMethod = getWsOnErrorMethod(GatewayClass);
1364
+ const wsHandler = this.upgradeWebSocketFn((c) => {
1365
+ const gateway = new RouterContext(c).getContainer().resolve(GatewayClass);
1366
+ const events = {};
1367
+ const bindWsHandler = (method, onCatch) => {
1368
+ return (evt, ws) => {
1369
+ invokeHandler(gateway, method, evt, new GatewayContext(c, ws)).catch((err) => {
1370
+ this.logger.error(`WebSocket ${method} handler error`, {
1371
+ gateway: GatewayClass.name,
1372
+ error: err instanceof Error ? err.message : String(err)
1373
+ });
1374
+ onCatch?.(err, ws);
1375
+ });
1376
+ };
1377
+ };
1378
+ if (onMsgMethod) events.onMessage = bindWsHandler(onMsgMethod, (_err, ws) => ws.close(1011, "Internal Error"));
1379
+ if (onCloseMethod) events.onClose = bindWsHandler(onCloseMethod);
1380
+ if (onErrMethod) events.onError = bindWsHandler(onErrMethod);
1381
+ return events;
1382
+ });
1383
+ this.nameHandler(wsHandler, GatewayClass.name, onMsgMethod ?? "[anonymous]", "ws");
1384
+ this.logger.info("Registering WebSocket gateway", {
1385
+ gateway: GatewayClass.name,
1386
+ path: fullPath
1387
+ });
1388
+ const handlers = [];
1389
+ if (guards.length > 0) {
1390
+ this.logger.info("Gateway guards", {
1391
+ gateway: GatewayClass.name,
1392
+ path: fullPath,
1393
+ guardCount: guards.length
1394
+ });
1395
+ handlers.push(this.createGuardMiddleware(guards));
1396
+ }
1397
+ handlers.push(wsHandler);
1398
+ this.app.get(fullPath, ...handlers);
1399
+ }
1400
+ /**
1401
+ * Create a guard execution middleware
1402
+ *
1403
+ * This middleware executes all guards for a route before the handler.
1404
+ * Guards are executed in order; all must pass for the request to proceed.
1405
+ *
1406
+ * @param guards - Array of guards to execute
1407
+ * @returns Hono middleware function
1408
+ */
1409
+ createGuardMiddleware(guards) {
1410
+ const guardService = new GuardExecutionService(this.logger);
1411
+ return async (c, next) => {
1412
+ const ctx = new RouterContext(c);
1413
+ const container = ctx.getContainer();
1414
+ await guardService.executeGuards(guards, ctx, container);
1415
+ await next();
1416
+ };
1417
+ }
1418
+ /**
1419
+ * Register wildcard route for non-RESTful controllers
1420
+ */
1421
+ registerWildcardRoute(ControllerClass, route) {
1422
+ this.logger.info(`Registering wildcard route`, {
1423
+ controller: ControllerClass.name,
1424
+ route: `${route}/:path{.+}`,
1425
+ method: "ALL"
1426
+ });
1427
+ const handler = this.createControllerHandler(ControllerClass, "handle");
1428
+ this.app.all(route, handler);
1429
+ this.app.all(`${route}/:path{.+}`, handler);
1430
+ }
1431
+ /**
1432
+ * Resolve HTTP method, path, route config, and status code from route metadata.
1433
+ */
1434
+ resolveMethodAndPath(meta, methodName, basePath, className) {
1435
+ if (meta.type === "convention") {
1436
+ const derived = this.deriveHttpMethodAndPath(methodName, basePath);
1437
+ if (!derived) throw new ControllerRegistrationError(`Cannot derive HTTP method/path for convention-based route "${className}.${methodName}". Ensure the method name follows the naming convention (e.g., index, create, show).`);
1438
+ return {
1439
+ httpMethod: derived.method,
1440
+ fullPath: derived.path,
1441
+ routeConfig: meta.config,
1442
+ statusCodeOverride: meta.config.statusCode
1443
+ };
1444
+ }
1445
+ return {
1446
+ httpMethod: meta.method,
1447
+ fullPath: this.joinPaths(basePath, meta.path),
1448
+ routeConfig: meta.config,
1449
+ statusCodeOverride: meta.config.statusCode
1450
+ };
1451
+ }
1452
+ /**
1453
+ * Join a base path and a route path, normalizing slashes
1454
+ */
1455
+ joinPaths(basePath, routePath) {
1456
+ if (routePath === "/") return basePath;
1457
+ if (basePath !== "/" && basePath.endsWith("/")) basePath = basePath.slice(0, -1);
1458
+ if (routePath && !routePath.startsWith("/")) routePath = "/" + routePath;
1459
+ return basePath + routePath;
1460
+ }
1461
+ /**
1462
+ * Auto-derive HTTP method and path from controller method name
1463
+ * Uses HTTP_METHODS constant for RESTful convention mapping
1464
+ */
1465
+ deriveHttpMethodAndPath(methodName, basePath) {
1466
+ if (!(methodName in HTTP_METHODS)) return null;
1467
+ const mapping = HTTP_METHODS[methodName];
1468
+ return {
1469
+ method: mapping.method,
1470
+ path: basePath + mapping.path
1471
+ };
1472
+ }
1473
+ /**
1474
+ * Merge controller-level and route-level metadata
1475
+ * Tags are merged (appended), security is merged (union)
1476
+ * Guards automatically add sessionCookie security if present
1477
+ */
1478
+ mergeMetadata(controllerOpts, routeConfig, ControllerClass, methodName) {
1479
+ const tags = [...controllerOpts?.tags ?? [], ...routeConfig.tags ?? []];
1480
+ const prototype = ControllerClass.prototype;
1481
+ const hasMethodGuards = (getMethodGuards(prototype, methodName)?.guards.length ?? 0) > 0;
1482
+ const hasControllerGuards = (getControllerGuards(ControllerClass)?.guards.length ?? 0) > 0;
1483
+ const requiresAuth = hasMethodGuards || hasControllerGuards;
1484
+ let security = [];
1485
+ if (routeConfig.security !== void 0) security = [...controllerOpts?.security ?? [], ...routeConfig.security];
1486
+ else if (controllerOpts?.security) security = controllerOpts.security;
1487
+ if (requiresAuth && !security.includes(SECURITY_SCHEMES.SESSION_COOKIE)) security.push(SECURITY_SCHEMES.SESSION_COOKIE);
1488
+ return {
1489
+ tags,
1490
+ security: security.length > 0 ? security.map((scheme) => ({ [scheme]: [] })) : []
1491
+ };
1492
+ }
1493
+ /**
1494
+ * Build OpenAPI route configuration from metadata
1495
+ * Creates a route definition compatible with @hono/zod-openapi
1496
+ * Includes guard execution for proper access control
1497
+ *
1498
+ * Execution order: Global middlewares → Guards → Handler
1499
+ */
1500
+ buildOpenAPIRoute(method, path, routeConfig, metadata, guards, methodName, statusCodeOverride, hasLocaleParam = false) {
1501
+ try {
1502
+ const route = {
1503
+ method,
1504
+ path: toRoutingOpenAPIPath(path),
1505
+ request: {},
1506
+ responses: {},
1507
+ hide: true
1508
+ };
1509
+ if (guards.length > 0) route.middleware = [this.createGuardMiddleware(guards)];
1510
+ if (routeConfig.body) {
1511
+ const bodySchema = this.isRouteBodyObject(routeConfig.body) ? routeConfig.body.schema : routeConfig.body;
1512
+ const bodyContentType = this.isRouteBodyObject(routeConfig.body) ? routeConfig.body.contentType ?? "application/json" : DEFAULT_CONTENT_TYPE;
1513
+ route.request = {
1514
+ ...route.request,
1515
+ body: { content: { [bodyContentType]: { schema: bodySchema } } }
1516
+ };
1517
+ }
1518
+ if (routeConfig.query) route.request = {
1519
+ ...route.request,
1520
+ query: routeConfig.query
1521
+ };
1522
+ if (routeConfig.params) route.request = {
1523
+ ...route.request,
1524
+ params: routeConfig.params
1525
+ };
1526
+ const localeConfig = this.localePathService.localePathConfig;
1527
+ if (hasLocaleParam && localeConfig) {
1528
+ const localeParam = z.object({ locale: z.enum(localeConfig.prefixedLocales).openapi({ param: {
1529
+ name: "locale",
1530
+ in: "path"
1531
+ } }).optional() });
1532
+ route.request = {
1533
+ ...route.request,
1534
+ params: route.request.params ? route.request.params.extend(localeParam.shape) : localeParam
1535
+ };
1536
+ }
1537
+ const successStatus = statusCodeOverride ?? (methodName && METHOD_STATUS_CODES[methodName]) ?? 200;
1538
+ const responses = {};
1539
+ const responseDef = routeConfig.response;
1540
+ if (responseDef) if (typeof responseDef === "object" && "schema" in responseDef) responses[successStatus] = {
1541
+ content: { [responseDef.contentType ?? "application/json"]: { schema: responseDef.schema } },
1542
+ description: responseDef.description ?? `Response ${successStatus}`
1543
+ };
1544
+ else responses[successStatus] = {
1545
+ content: { [DEFAULT_CONTENT_TYPE]: { schema: responseDef } },
1546
+ description: `Response ${successStatus}`
1547
+ };
1548
+ for (const [statusStr, schema] of Object.entries(commonErrorSchemas)) {
1549
+ const status = parseInt(statusStr);
1550
+ responses[status] ??= schema;
1551
+ }
1552
+ route.responses = responses;
1553
+ if (metadata.tags.length > 0) route.tags = metadata.tags;
1554
+ if (metadata.security.length > 0) route.security = metadata.security;
1555
+ if (routeConfig.description) route.description = routeConfig.description;
1556
+ if (routeConfig.summary) route.summary = routeConfig.summary;
1557
+ return (0, validation_exports.createRoute)(route);
1558
+ } catch (error) {
1559
+ throw new OpenAPIRouteRegistrationError(path, error instanceof Error ? error.message : String(error));
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Check if a body definition is a RouteBodyObject (has schema key) vs bare ZodType
1564
+ */
1565
+ isRouteBodyObject(body) {
1566
+ return typeof body === "object" && "schema" in body;
1567
+ }
1568
+ /**
1569
+ * Resolve method parameter injections from the container
1570
+ *
1571
+ * @param prototype - Controller prototype
1572
+ * @param methodName - Method name to get injections for
1573
+ * @param container - Request-scoped container
1574
+ * @returns Array of resolved dependencies in parameter order
1575
+ */
1576
+ resolveMethodInjections(prototype, methodName, container) {
1577
+ const injections = getMethodInjections(prototype, methodName);
1578
+ if (!injections.length) return [];
1579
+ return injections.map((inj) => container.resolve(inj.token));
1580
+ }
1581
+ /**
1582
+ * Name a handler function so Hono's inspectRoutes() can identify it.
1583
+ * Format: `{type}:{Controller}.{method}` (e.g. `http:UsersController.create`)
1584
+ */
1585
+ nameHandler(fn, controller, method, type = "http") {
1586
+ Object.defineProperty(fn, "name", { value: `${type}:${controller}.${method}` });
1587
+ }
1588
+ /**
1589
+ * Create controller handler that resolves controller from request-scoped container
1590
+ * This ensures each request gets a fresh controller with request-scoped context
1591
+ */
1592
+ createControllerHandler(ControllerClass, methodName, responseSchema = null) {
1593
+ const handler = async (c) => {
1594
+ const ctx = new RouterContext(c);
1595
+ const requestContainer = ctx.getContainer();
1596
+ const controller = requestContainer.resolve(ControllerClass);
1597
+ const method = controller[methodName];
1598
+ if (typeof method === "function") {
1599
+ const injectedArgs = this.resolveMethodInjections(ControllerClass.prototype, methodName, requestContainer);
1600
+ const response = await method.apply(controller, [ctx, ...injectedArgs]);
1601
+ if (responseSchema && c.env.ENVIRONMENT !== "production") return this.validateResponse(response, responseSchema);
1602
+ return response;
1603
+ }
1604
+ throw new ControllerMethodNotFoundError(methodName, ControllerClass.name);
1605
+ };
1606
+ this.nameHandler(handler, ControllerClass.name, methodName);
1607
+ return handler;
1608
+ }
1609
+ /**
1610
+ * Extract the Zod schema from a RouteResponse definition.
1611
+ * Returns null for non-JSON content types or when no response is defined.
1612
+ */
1613
+ extractResponseSchema(routeConfig) {
1614
+ const responseDef = routeConfig.response;
1615
+ if (!responseDef) return null;
1616
+ if (this.isRouteResponseObject(responseDef)) {
1617
+ if (!(responseDef.contentType ?? "application/json").includes("application/json")) return null;
1618
+ return responseDef.schema;
1619
+ }
1620
+ return responseDef;
1621
+ }
1622
+ /**
1623
+ * Check if a response definition is a RouteResponseObject (has schema key) vs bare ZodType
1624
+ */
1625
+ isRouteResponseObject(response) {
1626
+ return typeof response === "object" && "schema" in response;
1627
+ }
1628
+ /**
1629
+ * Validate a Response body against its declared Zod schema.
1630
+ *
1631
+ * Skips validation for:
1632
+ * - Non-JSON content types
1633
+ * - Empty bodies (204 No Content, 304 Not Modified)
1634
+ *
1635
+ * Clones the response to read the body without consuming the original stream.
1636
+ */
1637
+ async validateResponse(response, schema) {
1638
+ const contentType = response.headers.get("content-type");
1639
+ if (!contentType || !contentType.includes("application/json")) return response;
1640
+ if (response.status === 204 || response.status === 304) return response;
1641
+ const cloned = response.clone();
1642
+ let body;
1643
+ try {
1644
+ body = await cloned.json();
1645
+ } catch {
1646
+ return response;
1647
+ }
1648
+ const result = schema.safeParse(body);
1649
+ if (!result.success) throw new ResponseValidationError(result.error);
1650
+ return response;
1651
+ }
1652
+ };
1653
+ RouteRegistrationService = __decorate([
1654
+ Transient(),
1655
+ __decorateParam(0, inject(LOGGER_TOKENS.LoggerService)),
1656
+ __decorateParam(1, inject(ROUTER_TOKENS.RouteRegistry)),
1657
+ __decorateParam(2, inject(ROUTER_TOKENS.RouterResolver)),
1658
+ __decorateParam(3, inject(ROUTER_TOKENS.LocalePathService)),
1659
+ __decorateParam(4, inject(ROUTER_TOKENS.HonoApp)),
1660
+ __decorateParam(5, inject(DI_TOKENS.ModuleRegistry)),
1661
+ __decorateMetadata("design:paramtypes", [
1662
+ Object,
1663
+ Object,
1664
+ Object,
1665
+ Object,
1666
+ Object,
1667
+ Object
1668
+ ])
1669
+ ], RouteRegistrationService);
1670
+ //#endregion
1671
+ //#region src/router/hono-app.ts
1672
+ const isMiddlewareClass = (arg) => typeof arg === "function" && arg.prototype && "handle" in arg.prototype;
1673
+ let HonoApp = class HonoApp extends OpenAPIHono {
1674
+ configured = false;
1675
+ _container;
1676
+ _logger;
1677
+ /**
1678
+ * Reference to the original Hono `use` implementation.
1679
+ * Captured in constructor after super() sets it as an instance property.
1680
+ * Used by private methods to register middleware without going through the override.
1681
+ */
1682
+ nativeUse;
1683
+ constructor(container, logger) {
1684
+ super({ defaultHook: (result, c) => {
1685
+ if (!result.success) throw new SchemaValidationError(result.error);
1686
+ const override = c.get("validationSuccessResponse");
1687
+ if (override) return override;
1688
+ } });
1689
+ this._container = container;
1690
+ this._logger = logger;
1691
+ this.nativeUse = this.use;
1692
+ this.use = ((...args) => {
1693
+ if (isMiddlewareClass(args[0])) {
1694
+ this.nativeUse("*", createMiddlewareChain(args));
1695
+ return this;
1696
+ }
1697
+ if (typeof args[0] === "string" && args.length > 1 && isMiddlewareClass(args[1])) {
1698
+ this.nativeUse(args[0], createMiddlewareChain(args.slice(1)));
1699
+ return this;
1700
+ }
1701
+ return this.nativeUse(...args);
1702
+ });
1703
+ this.setupRequestScope();
1704
+ this.applyGlobalMiddleware();
1705
+ }
1706
+ /**
1707
+ * Apply global middleware (logger + error handler).
1708
+ * Called by Application after locale middleware is applied by LocalePathService.
1709
+ */
1710
+ applyGlobalMiddleware() {
1711
+ this.nativeUse("*", createLoggerMiddleware(this._logger));
1712
+ this.onError((err, c) => this.handleException(c, err));
1713
+ }
1714
+ /**
1715
+ * Configure OpenAPI endpoints, controller routes, and 404 handler.
1716
+ * Called once by Application.initialize().
1717
+ */
1718
+ async configure() {
1719
+ if (this.configured) throw new HonoAppAlreadyConfiguredError();
1720
+ this._container.resolve(OPENAPI_TOKENS.OpenAPIService).setupEndpoints(this, this._container);
1721
+ await this._container.resolve(RouteRegistrationService).configure();
1722
+ this.notFound((c) => {
1723
+ throw new RouteNotFoundError(c.req.path, c.req.method);
1724
+ });
1725
+ this.configured = true;
1726
+ }
1727
+ setupRequestScope() {
1728
+ this.nativeUse("*", async (c, next) => {
1729
+ const routerContext = new RouterContext(c);
1730
+ const requestContainer = this._container.createRequestScope(routerContext);
1731
+ c.set(ROUTER_CONTEXT_KEYS.REQUEST_CONTAINER, requestContainer);
1732
+ await runWithContainer(requestContainer, next);
1733
+ });
1734
+ }
1735
+ handleException(c, err) {
1736
+ const handler = (c.get(ROUTER_CONTEXT_KEYS.REQUEST_CONTAINER) ?? this._container).resolve(DI_TOKENS.ExceptionHandler);
1737
+ const ctx = createHttpExceptionContext(c);
1738
+ return handler.handle(err, ctx);
1739
+ }
1740
+ };
1741
+ HonoApp = __decorate([
1742
+ Transient(),
1743
+ __decorateParam(0, inject(CONTAINER_TOKEN)),
1744
+ __decorateParam(1, inject(LOGGER_TOKENS.LoggerService)),
1745
+ __decorateMetadata("design:paramtypes", [Object, Object])
1746
+ ], HonoApp);
1747
+ //#endregion
1748
+ //#region src/router/services/locale-path.service.ts
1749
+ let LocalePathService = class LocalePathService {
1750
+ _config;
1751
+ _pathDetectionEnabled;
1752
+ _prefixDefaultLocale;
1753
+ constructor(container, honoApp) {
1754
+ this.honoApp = honoApp;
1755
+ const i18nOptions = container.isRegistered(I18N_TOKENS.Options) ? container.resolve(I18N_TOKENS.Options) : void 0;
1756
+ const detection = i18nOptions?.detection;
1757
+ const detectionEnabled = detection ? detection.enabled !== false : true;
1758
+ const strategy = (detection && "strategy" in detection && detection.strategy) ?? "cookie";
1759
+ this._pathDetectionEnabled = detectionEnabled && strategy === "path";
1760
+ this._prefixDefaultLocale = detection && "prefixDefaultLocale" in detection && detection.prefixDefaultLocale !== void 0 ? detection.prefixDefaultLocale : false;
1761
+ if (this._pathDetectionEnabled) {
1762
+ const allLocales = i18nOptions?.locales ?? ["en"];
1763
+ const defaultLocale = i18nOptions?.defaultLocale ?? "en";
1764
+ this._config = this._prefixDefaultLocale === true ? {
1765
+ allLocales,
1766
+ prefixedLocales: allLocales,
1767
+ defaultLocale: null
1768
+ } : {
1769
+ allLocales,
1770
+ prefixedLocales: allLocales.filter((l) => l !== defaultLocale),
1771
+ defaultLocale
1772
+ };
1773
+ } else this._config = null;
1774
+ if (detectionEnabled) this.setupLanguageDetection(i18nOptions);
1775
+ if (this._config?.defaultLocale && this._prefixDefaultLocale === "redirect") this.setupDefaultLocaleRedirect(this._config.defaultLocale);
1776
+ }
1777
+ /** Whether path-based locale detection is enabled */
1778
+ get enabled() {
1779
+ return this._pathDetectionEnabled;
1780
+ }
1781
+ /** The computed locale path config, or null if path detection is disabled */
1782
+ get localePathConfig() {
1783
+ return this._config;
1784
+ }
1785
+ /** The prefixDefaultLocale setting (false, true, or 'redirect') */
1786
+ get prefixDefaultLocale() {
1787
+ return this._prefixDefaultLocale;
1788
+ }
1789
+ /**
1790
+ * Expand a path into primary + locale-prefixed variants.
1791
+ *
1792
+ * @param path - The base path to expand
1793
+ * @returns Array of resolved paths with locale metadata
1794
+ */
1795
+ resolve(path) {
1796
+ if (!this._config) return [{
1797
+ path,
1798
+ isLocaleVariant: false
1799
+ }];
1800
+ const constraint = this.buildLocaleConstraint();
1801
+ const suffix = path === "/" ? "" : path;
1802
+ if (this._config.defaultLocale === null) return [{
1803
+ path: `/:locale${constraint}${suffix}`,
1804
+ isLocaleVariant: true
1805
+ }];
1806
+ const result = [{
1807
+ path,
1808
+ isLocaleVariant: false
1809
+ }];
1810
+ if (this._config.prefixedLocales.length > 0) result.push({
1811
+ path: `/:locale${constraint}${suffix}`,
1812
+ isLocaleVariant: true
1813
+ });
1814
+ return result;
1815
+ }
1816
+ /**
1817
+ * Build a Hono regex constraint from prefixed locales.
1818
+ * e.g., `{en|de|fr}` — restricts `:locale` to only match known values.
1819
+ */
1820
+ buildLocaleConstraint() {
1821
+ return `{${(this._config.defaultLocale === null ? this._config.allLocales : this._config.prefixedLocales).join("|")}}`;
1822
+ }
1823
+ /**
1824
+ * Apply Hono's languageDetector middleware and bridge the detected language
1825
+ * to Stratal's LOCALE context variable.
1826
+ */
1827
+ setupLanguageDetection(i18nOptions) {
1828
+ const detectorOptions = buildDetectorOptions(i18nOptions);
1829
+ this.honoApp.use("*", languageDetector(detectorOptions));
1830
+ this.honoApp.use("*", async (c, next) => {
1831
+ const language = c.get("language");
1832
+ if (language) c.set(ROUTER_CONTEXT_KEYS.LOCALE, language);
1833
+ await next();
1834
+ });
1835
+ }
1836
+ /**
1837
+ * Redirect requests that include the default locale prefix to the unprefixed path.
1838
+ * For example, `/en/users` → 301 redirect to `/users`.
1839
+ *
1840
+ * Only active when `prefixDefaultLocale` is `'redirect'`.
1841
+ */
1842
+ setupDefaultLocaleRedirect(defaultLocale) {
1843
+ const prefix = `/${defaultLocale}`;
1844
+ this.honoApp.use("*", async (c, next) => {
1845
+ const path = new URL(c.req.url).pathname;
1846
+ if (path === prefix || path.startsWith(`${prefix}/`)) {
1847
+ const stripped = path.slice(prefix.length) || "/";
1848
+ return c.redirect(stripped, 301);
1849
+ }
1850
+ await next();
1851
+ });
1852
+ }
1853
+ };
1854
+ LocalePathService = __decorate([
1855
+ Transient(),
1856
+ __decorateParam(0, inject(CONTAINER_TOKEN)),
1857
+ __decorateParam(1, inject(ROUTER_TOKENS.HonoApp)),
1858
+ __decorateMetadata("design:paramtypes", [Object, Object])
1859
+ ], LocalePathService);
1860
+ //#endregion
1861
+ //#region src/router/services/versioning.service.ts
1862
+ let VersioningService = class VersioningService {
1863
+ options;
1864
+ constructor(app) {
1865
+ this.options = app.config.versioning ?? null;
1866
+ }
1867
+ /** Whether versioning is enabled */
1868
+ get enabled() {
1869
+ return this.options !== null;
1870
+ }
1871
+ /**
1872
+ * Resolve versioned paths for a base path.
1873
+ *
1874
+ * @param basePath - The base path (e.g., '/users')
1875
+ * @param version - Explicit version from controller/router config
1876
+ * @returns Array of versioned path strings (e.g., ['/v1/users', '/v2/users'])
1877
+ */
1878
+ resolve(basePath, version) {
1879
+ if (!this.options) return [basePath];
1880
+ if (version === VERSION_NEUTRAL) return [basePath];
1881
+ const prefix = this.options.prefix ?? "v";
1882
+ if (version !== void 0) return (Array.isArray(version) ? version : [version]).map((v) => `/${prefix}${v}${basePath}`);
1883
+ if (this.options.defaultVersion !== void 0) return (Array.isArray(this.options.defaultVersion) ? this.options.defaultVersion : [this.options.defaultVersion]).map((v) => `/${prefix}${v}${basePath}`);
1884
+ return [basePath];
1885
+ }
1886
+ };
1887
+ VersioningService = __decorate([
1888
+ Transient(),
1889
+ __decorateParam(0, inject(DI_TOKENS.Application)),
1890
+ __decorateMetadata("design:paramtypes", [Object])
1891
+ ], VersioningService);
1892
+ //#endregion
1893
+ //#region src/router/route-registry.ts
1894
+ let RouteRegistry = class RouteRegistry {
1895
+ routes = [];
1896
+ namedRoutes = /* @__PURE__ */ new Map();
1897
+ _sortedCache = null;
1898
+ constructor(versioningService, localePathService) {
1899
+ this.versioningService = versioningService;
1900
+ this.localePathService = localePathService;
1901
+ }
1902
+ /**
1903
+ * Register a route. Expands via VersioningService + LocalePathService.
1904
+ * Named routes must have unique names.
1905
+ *
1906
+ * @returns Array of expanded RegisteredRoute entries (primary + locale variants)
1907
+ * @throws DuplicateRouteNameError if a named route with the same name already exists
1908
+ */
1909
+ register(input) {
1910
+ const domainParamNames = input.domainParamNames ?? (input.domain ? extractDomainParamNames(input.domain) : []);
1911
+ const versionedPaths = this.versioningService.resolve(input.basePath, input.version);
1912
+ const expandedRoutes = [];
1913
+ const localeEnabled = this.localePathService.enabled;
1914
+ for (const versionedPath of versionedPaths) {
1915
+ const resolvedPaths = this.localePathService.resolve(versionedPath);
1916
+ let localeVariantPaths;
1917
+ if (localeEnabled) {
1918
+ const variants = resolvedPaths.filter((p) => p.isLocaleVariant);
1919
+ localeVariantPaths = variants.length > 0 ? variants.map((p) => p.path) : void 0;
1920
+ }
1921
+ for (const resolved of resolvedPaths) {
1922
+ const route = {
1923
+ name: resolved.isLocaleVariant ? void 0 : input.name,
1924
+ method: input.method,
1925
+ path: resolved.path,
1926
+ localePaths: resolved.isLocaleVariant ? void 0 : localeVariantPaths,
1927
+ paramNames: extractParamNames(resolved.path),
1928
+ domain: input.domain,
1929
+ domainParamNames,
1930
+ controller: input.controller,
1931
+ action: input.action,
1932
+ hidden: input.hidden,
1933
+ middleware: input.middleware,
1934
+ isLocaleVariant: resolved.isLocaleVariant || void 0
1935
+ };
1936
+ if (route.name) {
1937
+ if (this.namedRoutes.has(route.name)) {
1938
+ const existing = this.namedRoutes.get(route.name);
1939
+ throw new DuplicateRouteNameError(route.name, `${existing.controller}.${existing.action}`, `${route.controller}.${route.action}`);
1940
+ }
1941
+ this.namedRoutes.set(route.name, route);
1942
+ }
1943
+ this.routes.push(route);
1944
+ expandedRoutes.push(route);
1945
+ }
1946
+ }
1947
+ this._sortedCache = null;
1948
+ return expandedRoutes;
1949
+ }
1950
+ /** Get a named route by name */
1951
+ get(name) {
1952
+ return this.namedRoutes.get(name);
1953
+ }
1954
+ /** Check if a named route exists */
1955
+ has(name) {
1956
+ return this.namedRoutes.has(name);
1957
+ }
1958
+ /** Get all routes sorted by specificity (static > param > wildcard, primary before locale) */
1959
+ all() {
1960
+ this._sortedCache ??= sortRoutesBySpecificity(this.routes);
1961
+ return this._sortedCache;
1962
+ }
1963
+ /** Get only named routes */
1964
+ named() {
1965
+ return [...this.namedRoutes.values()];
1966
+ }
1967
+ };
1968
+ RouteRegistry = __decorate([
1969
+ Transient(),
1970
+ __decorateParam(0, inject(ROUTER_TOKENS.VersioningService)),
1971
+ __decorateParam(1, inject(ROUTER_TOKENS.LocalePathService)),
1972
+ __decorateMetadata("design:paramtypes", [Object, Object])
1973
+ ], RouteRegistry);
1974
+ //#endregion
1975
+ //#region src/router/signed-url.ts
1976
+ /**
1977
+ * Import a signing key for HMAC-SHA256.
1978
+ */
1979
+ async function importKey(secret) {
1980
+ const encoder = new TextEncoder();
1981
+ return crypto.subtle.importKey("raw", encoder.encode(secret), {
1982
+ name: "HMAC",
1983
+ hash: "SHA-256"
1984
+ }, false, ["sign", "verify"]);
1985
+ }
1986
+ /**
1987
+ * Encode an ArrayBuffer as base64url (URL-safe base64).
1988
+ */
1989
+ function toBase64Url(buffer) {
1990
+ const bytes = new Uint8Array(buffer);
1991
+ let binary = "";
1992
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1993
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1994
+ }
1995
+ /**
1996
+ * Sign a URL with HMAC-SHA256.
1997
+ *
1998
+ * Appends `signature` and optionally `expires` query parameters.
1999
+ * The signature covers the pathname + search (excluding the signature params themselves).
2000
+ *
2001
+ * @param url - Full URL or path to sign
2002
+ * @param secret - HMAC secret key (e.g., from env.APP_SECRET)
2003
+ * @param options - Optional expiration
2004
+ * @returns URL string with `signature` (and `expires`) query params appended
2005
+ */
2006
+ async function signUrl(url, secret, options) {
2007
+ const parsedUrl = new URL(url, "https://placeholder.local");
2008
+ const key = await importKey(secret);
2009
+ if (options?.expiresIn) {
2010
+ const expires = Math.floor(Date.now() / 1e3) + options.expiresIn;
2011
+ parsedUrl.searchParams.set("expires", String(expires));
2012
+ }
2013
+ const dataToSign = `${parsedUrl.pathname}?${parsedUrl.searchParams.toString()}`;
2014
+ const encoder = new TextEncoder();
2015
+ const signature = toBase64Url(await crypto.subtle.sign("HMAC", key, encoder.encode(dataToSign)));
2016
+ parsedUrl.searchParams.set("signature", signature);
2017
+ return url.startsWith("http") ? parsedUrl.toString() : `${parsedUrl.pathname}?${parsedUrl.searchParams.toString()}`;
2018
+ }
2019
+ /**
2020
+ * Verify a signed URL using `crypto.subtle.verify()` (timing-attack-safe).
2021
+ *
2022
+ * @param url - Full URL or path with signature query param
2023
+ * @param secret - HMAC secret key (same key used for signing)
2024
+ * @returns true if signature is valid and not expired
2025
+ */
2026
+ async function verifySignedUrl(url, secret) {
2027
+ const parsedUrl = new URL(url, "https://placeholder.local");
2028
+ const signature = parsedUrl.searchParams.get("signature");
2029
+ if (!signature) return false;
2030
+ const expires = parsedUrl.searchParams.get("expires");
2031
+ if (expires) {
2032
+ const expiryTime = parseInt(expires, 10);
2033
+ if (isNaN(expiryTime) || Math.floor(Date.now() / 1e3) > expiryTime) return false;
2034
+ }
2035
+ parsedUrl.searchParams.delete("signature");
2036
+ const dataToVerify = `${parsedUrl.pathname}?${parsedUrl.searchParams.toString()}`;
2037
+ const base64 = signature.replace(/-/g, "+").replace(/_/g, "/");
2038
+ const binaryStr = atob(base64);
2039
+ const signatureBytes = new Uint8Array(binaryStr.length);
2040
+ for (let i = 0; i < binaryStr.length; i++) signatureBytes[i] = binaryStr.charCodeAt(i);
2041
+ const key = await importKey(secret);
2042
+ const encoder = new TextEncoder();
2043
+ return crypto.subtle.verify("HMAC", key, signatureBytes, encoder.encode(dataToVerify));
2044
+ }
2045
+ //#endregion
2046
+ //#region src/router/uri.ts
2047
+ /**
2048
+ * Build a URL from a registered route, filling path/domain params and appending extras as query string.
2049
+ *
2050
+ * Pure function — no request context needed. Used by both the `Uri` class and the standalone `route()` function.
2051
+ *
2052
+ * @param route - The registered route to build a URL for
2053
+ * @param name - Route name (used in error messages)
2054
+ * @param params - Path params, domain params, and extra query params
2055
+ * @returns Relative URL string (or absolute with domain prefix if route has a domain pattern)
2056
+ *
2057
+ * @throws MissingRouteParamError if a required path or domain param is missing
2058
+ */
2059
+ function buildRouteUrl(route, name, params) {
2060
+ const allParams = { ...params };
2061
+ const consumedKeys = /* @__PURE__ */ new Set();
2062
+ let url = route.path;
2063
+ if (allParams.locale && route.localePaths?.length) {
2064
+ url = `/${allParams.locale}${url === "/" ? "" : url}`;
2065
+ consumedKeys.add("locale");
2066
+ }
2067
+ for (const paramName of route.paramNames) {
2068
+ const value = allParams[paramName];
2069
+ if (value === void 0) throw new MissingRouteParamError(paramName, name, route.path);
2070
+ url = url.replace(new RegExp(`:${paramName}(\\{[^}]*\\})?`), encodeURIComponent(value));
2071
+ consumedKeys.add(paramName);
2072
+ }
2073
+ let domain;
2074
+ if (route.domain) {
2075
+ domain = route.domain;
2076
+ for (const domainParam of route.domainParamNames) {
2077
+ const value = allParams[domainParam];
2078
+ if (value === void 0) throw new MissingRouteParamError(domainParam, name, route.domain);
2079
+ domain = domain.replace(`{${domainParam}}`, encodeURIComponent(value));
2080
+ consumedKeys.add(domainParam);
2081
+ }
2082
+ }
2083
+ const queryEntries = Object.entries(allParams).filter(([key]) => !consumedKeys.has(key));
2084
+ if (queryEntries.length > 0) {
2085
+ const queryString = queryEntries.filter(([, value]) => Boolean(value)).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
2086
+ url = `${url}${queryString.length ? `?${queryString}` : ""}`;
2087
+ }
2088
+ if (domain) url = `https://${domain}${url}`;
2089
+ return url;
2090
+ }
2091
+ let Uri = class Uri {
2092
+ _defaults = {};
2093
+ constructor(registry, routerContext) {
2094
+ this.registry = registry;
2095
+ this.routerContext = routerContext;
2096
+ }
2097
+ /**
2098
+ * Set default URL parameters for this request.
2099
+ * Applied to all subsequent `route()` calls — explicit params override defaults.
2100
+ *
2101
+ * @param params - Default parameters (e.g., `{ locale: 'en' }`)
2102
+ */
2103
+ defaults(params) {
2104
+ this._defaults = {
2105
+ ...this._defaults,
2106
+ ...params
2107
+ };
2108
+ }
2109
+ /**
2110
+ * Generate a URL from a named route.
2111
+ *
2112
+ * Keys matching `:param` placeholders fill the path.
2113
+ * Domain params (`{tenant}`) are consumed from the same object.
2114
+ * Extra keys become query string parameters.
2115
+ * Default params (from `defaults()`) are merged — explicit params override.
2116
+ *
2117
+ * @param name - Named route identifier
2118
+ * @param params - Route params + domain params + extra query params
2119
+ * @param options - URL generation options
2120
+ * @returns Generated URL string
2121
+ *
2122
+ * @throws RouteNameNotFoundError if route name not found
2123
+ * @throws MissingRouteParamError if required params missing
2124
+ */
2125
+ route(name, params, options) {
2126
+ const registeredRoute = this.registry.get(name);
2127
+ if (!registeredRoute) throw new RouteNameNotFoundError(name);
2128
+ let url = buildRouteUrl(registeredRoute, name, {
2129
+ ...this._defaults,
2130
+ ...params
2131
+ });
2132
+ if (options?.absolute && !url.startsWith("http")) url = `${new URL(this.routerContext.c.req.url).origin}${url}`;
2133
+ return url;
2134
+ }
2135
+ /**
2136
+ * Generate a signed URL from a named route.
2137
+ *
2138
+ * @param name - Named route identifier
2139
+ * @param params - Route params + domain params + extra query params
2140
+ * @param options - Signing options (e.g., expiresIn) and URL options
2141
+ * @returns Signed URL string with signature query param
2142
+ *
2143
+ * @throws Error if APP_SECRET environment variable is not set
2144
+ */
2145
+ async signedRoute(name, params, options) {
2146
+ return signUrl(this.route(name, params, options), this.getAppSecret(), options);
2147
+ }
2148
+ /**
2149
+ * Generate a temporary signed URL from a named route.
2150
+ *
2151
+ * @param name - Named route identifier
2152
+ * @param expiresIn - Time-to-live in seconds
2153
+ * @param params - Route params + domain params + extra query params
2154
+ * @param options - URL generation options
2155
+ * @returns Signed URL string with signature and expires query params
2156
+ *
2157
+ * @throws Error if APP_SECRET environment variable is not set
2158
+ */
2159
+ async temporarySignedRoute(name, expiresIn, params, options) {
2160
+ return this.signedRoute(name, params, {
2161
+ ...options,
2162
+ expiresIn
2163
+ });
2164
+ }
2165
+ /**
2166
+ * Check if the current request has a valid signature.
2167
+ *
2168
+ * @returns true if the URL signature is valid and not expired
2169
+ */
2170
+ async hasValidSignature() {
2171
+ const secret = this.routerContext.c.env.APP_SECRET;
2172
+ if (!secret) return false;
2173
+ return verifySignedUrl(this.routerContext.c.req.url, secret);
2174
+ }
2175
+ /**
2176
+ * Get the current request URL pathname (without query string).
2177
+ */
2178
+ current() {
2179
+ return new URL(this.routerContext.c.req.url).pathname;
2180
+ }
2181
+ /**
2182
+ * Get the current request URL with query string (pathname + search).
2183
+ */
2184
+ full() {
2185
+ const parsed = new URL(this.routerContext.c.req.url);
2186
+ return `${parsed.pathname}${parsed.search}`;
2187
+ }
2188
+ /**
2189
+ * Get the previous request URL from the Referer header.
2190
+ *
2191
+ * @param fallback - URL to return if no Referer header (default: '/')
2192
+ */
2193
+ previous(fallback = "/") {
2194
+ return this.routerContext.c.req.header("referer") ?? fallback;
2195
+ }
2196
+ /**
2197
+ * Get the previous request URL pathname (no query string or host) from the Referer header.
2198
+ *
2199
+ * @param fallback - Path to return if no Referer header (default: '/')
2200
+ */
2201
+ previousPath(fallback = "/") {
2202
+ const referer = this.routerContext.c.req.header("referer");
2203
+ if (!referer) return fallback;
2204
+ try {
2205
+ return new URL(referer).pathname;
2206
+ } catch {
2207
+ return referer;
2208
+ }
2209
+ }
2210
+ /**
2211
+ * Build a URL to a raw path (not a named route) with optional query params.
2212
+ *
2213
+ * @param path - URL path (e.g., '/users')
2214
+ * @param queryParams - Query parameters to append
2215
+ * @param options - URL generation options
2216
+ */
2217
+ to(path, queryParams, options) {
2218
+ let url = path;
2219
+ if (queryParams) {
2220
+ const entries = Object.entries(queryParams);
2221
+ if (entries.length > 0) {
2222
+ const queryString = entries.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
2223
+ url = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
2224
+ }
2225
+ }
2226
+ if (options?.absolute && !url.startsWith("http")) url = `${new URL(this.routerContext.c.req.url).origin}${url}`;
2227
+ return url;
2228
+ }
2229
+ /**
2230
+ * Build a URL with query string parameters. Merges with existing query params in path.
2231
+ *
2232
+ * @param path - URL path, may already contain query params
2233
+ * @param queryParams - Query parameters to merge (new values override existing)
2234
+ */
2235
+ query(path, queryParams) {
2236
+ const parsed = new URL(path, "https://placeholder.local");
2237
+ for (const [key, value] of Object.entries(queryParams)) parsed.searchParams.set(key, value);
2238
+ return `${parsed.pathname}${parsed.search}`;
2239
+ }
2240
+ getAppSecret() {
2241
+ const secret = this.routerContext.c.env.APP_SECRET;
2242
+ if (!secret) throw new Error("APP_SECRET environment variable is required for signed URLs");
2243
+ return secret;
2244
+ }
2245
+ };
2246
+ Uri = __decorate([
2247
+ Transient(),
2248
+ __decorateParam(0, inject(ROUTER_TOKENS.RouteRegistry)),
2249
+ __decorateParam(1, inject(ROUTER_TOKENS.RouterContext)),
2250
+ __decorateMetadata("design:paramtypes", [Object, Object])
2251
+ ], Uri);
2252
+ //#endregion
2253
+ //#region src/router/route-url.ts
2254
+ /**
2255
+ * Generate a URL from a named route.
2256
+ *
2257
+ * Keys in `params` matching `:param` placeholders fill the path.
2258
+ * Domain params (`{tenant}`) are also consumed from `params`.
2259
+ * Extra keys become query string parameters.
2260
+ *
2261
+ * Resolves RouteRegistry from the application container via AsyncLocalStorage.
2262
+ * Available after `Application.initialize()` has been called.
2263
+ *
2264
+ * @param name - Named route identifier
2265
+ * @param params - Route params + domain params + extra query params
2266
+ * @returns Generated URL string
2267
+ *
2268
+ * @example
2269
+ * ```typescript
2270
+ * // In a controller (preferred):
2271
+ * ctx.route('users.show', { id: '1' })
2272
+ *
2273
+ * // Outside controllers (standalone function):
2274
+ * import { route } from 'stratal/router'
2275
+ *
2276
+ * route('users.show', { id: '1' })
2277
+ * ```
2278
+ */
2279
+ function route(name, params) {
2280
+ const registeredRoute = getContainer().resolve(ROUTER_TOKENS.RouteRegistry).get(name);
2281
+ if (!registeredRoute) throw new RouteNameNotFoundError(name);
2282
+ return buildRouteUrl(registeredRoute, name, params);
2283
+ }
2284
+ //#endregion
2285
+ //#region src/router/middleware/verify-signature.middleware.ts
2286
+ /**
2287
+ * Middleware that verifies signed URLs.
2288
+ *
2289
+ * Checks the `signature` (and optionally `expires`) query params against the
2290
+ * request URL using HMAC-SHA256 via `crypto.subtle.verify()`.
2291
+ *
2292
+ * Requires `APP_SECRET` in the Cloudflare Workers environment bindings.
2293
+ *
2294
+ * @throws InvalidSignatureError (403) if signature is missing, invalid, or expired
2295
+ *
2296
+ * @example
2297
+ * ```typescript
2298
+ * @Module({ controllers: [UnsubscribeController], providers: [VerifySignatureMiddleware] })
2299
+ * export class EmailModule implements RouteConfigurable {
2300
+ * configureRoutes(router: Router): void {
2301
+ * router.middleware(VerifySignatureMiddleware)
2302
+ * }
2303
+ * }
2304
+ * ```
2305
+ */
2306
+ var VerifySignatureMiddleware = class {
2307
+ async handle(ctx, next) {
2308
+ const url = ctx.c.req.url;
2309
+ const secret = ctx.c.env.APP_SECRET;
2310
+ if (!secret) throw new MissingEnvironmentVariableError("APP_SECRET");
2311
+ if (!await verifySignedUrl(url, secret)) throw new InvalidSignatureError();
2312
+ await next();
2313
+ }
2314
+ };
2315
+ //#endregion
2316
+ //#region src/i18n/services/i18n.service.ts
2317
+ /**
2318
+ * I18n Service
2319
+ *
2320
+ * Request-scoped service for translations.
2321
+ * Injects RouterContext to access request-specific locale.
2322
+ * Uses pre-built CoreContext from MessageLoaderService (singleton) for zero-cost lookups.
2323
+ */
2324
+ let I18nService = class I18nService {
2325
+ constructor(loader, routerContext) {
2326
+ this.loader = loader;
2327
+ this.routerContext = routerContext;
2328
+ }
2329
+ /**
2330
+ * Translate a message key
2331
+ *
2332
+ * @param key - Message key (e.g., 'common.actions.save')
2333
+ * @param params - Optional parameters for interpolation
2334
+ * @returns Translated string
2335
+ */
2336
+ t(key, params) {
2337
+ const context = this.loader.getCoreContext(this.getLocale());
2338
+ const result = params !== void 0 ? translate(context, key, params) : translate(context, key);
2339
+ return typeof result === "string" ? result : key;
2340
+ }
2341
+ /**
2342
+ * Get current locale
2343
+ *
2344
+ * @returns Current locale code from RouterContext or default locale
2345
+ */
2346
+ getLocale() {
2347
+ return this.routerContext?.getLocale() ?? "en";
2348
+ }
2349
+ };
2350
+ I18nService = __decorate([
2351
+ Transient(I18N_TOKENS.I18nService),
2352
+ __decorateParam(0, inject(I18N_TOKENS.MessageLoader)),
2353
+ __decorateParam(1, inject(ROUTER_TOKENS.RouterContext, { isOptional: true })),
2354
+ __decorateMetadata("design:paramtypes", [Object, Object])
2355
+ ], I18nService);
2356
+ //#endregion
2357
+ //#region src/i18n/i18n.module.ts
2358
+ /**
2359
+ * I18n Module
2360
+ *
2361
+ * Core infrastructure module for internationalization.
2362
+ * Provides message translation and locale handling.
2363
+ *
2364
+ * - `forRoot()` configures locale settings (call once in root module)
2365
+ * - `registerMessages()` adds translations (call from any module, as many times as needed)
2366
+ *
2367
+ * @example
2368
+ * ```typescript
2369
+ * @Module({
2370
+ * imports: [
2371
+ * I18nModule.forRoot({ defaultLocale: 'en', locales: ['en', 'fr'] }),
2372
+ * I18nModule.registerMessages(appMessages),
2373
+ * ],
2374
+ * })
2375
+ * export class AppModule {}
2376
+ * ```
2377
+ *
2378
+ * @example Package contributing messages
2379
+ * ```typescript
2380
+ * @Module({
2381
+ * imports: [
2382
+ * I18nModule.registerMessages(tenancyMessages),
2383
+ * ],
2384
+ * })
2385
+ * export class TenancyModule {}
2386
+ * ```
2387
+ */
2388
+ var _I18nModule;
2389
+ setupI18nCompiler();
2390
+ z.config({ customError: backendErrorMap });
2391
+ let I18nModule = _I18nModule = class I18nModule {
2392
+ /**
2393
+ * Configure I18n locale settings
2394
+ *
2395
+ * Call once in the root module. Does not accept messages —
2396
+ * use `registerMessages()` to add translations.
2397
+ *
2398
+ * @param options - Locale configuration (defaultLocale, fallbackLocale, locales)
2399
+ */
2400
+ static forRoot(options = {}) {
2401
+ return {
2402
+ module: _I18nModule,
2403
+ providers: [{
2404
+ provide: I18N_TOKENS.Options,
2405
+ useValue: options
2406
+ }]
2407
+ };
2408
+ }
2409
+ /**
2410
+ * Register i18n messages
2411
+ *
2412
+ * Can be called from any module, as many times as needed.
2413
+ * Messages are deep-merged in registration order — later calls override earlier ones at leaf level.
2414
+ *
2415
+ * @param messages - Messages keyed by locale code
2416
+ *
2417
+ * @example App-level messages
2418
+ * ```typescript
2419
+ * I18nModule.registerMessages({
2420
+ * en: { common: { hello: 'Hello' }, errors: { notFound: 'Not found' } },
2421
+ * fr: { common: { hello: 'Bonjour' }, errors: { notFound: 'Introuvable' } },
2422
+ * })
2423
+ * ```
2424
+ *
2425
+ * @example Package-level messages
2426
+ * ```typescript
2427
+ * I18nModule.registerMessages({
2428
+ * en: { tenancy: { tenantNotFound: 'Tenant not found' } },
2429
+ * })
2430
+ * ```
2431
+ */
2432
+ static registerMessages(messages) {
2433
+ MessageRegistry.addMessages(messages);
2434
+ return {
2435
+ module: _I18nModule,
2436
+ providers: []
2437
+ };
2438
+ }
2439
+ configureRoutes(router) {
2440
+ router.use(I18nContextMiddleware);
2441
+ }
2442
+ };
2443
+ I18nModule = _I18nModule = __decorate([Module({ providers: [
2444
+ {
2445
+ provide: I18N_TOKENS.MessageRegistry,
2446
+ useClass: MessageRegistry,
2447
+ scope: Scope.Singleton
2448
+ },
2449
+ {
2450
+ provide: I18N_TOKENS.MessageLoader,
2451
+ useClass: MessageLoaderService,
2452
+ scope: Scope.Singleton
2453
+ },
2454
+ {
2455
+ provide: I18N_TOKENS.I18nService,
2456
+ useClass: I18nService
2457
+ }
2458
+ ] })], I18nModule);
2459
+ //#endregion
2460
+ export { Delete as A, MessageRegistry as B, successMessageSchema as C, getRouteDecoratedMethods as D, Route as E, createMiddlewareChain as F, buildDetectorOptions as G, getLocales as H, createDomainMiddleware as I, LocaleNotSupportedError as J, resolveI18nOptions as K, parseDomainPattern as L, Patch as M, Post as N, getRouteMetadata as O, Put as P, OpenAPIModule as R, paginationQuerySchema as S, validationErrorResponseSchema as T, getMessages as U, MessageLoaderService as V, messages as W, I18nContextMiddleware as X, OpenAPIConfigService as Y, sortRoutesBySpecificity as _, buildRouteUrl as a, errorResponseSchema as b, RouteRegistry as c, HonoApp as d, RouteRegistrationService as f, getPathSpecificityScore as g, generateConventionRouteName as h, Uri as i, Get as j, All as k, VersioningService as l, extractParamNames as m, VerifySignatureMiddleware as n, signUrl as o, extractDomainParamNames as p, TranslationMissingError as q, route as r, verifySignedUrl as s, I18nModule as t, LocalePathService as u, toOpenAPIPath as v, uuidParamSchema as w, paginatedResponseSchema as x, commonErrorSchemas as y, OpenAPIService as z };
2461
+
2462
+ //# sourceMappingURL=i18n.module-BpLLLCTg.mjs.map