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