@guren/server 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/dist/{McpServiceProvider-7BB5FPF3.js → McpServiceProvider-GRDYNEQG.js} +1 -1
  2. package/dist/auth/AuthManager.d.ts +30 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +25 -0
  4. package/dist/auth/RequestAuthContext.d.ts +24 -0
  5. package/dist/auth/SessionGuard.d.ts +31 -0
  6. package/dist/auth/api-token.d.ts +299 -0
  7. package/dist/auth/email-verification.d.ts +203 -0
  8. package/dist/auth/index.d.ts +18 -110
  9. package/dist/auth/index.js +3 -1
  10. package/dist/auth/oauth/index.d.ts +239 -0
  11. package/dist/auth/password/DefaultHasher.d.ts +13 -0
  12. package/dist/auth/password/NodeHasher.d.ts +22 -0
  13. package/dist/auth/password/PasswordHasher.d.ts +5 -0
  14. package/dist/auth/password/ScryptHasher.d.ts +26 -0
  15. package/dist/auth/password-reset.d.ts +91 -0
  16. package/dist/auth/providers/ModelUserProvider.d.ts +36 -0
  17. package/dist/auth/providers/UserProvider.d.ts +9 -0
  18. package/dist/auth/types.d.ts +102 -0
  19. package/dist/auth/utils.d.ts +39 -0
  20. package/dist/{Gate-CynjZCtS.d.ts → authorization/Gate.d.ts} +30 -111
  21. package/dist/authorization/Policy.d.ts +77 -0
  22. package/dist/authorization/index.d.ts +5 -129
  23. package/dist/authorization/index.js +3 -1
  24. package/dist/authorization/middleware.d.ts +49 -0
  25. package/dist/authorization/types.d.ts +108 -0
  26. package/dist/broadcasting/BroadcastManager.d.ts +205 -0
  27. package/dist/broadcasting/channels/Channel.d.ts +28 -0
  28. package/dist/broadcasting/channels/PresenceChannel.d.ts +72 -0
  29. package/dist/broadcasting/channels/PrivateChannel.d.ts +32 -0
  30. package/dist/broadcasting/channels/index.d.ts +3 -0
  31. package/dist/broadcasting/drivers/MemoryDriver.d.ts +93 -0
  32. package/dist/broadcasting/drivers/RedisDriver.d.ts +112 -0
  33. package/dist/broadcasting/drivers/index.d.ts +2 -0
  34. package/dist/broadcasting/index.d.ts +6 -233
  35. package/dist/broadcasting/index.js +1 -1
  36. package/dist/broadcasting/typed.d.ts +23 -0
  37. package/dist/broadcasting/types.d.ts +155 -0
  38. package/dist/cache/CacheManager.d.ts +87 -0
  39. package/dist/cache/TaggedCache.d.ts +62 -0
  40. package/dist/cache/index.d.ts +6 -233
  41. package/dist/cache/index.js +1 -1
  42. package/dist/cache/stores/FileStore.d.ts +64 -0
  43. package/dist/cache/stores/MemoryStore.d.ts +52 -0
  44. package/dist/cache/stores/RedisStore.d.ts +53 -0
  45. package/dist/{CacheManager-BmDzUKrF.d.ts → cache/types.d.ts} +26 -99
  46. package/dist/{chunk-TVY72CLV.js → chunk-4VE3LYOM.js} +3 -2
  47. package/dist/{chunk-FZD2AKJI.js → chunk-7OB2YXRE.js} +56 -28
  48. package/dist/{chunk-J6ETA476.js → chunk-BUQXOZCT.js} +93 -5
  49. package/dist/{chunk-DSDX3ASM.js → chunk-CDZUNKI6.js} +65 -83
  50. package/dist/{chunk-CWI4AJ47.js → chunk-HPET6XY5.js} +13 -9
  51. package/dist/{chunk-A3ISJVEV.js → chunk-HR2KZ3WL.js} +23 -5
  52. package/dist/{chunk-5SZTEZ22.js → chunk-PZKUDFMW.js} +11 -8
  53. package/dist/console/Command.d.ts +179 -0
  54. package/dist/{ConsoleKernel-CJg975mp.d.ts → console/ConsoleKernel.d.ts} +4 -6
  55. package/dist/console/Input.d.ts +140 -0
  56. package/dist/console/Output.d.ts +161 -0
  57. package/dist/console/index.d.ts +5 -0
  58. package/dist/console/types.d.ts +106 -0
  59. package/dist/container/Container.d.ts +148 -0
  60. package/dist/container/ServiceProvider.d.ts +103 -0
  61. package/dist/container/bindings.d.ts +55 -0
  62. package/dist/container/defineModule.d.ts +88 -0
  63. package/dist/container/definePlugin.d.ts +62 -0
  64. package/dist/container/index.d.ts +8 -0
  65. package/dist/container/types.d.ts +73 -0
  66. package/dist/database/Factory.d.ts +82 -0
  67. package/dist/database/Seeder.d.ts +35 -0
  68. package/dist/database/SeederRunner.d.ts +41 -0
  69. package/dist/database/index.d.ts +4 -0
  70. package/dist/database/types.d.ts +49 -0
  71. package/dist/discovery/AutoDiscovery.d.ts +113 -0
  72. package/dist/discovery/index.d.ts +2 -0
  73. package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +12 -0
  74. package/dist/docs-viewer/endpoint.d.ts +19 -0
  75. package/dist/encryption/Encrypter.d.ts +96 -0
  76. package/dist/encryption/Hash.d.ts +69 -0
  77. package/dist/encryption/MessageSigner.d.ts +21 -0
  78. package/dist/encryption/Random.d.ts +119 -0
  79. package/dist/encryption/app-key.d.ts +12 -0
  80. package/dist/encryption/index.d.ts +10 -222
  81. package/dist/encryption/signed-url.d.ts +9 -0
  82. package/dist/encryption/types.d.ts +103 -0
  83. package/dist/errors/ExceptionHandler.d.ts +118 -0
  84. package/dist/errors/HttpException.d.ts +106 -0
  85. package/dist/errors/debug-page.d.ts +22 -0
  86. package/dist/errors/error-page.d.ts +1 -0
  87. package/dist/errors/exceptions/AuthenticationException.d.ts +32 -0
  88. package/dist/errors/exceptions/AuthorizationException.d.ts +32 -0
  89. package/dist/errors/exceptions/MethodNotAllowedException.d.ts +31 -0
  90. package/dist/errors/exceptions/NotFoundHttpException.d.ts +36 -0
  91. package/dist/errors/exceptions/ValidationException.d.ts +60 -0
  92. package/dist/errors/exceptions/index.d.ts +5 -0
  93. package/dist/errors/index.d.ts +5 -0
  94. package/dist/errors/types.d.ts +43 -0
  95. package/dist/events/Event.d.ts +33 -0
  96. package/dist/{EventManager-CmIoLt7r.d.ts → events/EventManager.d.ts} +4 -86
  97. package/dist/events/Listener.d.ts +79 -0
  98. package/dist/events/builtin.d.ts +73 -0
  99. package/dist/events/index.d.ts +6 -155
  100. package/dist/events/types.d.ts +48 -0
  101. package/dist/facades/index.d.ts +31 -0
  102. package/dist/health/HealthCheck.d.ts +34 -0
  103. package/dist/health/HealthManager.d.ts +53 -0
  104. package/dist/health/checks/CacheCheck.d.ts +35 -0
  105. package/dist/health/checks/CustomCheck.d.ts +23 -0
  106. package/dist/health/checks/DatabaseCheck.d.ts +33 -0
  107. package/dist/health/checks/MemoryCheck.d.ts +32 -0
  108. package/dist/health/checks/RedisCheck.d.ts +27 -0
  109. package/dist/health/checks/StorageCheck.d.ts +35 -0
  110. package/dist/health/checks/index.d.ts +12 -0
  111. package/dist/health/index.d.ts +5 -185
  112. package/dist/health/types.d.ts +52 -0
  113. package/dist/hot-reload/hot-disposables.d.ts +96 -0
  114. package/dist/hot-reload/testing.d.ts +14 -0
  115. package/dist/http/Application.d.ts +187 -0
  116. package/dist/http/FormRequest.d.ts +73 -0
  117. package/dist/http/dev-assets.d.ts +51 -0
  118. package/dist/http/dev-banner.d.ts +7 -0
  119. package/dist/http/inertia-assets.d.ts +22 -0
  120. package/dist/http/middleware/auth.d.ts +13 -0
  121. package/dist/http/middleware/capabilities.d.ts +22 -0
  122. package/dist/http/middleware/cors.d.ts +40 -0
  123. package/dist/http/middleware/csp.d.ts +59 -0
  124. package/dist/http/middleware/csrf.d.ts +121 -0
  125. package/dist/http/middleware/detect-locale.d.ts +65 -0
  126. package/dist/http/middleware/force-https.d.ts +34 -0
  127. package/dist/http/middleware/host-authorization.d.ts +24 -0
  128. package/dist/http/middleware/index.d.ts +19 -0
  129. package/dist/http/middleware/loopback-guard.d.ts +38 -0
  130. package/dist/{rate-limit-D9J2b4S1.d.ts → http/middleware/rate-limit.d.ts} +22 -50
  131. package/dist/http/middleware/redirect-safety.d.ts +29 -0
  132. package/dist/http/middleware/request-id.d.ts +19 -0
  133. package/dist/http/middleware/request-logging.d.ts +16 -0
  134. package/dist/http/middleware/security-headers.d.ts +49 -0
  135. package/dist/http/middleware/session.d.ts +93 -0
  136. package/dist/http/middleware/validation.d.ts +94 -0
  137. package/dist/http/public-assets.d.ts +15 -0
  138. package/dist/http/request.d.ts +24 -0
  139. package/dist/http/resources/CursorPaginator.d.ts +106 -0
  140. package/dist/http/resources/Paginator.d.ts +130 -0
  141. package/dist/http/resources/Resource.d.ts +67 -0
  142. package/dist/http/resources/ResourceCollection.d.ts +60 -0
  143. package/dist/http/resources/index.d.ts +6 -0
  144. package/dist/http/resources/types.d.ts +91 -0
  145. package/dist/http/validation/Validator.d.ts +128 -0
  146. package/dist/http/validation/index.d.ts +3 -0
  147. package/dist/http/validation/rules.d.ts +196 -0
  148. package/dist/http/validation/types.d.ts +96 -0
  149. package/dist/http/vite-dev-server.d.ts +27 -0
  150. package/dist/i18n/I18nManager.d.ts +114 -0
  151. package/dist/i18n/Translator.d.ts +80 -0
  152. package/dist/i18n/index.d.ts +6 -101
  153. package/dist/i18n/index.js +5 -3
  154. package/dist/i18n/loaders/JsonLoader.d.ts +47 -0
  155. package/dist/i18n/loaders/MemoryLoader.d.ts +37 -0
  156. package/dist/i18n/pluralization.d.ts +19 -0
  157. package/dist/i18n/types.d.ts +106 -0
  158. package/dist/index.d.ts +69 -2605
  159. package/dist/index.js +332 -152
  160. package/dist/lambda/index.d.ts +17 -37
  161. package/dist/logging/LogManager.d.ts +83 -0
  162. package/dist/logging/Logger.d.ts +76 -0
  163. package/dist/logging/channels/ConsoleChannel.d.ts +11 -0
  164. package/dist/logging/channels/DailyFileChannel.d.ts +20 -0
  165. package/dist/logging/channels/FileChannel.d.ts +15 -0
  166. package/dist/logging/index.d.ts +8 -50
  167. package/dist/logging/types.d.ts +96 -0
  168. package/dist/mail/Mail.d.ts +138 -0
  169. package/dist/mail/MailManager.d.ts +79 -0
  170. package/dist/mail/address.d.ts +8 -0
  171. package/dist/mail/index.d.ts +7 -316
  172. package/dist/mail/transports/LogTransport.d.ts +19 -0
  173. package/dist/mail/transports/MemoryTransport.d.ts +84 -0
  174. package/dist/mail/transports/ResendTransport.d.ts +32 -0
  175. package/dist/mail/transports/SmtpTransport.d.ts +40 -0
  176. package/dist/{MailManager-DpMvYiP9.d.ts → mail/types.d.ts} +11 -92
  177. package/dist/mcp/McpServiceProvider.d.ts +17 -0
  178. package/dist/mcp/create-mcp-server.d.ts +144 -0
  179. package/dist/mcp/endpoint.d.ts +29 -0
  180. package/dist/mcp/index.d.ts +3 -185
  181. package/dist/mcp/index.js +1 -1
  182. package/dist/mvc/Controller.d.ts +326 -0
  183. package/dist/mvc/Router.d.ts +239 -0
  184. package/dist/mvc/ViewEngine.d.ts +11 -0
  185. package/dist/mvc/inertia/InertiaEngine.d.ts +114 -0
  186. package/dist/mvc/inertia/shared.d.ts +90 -0
  187. package/dist/mvc/mount-route.d.ts +10 -0
  188. package/dist/notifications/Notification.d.ts +99 -0
  189. package/dist/notifications/NotificationManager.d.ts +150 -0
  190. package/dist/notifications/channels/DatabaseChannel.d.ts +55 -0
  191. package/dist/notifications/channels/MailChannel.d.ts +45 -0
  192. package/dist/notifications/channels/MemoryChannel.d.ts +85 -0
  193. package/dist/notifications/channels/SlackChannel.d.ts +73 -0
  194. package/dist/notifications/channels/index.d.ts +4 -0
  195. package/dist/notifications/index.d.ts +6 -322
  196. package/dist/notifications/notifiable-type.d.ts +10 -0
  197. package/dist/notifications/registry.d.ts +39 -0
  198. package/dist/notifications/types.d.ts +162 -0
  199. package/dist/providers/AuthServiceProvider.d.ts +7 -0
  200. package/dist/providers/AuthorizationServiceProvider.d.ts +9 -0
  201. package/dist/providers/BroadcastServiceProvider.d.ts +7 -0
  202. package/dist/providers/CacheServiceProvider.d.ts +7 -0
  203. package/dist/providers/EncryptionServiceProvider.d.ts +7 -0
  204. package/dist/providers/ErrorServiceProvider.d.ts +9 -0
  205. package/dist/providers/EventServiceProvider.d.ts +7 -0
  206. package/dist/providers/HealthServiceProvider.d.ts +7 -0
  207. package/dist/providers/I18nServiceProvider.d.ts +27 -0
  208. package/dist/providers/InertiaServiceProvider.d.ts +20 -0
  209. package/dist/providers/LogServiceProvider.d.ts +7 -0
  210. package/dist/providers/MailServiceProvider.d.ts +7 -0
  211. package/dist/providers/NotificationServiceProvider.d.ts +8 -0
  212. package/dist/providers/OAuthServiceProvider.d.ts +7 -0
  213. package/dist/providers/QueueServiceProvider.d.ts +7 -0
  214. package/dist/providers/SchedulingServiceProvider.d.ts +7 -0
  215. package/dist/providers/StorageServiceProvider.d.ts +7 -0
  216. package/dist/providers/index.d.ts +17 -0
  217. package/dist/queue/FailedJobReporter.d.ts +40 -0
  218. package/dist/queue/Job.d.ts +140 -0
  219. package/dist/queue/QueueManager.d.ts +79 -0
  220. package/dist/queue/Worker.d.ts +99 -0
  221. package/dist/queue/drivers/MemoryDriver.d.ts +60 -0
  222. package/dist/queue/drivers/RedisDriver.d.ts +96 -0
  223. package/dist/queue/drivers/SqsDriver.d.ts +108 -0
  224. package/dist/queue/drivers/SyncDriver.d.ts +28 -0
  225. package/dist/queue/index.d.ts +9 -453
  226. package/dist/queue/types.d.ts +171 -0
  227. package/dist/redis/RedisApiTokenStore.d.ts +78 -0
  228. package/dist/redis/RedisEmailVerificationStore.d.ts +54 -0
  229. package/dist/redis/RedisOAuthStateStore.d.ts +26 -0
  230. package/dist/redis/RedisPasswordResetStore.d.ts +57 -0
  231. package/dist/redis/RedisRateLimitStore.d.ts +77 -0
  232. package/dist/redis/RedisSessionStore.d.ts +61 -0
  233. package/dist/redis/client.d.ts +41 -0
  234. package/dist/redis/index.d.ts +14 -356
  235. package/dist/redis/index.js +5 -2
  236. package/dist/redis/scan-keys.d.ts +6 -0
  237. package/dist/runtime/index.d.ts +8 -95
  238. package/dist/runtime/index.js +1 -1
  239. package/dist/scheduling/CronParser.d.ts +37 -0
  240. package/dist/scheduling/Schedule.d.ts +229 -0
  241. package/dist/scheduling/ScheduledTask.d.ts +47 -0
  242. package/dist/scheduling/Scheduler.d.ts +99 -0
  243. package/dist/scheduling/index.d.ts +5 -41
  244. package/dist/scheduling/types.d.ts +97 -0
  245. package/dist/storage/StorageManager.d.ts +65 -0
  246. package/dist/storage/drivers/LocalDriver.d.ts +55 -0
  247. package/dist/storage/drivers/MemoryDriver.d.ts +66 -0
  248. package/dist/storage/drivers/S3Driver.d.ts +72 -0
  249. package/dist/storage/index.d.ts +5 -197
  250. package/dist/{StorageManager-oZTHqaza.d.ts → storage/types.d.ts} +10 -77
  251. package/dist/support/error-polyfill.d.ts +9 -0
  252. package/dist/support/import-map.d.ts +13 -0
  253. package/dist/support/redirect-target.d.ts +11 -0
  254. package/dist/support/stack-frames.d.ts +56 -0
  255. package/dist/support/trim-slashes.d.ts +11 -0
  256. package/dist/vite/index.d.ts +2 -35
  257. package/dist/vite/index.js +0 -3
  258. package/dist/vite/plugin.d.ts +34 -0
  259. package/package.json +3 -3
  260. package/dist/AuthManager-DBP4KYsx.d.ts +0 -79
  261. package/dist/BroadcastManager-D8KoJxiV.d.ts +0 -492
  262. package/dist/HealthManager-DUyMIzsZ.d.ts +0 -141
  263. package/dist/I18nManager-BiSoczfV.d.ts +0 -275
  264. package/dist/LogManager-7mxnkaPM.d.ts +0 -256
  265. package/dist/Scheduler-pZiT8i57.d.ts +0 -471
  266. package/dist/api-token-D24VPr_E.d.ts +0 -663
  267. package/dist/app-key-CsBfRC_Q.d.ts +0 -214
  268. package/dist/email-verification-Dx426KLn.d.ts +0 -336
  269. package/dist/index-9_Jzj5jo.d.ts +0 -7
  270. package/dist/validation-yAL53e1S.d.ts +0 -2610
@@ -1,2610 +0,0 @@
1
- import * as hono from 'hono';
2
- import { Context, MiddlewareHandler, Hono, Next, ExecutionContext } from 'hono';
3
- import { l as OAuthManager, g as AuthContext, j as ApiToken, C as CreateSessionMiddlewareOptions } from './api-token-D24VPr_E.js';
4
- import { A as AuthManager } from './AuthManager-DBP4KYsx.js';
5
- import { InlineConfig, ViteDevServer } from 'vite';
6
- import { E as EventManager } from './EventManager-CmIoLt7r.js';
7
- import { C as CacheManager } from './CacheManager-BmDzUKrF.js';
8
- import { M as MailManager } from './MailManager-DpMvYiP9.js';
9
- import { L as LogManager } from './LogManager-7mxnkaPM.js';
10
- import { I as I18nManager } from './I18nManager-BiSoczfV.js';
11
- import { B as BroadcastManager } from './BroadcastManager-D8KoJxiV.js';
12
- import { E as Encrypter, A as AppKeyring } from './app-key-CsBfRC_Q.js';
13
- import { S as StorageManager } from './StorageManager-oZTHqaza.js';
14
- import { H as HealthManager } from './HealthManager-DUyMIzsZ.js';
15
- import { S as Scheduler } from './Scheduler-pZiT8i57.js';
16
- import { G as Gate } from './Gate-CynjZCtS.js';
17
- import { M as Middleware } from './index-9_Jzj5jo.js';
18
-
19
- declare const CSRF_TOKEN_KEY = "_csrf_token";
20
- declare const CSRF_HEADER_NAME = "X-CSRF-TOKEN";
21
- declare const CSRF_FORM_FIELD = "_token";
22
- interface CsrfOptions {
23
- /**
24
- * Routes to exclude from CSRF protection.
25
- * Supports exact paths ('/api/webhook') or patterns ('/api/*').
26
- */
27
- exclude?: string[];
28
- /**
29
- * Custom error handler when CSRF validation fails.
30
- * Defaults to returning a 403 JSON response.
31
- */
32
- onError?: (ctx: Context) => Response | Promise<Response>;
33
- /**
34
- * HTTP methods that require CSRF token validation.
35
- * Defaults to ['POST', 'PUT', 'PATCH', 'DELETE'].
36
- */
37
- methods?: string[];
38
- /**
39
- * Set the CSRF token as an `XSRF-TOKEN` cookie on every response.
40
- * This enables Axios/Inertia.js to automatically read the cookie
41
- * and send it back as the `X-XSRF-TOKEN` header.
42
- * Defaults to true.
43
- */
44
- cookie?: boolean;
45
- /**
46
- * Cookie options when `cookie` is enabled.
47
- */
48
- cookieOptions?: {
49
- path?: string;
50
- secure?: boolean;
51
- sameSite?: 'Strict' | 'Lax' | 'None';
52
- };
53
- }
54
- /**
55
- * Get the request's CSRF token.
56
- *
57
- * Signed token bound to the session when a stable one exists, otherwise a
58
- * stateless signed double-submit token for guests. Nothing is stored
59
- * server-side, so anonymous page views cost no session writes. A cookie
60
- * token that is still valid for this request's mode is reused; otherwise a
61
- * fresh token is minted and set on the response by the middleware.
62
- */
63
- declare function getCsrfToken(ctx: Context): string;
64
- /**
65
- * Generate an HTML hidden input field containing the CSRF token.
66
- */
67
- declare function csrfField(ctx: Context): string;
68
- /**
69
- * Verify a request token.
70
- *
71
- * The token must first carry a valid app-key signature (proving this server
72
- * minted it). Then, by mode:
73
- * - **Session-bound** (token carries a `sid`): the id must match the live
74
- * session. This is immune to cookie injection — a sibling-subdomain
75
- * attacker can plant a cookie but cannot know the victim's session id.
76
- * - **Stateless** (guest, no `sid`): the token must match the `XSRF-TOKEN`
77
- * cookie (double-submit). Guests hold no authenticated state to protect.
78
- *
79
- * Legacy fallback: tokens stored in sessions by earlier releases keep
80
- * verifying against the session until those sessions expire. Remove this
81
- * branch once all pre-upgrade sessions have aged out (a major release).
82
- */
83
- declare function verifyCsrfToken(ctx: Context, token: string | undefined): boolean;
84
- /**
85
- * Creates a CSRF protection middleware.
86
- *
87
- * This middleware:
88
- * - Issues a signed token in the `XSRF-TOKEN` cookie on safe requests.
89
- * With a logged-in session the token is bound to the session id; for
90
- * guests it is a stateless double-submit token. Nothing is stored
91
- * server-side, so anonymous traffic costs no session writes and session
92
- * middleware is optional.
93
- * - Validates the token for state-changing HTTP methods (POST, PUT, PATCH,
94
- * DELETE): always requires a valid app-key signature, then the bound
95
- * session id or (guest) the cookie match.
96
- * - Supports token submission via form field (_token) or header (X-CSRF-TOKEN)
97
- * - Keeps verifying tokens stored in sessions by earlier releases until
98
- * those sessions expire
99
- * - Exempts the dev-only MCP endpoint while it is mounted, since agent
100
- * clients cannot fetch a token first (it guards local-only access instead)
101
- *
102
- * `cookie: false` disables the `XSRF-TOKEN` cookie for apps that deliver the
103
- * token themselves (meta tag / form field). Session-bound tokens still
104
- * verify without the cookie; guest (stateless) tokens require the cookie, so
105
- * disable it only for session-authenticated flows.
106
- *
107
- * @example
108
- * ```ts
109
- * import { createCsrfMiddleware } from '@guren/server'
110
- *
111
- * app.use(createSessionMiddleware())
112
- * app.use(createCsrfMiddleware({
113
- * exclude: ['/api/webhooks/*']
114
- * }))
115
- * ```
116
- */
117
- declare function createCsrfMiddleware(options?: CsrfOptions): MiddlewareHandler;
118
-
119
- /**
120
- * Per-response form of {@link InertiaDocumentOptions}: the same fields, already
121
- * resolved to strings. Each one overrides the app-wide default registered
122
- * through {@link setInertiaDocument}.
123
- */
124
- type InertiaDocumentOverrides = {
125
- readonly [K in keyof InertiaDocumentOptions]?: string;
126
- };
127
- interface InertiaOptions extends InertiaDocumentOverrides {
128
- readonly url?: string;
129
- readonly version?: string;
130
- readonly status?: number;
131
- readonly headers?: HeadersInit;
132
- readonly request?: Request;
133
- readonly title?: string;
134
- /** Value for the root `<html lang>` attribute. Defaults to "en". */
135
- readonly lang?: string;
136
- readonly entry?: string;
137
- readonly importMap?: Record<string, string>;
138
- readonly styles?: string[];
139
- readonly ssr?: InertiaSsrOptions;
140
- }
141
- interface InertiaPagePayload {
142
- component: string;
143
- props: Record<string, unknown>;
144
- url: string;
145
- version?: string;
146
- }
147
- interface InertiaSsrContext {
148
- page: InertiaPagePayload;
149
- request?: Request;
150
- manifest?: string;
151
- }
152
- interface InertiaSsrResult {
153
- head: string[];
154
- body: string;
155
- }
156
- type InertiaSsrRenderer = (context: InertiaSsrContext) => Promise<InertiaSsrResult> | InertiaSsrResult;
157
- interface InertiaSsrOptions {
158
- enabled?: boolean;
159
- entry?: string;
160
- manifest?: string;
161
- render?: InertiaSsrRenderer;
162
- }
163
- interface InertiaDocumentContext {
164
- /** Page component being rendered, e.g. `"Docs/Show"`. */
165
- readonly component: string;
166
- }
167
- type InertiaDocumentValue = string | ((context: InertiaDocumentContext) => string | undefined);
168
- interface InertiaDocumentOptions {
169
- /**
170
- * Class attribute for the root `<body>` element. Pass a function to vary it
171
- * per page component — a docs section that needs a light surface while the
172
- * marketing pages keep a dark one, for instance.
173
- */
174
- readonly bodyClass?: InertiaDocumentValue;
175
- /**
176
- * CSS inlined into `<head>` ahead of the stylesheet links. Keep it to the
177
- * few declarations that decide the first paint (surface and text colors);
178
- * the main stylesheet still wins for everything it defines later.
179
- */
180
- readonly criticalCss?: InertiaDocumentValue;
181
- /**
182
- * Body of a blocking inline `<script>` executed before the first paint.
183
- * Use it for theme prepaint logic that has to read `localStorage` or
184
- * `matchMedia` before React hydrates.
185
- */
186
- readonly prepaintScript?: InertiaDocumentValue;
187
- /**
188
- * Raw markup inlined into `<head>`, ahead of the critical CSS and stylesheet
189
- * links. Unescaped — the app author owns this string. Use it for static,
190
- * site-wide tags the framework has no way to infer on its own, such as
191
- * `<link rel="icon">` favicons.
192
- */
193
- readonly head?: InertiaDocumentValue;
194
- }
195
- /**
196
- * Register app-wide document defaults for server-rendered Inertia responses.
197
- *
198
- * Without this, the `<body>` ships without a class and nothing is inlined into
199
- * `<head>`, so a page whose theme is applied by a client effect flashes the
200
- * stylesheet's default surface color until React hydrates. Call it at module
201
- * scope in the app entry so every runtime (Bun, serverless handlers, generated
202
- * worker bundles) picks it up.
203
- *
204
- * Registration is process-wide and not request-scoped: calling this while
205
- * requests are in flight leaks the new policy into them. Use the matching
206
- * {@link InertiaOptions} fields for a single response instead.
207
- *
208
- * The values are emitted verbatim — inside `<style>` / `<script>` elements,
209
- * or as raw markup for `head` — they are developer-authored assets, never
210
- * user input.
211
- *
212
- * ```typescript
213
- * setInertiaDocument({
214
- * bodyClass: ({ component }) => (component.startsWith('Docs/') ? 'docs-theme' : undefined),
215
- * })
216
- * ```
217
- *
218
- * Pass `undefined` to clear (test isolation).
219
- */
220
- declare function setInertiaDocument(options: InertiaDocumentOptions | undefined): void;
221
- /**
222
- * Register a process-wide default SSR renderer.
223
- *
224
- * Serverless adapters whose bundlers cannot resolve a runtime file path
225
- * (Cloudflare Workers has no filesystem for `GUREN_INERTIA_SSR_ENTRY`'s
226
- * dynamic import) register the statically imported renderer once at module
227
- * scope. Per-call `ssr.render` still takes precedence; pass `undefined` to
228
- * clear (test isolation).
229
- */
230
- declare function setInertiaSsrRenderer(renderer: InertiaSsrRenderer | undefined): void;
231
- declare function inertia(component: string, props: Record<string, unknown>, options?: InertiaOptions): Promise<Response>;
232
-
233
- /**
234
- * Application-level shared props shape for Inertia responses.
235
- * Extend this interface in your app (via declaration merging) to type shared props.
236
- */
237
- interface InertiaSharedProps {
238
- }
239
- type SharedPropsDefault = Record<string, unknown>;
240
- type ResolvedSharedInertiaProps = InertiaSharedProps extends Record<string, unknown> ? InertiaSharedProps : SharedPropsDefault;
241
- type SharedInertiaPropsResolver<Props extends Record<string, unknown> = ResolvedSharedInertiaProps> = (ctx: Context) => Promise<Props> | Props;
242
- declare function setInertiaSharedProps<Props extends Record<string, unknown> = ResolvedSharedInertiaProps>(resolverFn: SharedInertiaPropsResolver<Props> | null): void;
243
- declare function getInertiaSharedPropsResolver(): SharedInertiaPropsResolver<ResolvedSharedInertiaProps> | null;
244
- /**
245
- * Register additional shared props without replacing resolvers registered
246
- * earlier — the new resolver's props are merged over the previous ones.
247
- * Use this from app providers so multiple providers can each contribute
248
- * shared props (setInertiaSharedProps replaces the resolver wholesale).
249
- */
250
- declare function shareInertiaProps<Props extends Record<string, unknown>>(resolverFn: SharedInertiaPropsResolver<Props>): void;
251
-
252
- /**
253
- * Service factory function.
254
- */
255
- type ServiceFactory<T> = (container: Container) => T;
256
- /**
257
- * Service class constructor.
258
- */
259
- type ServiceClass<T> = new (...args: unknown[]) => T;
260
- /**
261
- * Service binding configuration.
262
- */
263
- interface ServiceBinding {
264
- factory: ServiceFactory<unknown>;
265
- singleton: boolean;
266
- instance?: unknown;
267
- }
268
- /**
269
- * Contextual binding builder interface.
270
- */
271
- interface ContextualBindingBuilder {
272
- needs(abstract: string): ContextualNeedsBuilder;
273
- }
274
- /**
275
- * Contextual needs builder interface.
276
- */
277
- interface ContextualNeedsBuilder {
278
- give<T>(factory: ServiceFactory<T> | T): void;
279
- }
280
- /**
281
- * Contextual binding configuration.
282
- */
283
- interface ContextualBinding {
284
- concrete: string;
285
- needs: string;
286
- factory: ServiceFactory<unknown>;
287
- }
288
- /**
289
- * Service provider options.
290
- */
291
- interface ServiceProviderOptions {
292
- /**
293
- * Whether this provider should be deferred.
294
- */
295
- deferred?: boolean;
296
- /**
297
- * Services this provider provides (for deferred loading).
298
- */
299
- provides?: string[];
300
- }
301
- /**
302
- * Provider interface for container-based service providers.
303
- */
304
- interface Provider {
305
- register?(context: unknown): void | Promise<void>;
306
- boot?(context: unknown): void | Promise<void>;
307
- }
308
- /**
309
- * Service provider class type.
310
- */
311
- interface ServiceProviderClass {
312
- new (container: Container): Provider;
313
- deferred?: boolean;
314
- provides?: string[];
315
- }
316
-
317
- /**
318
- * Serialized job data stored in the queue.
319
- */
320
- interface QueuedJob<T = unknown> {
321
- /**
322
- * Unique job identifier.
323
- */
324
- id: string;
325
- /**
326
- * Job class name.
327
- */
328
- name: string;
329
- /**
330
- * Job payload data.
331
- */
332
- payload: T;
333
- /**
334
- * Queue name this job belongs to.
335
- */
336
- queue: string;
337
- /**
338
- * Number of times this job has been attempted.
339
- */
340
- attempts: number;
341
- /**
342
- * Maximum number of attempts before failing permanently.
343
- */
344
- maxAttempts: number;
345
- /**
346
- * When the job becomes available for processing.
347
- */
348
- availableAt: Date;
349
- /**
350
- * When the job was created.
351
- */
352
- createdAt: Date;
353
- /**
354
- * When the job was reserved by a worker (null if not reserved).
355
- */
356
- reservedAt: Date | null;
357
- /**
358
- * Last error message if the job failed.
359
- */
360
- lastError?: string;
361
- }
362
- /**
363
- * Failed job record.
364
- */
365
- interface FailedJob<T = unknown> extends QueuedJob<T> {
366
- /**
367
- * When the job failed.
368
- */
369
- failedAt: Date;
370
- /**
371
- * Error that caused the failure.
372
- */
373
- error: string;
374
- /**
375
- * Stack trace of the error.
376
- */
377
- stack?: string;
378
- }
379
- /**
380
- * Queue driver interface.
381
- * Implement this to create a custom queue backend.
382
- */
383
- interface QueueDriver {
384
- /**
385
- * Push a job onto the queue.
386
- */
387
- push(job: QueuedJob): Promise<void>;
388
- /**
389
- * Pop the next available job from the queue.
390
- * Returns null if no jobs are available.
391
- */
392
- pop(queue: string): Promise<QueuedJob | null>;
393
- /**
394
- * Release a job back onto the queue (for retry).
395
- * @param job - The job to release
396
- * @param delayMs - Delay before the job becomes available again
397
- */
398
- release(job: QueuedJob, delayMs?: number): Promise<void>;
399
- /**
400
- * Delete a job from the queue.
401
- */
402
- delete(jobId: string): Promise<void>;
403
- /**
404
- * Mark a job as failed and move to failed jobs.
405
- */
406
- fail(job: QueuedJob, error: Error): Promise<void>;
407
- /**
408
- * Get the number of jobs in a queue.
409
- */
410
- size(queue: string): Promise<number>;
411
- /**
412
- * Get failed jobs.
413
- */
414
- getFailedJobs(queue?: string): Promise<FailedJob[]>;
415
- /**
416
- * Retry a failed job.
417
- */
418
- retryFailedJob(jobId: string): Promise<void>;
419
- /**
420
- * Delete a failed job.
421
- */
422
- deleteFailedJob(jobId: string): Promise<void>;
423
- /**
424
- * Clear all jobs (for testing).
425
- */
426
- clear(): Promise<void>;
427
- }
428
- /**
429
- * Options for creating a job.
430
- */
431
- interface JobOptions {
432
- /**
433
- * Queue to dispatch the job to.
434
- * @default 'default'
435
- */
436
- queue?: string;
437
- /**
438
- * Delay in milliseconds before the job is available.
439
- * @default 0
440
- */
441
- delay?: number;
442
- /**
443
- * Maximum number of attempts.
444
- * @default 3
445
- */
446
- maxAttempts?: number;
447
- }
448
- /**
449
- * Worker options.
450
- */
451
- interface WorkerOptions {
452
- /**
453
- * Queues to process (in priority order).
454
- * @default ['default']
455
- */
456
- queues?: string[];
457
- /**
458
- * Sleep time in milliseconds when no jobs are available.
459
- * @default 1000
460
- */
461
- sleep?: number;
462
- /**
463
- * Maximum number of jobs to process before stopping.
464
- * Set to 0 for unlimited.
465
- * @default 0
466
- */
467
- maxJobs?: number;
468
- /**
469
- * Timeout for each job in milliseconds.
470
- * @default 60000
471
- */
472
- timeout?: number;
473
- /**
474
- * Stop the worker when no jobs are available.
475
- * Useful for one-shot processing or testing.
476
- * @default false
477
- */
478
- stopWhenEmpty?: boolean;
479
- }
480
- /**
481
- * Job handler function type.
482
- */
483
- type JobHandler<T = unknown> = (payload: T) => void | Promise<void>;
484
- /**
485
- * Job failure handler function type.
486
- */
487
- type JobFailureHandler<T = unknown> = (payload: T, error: Error) => void | Promise<void>;
488
-
489
- /**
490
- * Set the global queue driver.
491
- */
492
- declare function setQueueDriver(driver: QueueDriver): void;
493
- /**
494
- * Get the global queue driver.
495
- */
496
- declare function getQueueDriver(): QueueDriver | null;
497
- /**
498
- * Base class for defining jobs.
499
- *
500
- * @example
501
- * ```ts
502
- * class SendWelcomeEmailJob extends Job<{ userId: string }> {
503
- * static queue = 'emails'
504
- * static maxAttempts = 5
505
- *
506
- * async handle({ userId }: { userId: string }): Promise<void> {
507
- * const user = await User.find(userId)
508
- * await mail.to(user.email).template(WelcomeEmail, user).send()
509
- * }
510
- *
511
- * async failed({ userId }: { userId: string }, error: Error): Promise<void> {
512
- * console.error(`Failed to send welcome email to user ${userId}:`, error)
513
- * }
514
- * }
515
- *
516
- * // Dispatch the job
517
- * await SendWelcomeEmailJob.dispatch({ userId: '123' })
518
- *
519
- * // Dispatch with delay
520
- * await SendWelcomeEmailJob.dispatchAfter(60000, { userId: '123' })
521
- * ```
522
- */
523
- declare abstract class Job<T = unknown> {
524
- /**
525
- * Stable wire name for this job.
526
- *
527
- * Queued messages record this name, and the worker resolves the class back
528
- * from it. When omitted the class name is used, which breaks if a bundler
529
- * mangles identifiers or if the class is later renamed while messages are
530
- * still in flight. Set it to pin the name across both.
531
- *
532
- * @default the class name
533
- */
534
- static jobName?: string;
535
- /**
536
- * The queue this job should be dispatched to.
537
- * @default 'default'
538
- */
539
- static queue: string;
540
- /**
541
- * Maximum number of times the job should be attempted.
542
- * @default 3
543
- */
544
- static maxAttempts: number;
545
- /**
546
- * Backoff strategy for retries.
547
- * - 'exponential': 2^attempt * 1000ms (1s, 2s, 4s, 8s, ...)
548
- * - 'linear': attempt * 1000ms (1s, 2s, 3s, 4s, ...)
549
- * - number: fixed delay in milliseconds
550
- * @default 'exponential'
551
- */
552
- static backoff: 'exponential' | 'linear' | number;
553
- protected make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
554
- protected make<TService>(key: string): TService;
555
- /**
556
- * Handle the job.
557
- * Override this method to define job logic.
558
- */
559
- abstract handle(payload: T): void | Promise<void>;
560
- /**
561
- * Called when the job fails permanently (after all retries exhausted).
562
- * Override this method to handle failures.
563
- */
564
- failed?(payload: T, error: Error): void | Promise<void>;
565
- /**
566
- * Dispatch the job to the queue.
567
- *
568
- * @param payload - Job payload data
569
- * @param options - Optional dispatch options
570
- */
571
- static dispatch<T>(this: JobClass<T>, payload: T, options?: JobOptions): Promise<string>;
572
- /**
573
- * Dispatch the job after a delay.
574
- *
575
- * @param delayMs - Delay in milliseconds
576
- * @param payload - Job payload data
577
- * @param options - Optional dispatch options (delay is overridden)
578
- */
579
- static dispatchAfter<T>(this: JobClass<T>, delayMs: number, payload: T, options?: Omit<JobOptions, 'delay'>): Promise<string>;
580
- /**
581
- * Calculate the retry delay based on backoff strategy.
582
- */
583
- static calculateRetryDelay(attempts: number): number;
584
- }
585
- /**
586
- * Job class constructor type.
587
- */
588
- interface JobClass<T = unknown> {
589
- new (): Job<T>;
590
- name: string;
591
- jobName?: string;
592
- queue: string;
593
- maxAttempts: number;
594
- backoff: 'exponential' | 'linear' | number;
595
- dispatch(payload: T, options?: JobOptions): Promise<string>;
596
- dispatchAfter(delayMs: number, payload: T, options?: Omit<JobOptions, 'delay'>): Promise<string>;
597
- calculateRetryDelay(attempts: number): number;
598
- }
599
- /**
600
- * Resolve the wire name a job is queued and looked up under.
601
- *
602
- * Prefers an explicit `jobName` over the class name so that renaming the class
603
- * or bundling with identifier mangling does not orphan queued messages.
604
- *
605
- * Only an *own* `jobName` counts. Static members are inherited, so reading it
606
- * off the prototype chain would make every subclass of a pinned job claim its
607
- * parent's identity and overwrite it in the registry. A subclass that wants a
608
- * pinned name declares its own.
609
- */
610
- declare function resolveJobName(jobClass: Pick<JobClass, 'name' | 'jobName'>): string;
611
- /**
612
- * Register a job class for the worker to use.
613
- */
614
- declare function registerJob<T>(jobClass: JobClass<T>): void;
615
- /**
616
- * Get a registered job class by name.
617
- */
618
- declare function getJob(name: string): JobClass | undefined;
619
- /**
620
- * Get all registered job classes.
621
- */
622
- declare function getRegisteredJobs(): Map<string, JobClass>;
623
- /**
624
- * Clear all registered jobs (for testing).
625
- */
626
- declare function clearJobRegistry(): void;
627
-
628
- /**
629
- * Queue driver factory function.
630
- */
631
- type QueueDriverFactory = () => QueueDriver;
632
- /**
633
- * Queue configuration.
634
- */
635
- interface QueueConfig {
636
- /**
637
- * Default driver name.
638
- * @default 'memory'
639
- */
640
- default?: string;
641
- /**
642
- * Driver configurations.
643
- */
644
- drivers?: Record<string, QueueDriverFactory>;
645
- }
646
- /**
647
- * Queue manager for handling multiple queue drivers.
648
- *
649
- * @example
650
- * ```ts
651
- * import { QueueManager, MemoryDriver, RedisDriver } from '@guren/server/queue'
652
- * import { createRedisClient } from '@guren/server/redis'
653
- *
654
- * const redis = createRedisClient({ url: process.env.REDIS_URL })
655
- *
656
- * const queueManager = new QueueManager({
657
- * default: 'redis',
658
- * drivers: {
659
- * memory: () => new MemoryDriver(),
660
- * redis: () => new RedisDriver(redis),
661
- * }
662
- * })
663
- *
664
- * // Use the default driver
665
- * const driver = queueManager.driver()
666
- *
667
- * // Use a specific driver
668
- * const memoryDriver = queueManager.driver('memory')
669
- * ```
670
- */
671
- declare class QueueManager {
672
- private readonly defaultDriver;
673
- private readonly driverFactories;
674
- private readonly resolvedDrivers;
675
- constructor(config?: QueueConfig);
676
- /**
677
- * Get a queue driver by name.
678
- * Returns the default driver if no name is specified.
679
- */
680
- driver(name?: string): QueueDriver;
681
- /**
682
- * Register a custom driver factory.
683
- */
684
- registerDriver(name: string, factory: QueueDriverFactory): void;
685
- /**
686
- * Check if a driver is registered.
687
- */
688
- hasDriver(name: string): boolean;
689
- /**
690
- * Get the default driver name.
691
- */
692
- getDefaultDriverName(): string;
693
- /**
694
- * Get all registered driver names.
695
- */
696
- getDriverNames(): string[];
697
- /**
698
- * Set the default driver and update global driver.
699
- */
700
- setDefaultDriver(name: string): void;
701
- }
702
- /**
703
- * Create a queue manager with default configuration.
704
- */
705
- declare function createQueueManager(config?: QueueConfig): QueueManager;
706
-
707
- /**
708
- * Base notification class.
709
- *
710
- * @example
711
- * ```typescript
712
- * class OrderShipped extends Notification {
713
- * static shouldQueue = true
714
- * static queue = 'notifications'
715
- *
716
- * constructor(private order: Order) {
717
- * super()
718
- * }
719
- *
720
- * via(notifiable: Notifiable): string[] {
721
- * return ['mail', 'database']
722
- * }
723
- *
724
- * toMail(notifiable: Notifiable): NotificationMailMessage {
725
- * return {
726
- * subject: `Order #${this.order.id} shipped`,
727
- * html: '<p>Your order is on its way!</p>',
728
- * }
729
- * }
730
- *
731
- * toDatabase(notifiable: Notifiable): Record<string, unknown> {
732
- * return {
733
- * orderId: this.order.id,
734
- * message: 'Your order has shipped',
735
- * }
736
- * }
737
- * }
738
- * ```
739
- */
740
- declare abstract class Notification {
741
- /**
742
- * Whether this notification should be queued.
743
- */
744
- static shouldQueue: boolean;
745
- /**
746
- * The queue name for this notification.
747
- */
748
- static queue?: string;
749
- /**
750
- * Delay in milliseconds before sending.
751
- */
752
- static delay?: number;
753
- /**
754
- * Unique notification ID.
755
- */
756
- readonly id: string;
757
- /**
758
- * When the notification was created.
759
- */
760
- readonly createdAt: Date;
761
- constructor();
762
- /**
763
- * Get the notification's delivery channels.
764
- */
765
- abstract via(notifiable: Notifiable): string[];
766
- /**
767
- * Get the mail representation of the notification.
768
- */
769
- toMail?(notifiable: Notifiable): NotificationMailMessage;
770
- /**
771
- * Get the database representation of the notification.
772
- */
773
- toDatabase?(notifiable: Notifiable): Record<string, unknown>;
774
- /**
775
- * Get the Slack representation of the notification.
776
- */
777
- toSlack?(notifiable: Notifiable): SlackMessage;
778
- /**
779
- * Get the array representation of the notification.
780
- * Used as a fallback for any channel.
781
- */
782
- toArray?(notifiable: Notifiable): Record<string, unknown>;
783
- /**
784
- * Get the notification type (default: class name).
785
- */
786
- get type(): string;
787
- /**
788
- * Check if the notification should be sent to the given notifiable.
789
- * Override to add custom logic.
790
- */
791
- shouldSend(_notifiable: Notifiable): boolean | Promise<boolean>;
792
- /**
793
- * Generate a unique notification ID.
794
- */
795
- protected generateId(): string;
796
- /**
797
- * Get static queue configuration.
798
- */
799
- static getQueueConfig(): {
800
- shouldQueue: boolean;
801
- queue?: string;
802
- delay?: number;
803
- };
804
- }
805
-
806
- /**
807
- * Notification channel interface.
808
- */
809
- interface NotificationChannel {
810
- readonly name: string;
811
- send(notifiable: Notifiable, notification: Notification): Promise<void>;
812
- }
813
- /**
814
- * Notifiable entity interface.
815
- */
816
- interface Notifiable {
817
- /**
818
- * Get the notification routing information for a given channel.
819
- */
820
- routeNotificationFor(channel: string): string | null;
821
- /**
822
- * Stable type name for this notifiable (optional).
823
- *
824
- * Defaults to the constructor name. Set this when the notifiable is rebuilt
825
- * from a queue payload, or when the class name is not durable (bundlers that
826
- * mangle identifiers).
827
- */
828
- notifiableType?: string;
829
- /**
830
- * Database notifications (optional).
831
- */
832
- notifications?: DatabaseNotification[];
833
- }
834
- /**
835
- * Database notification record.
836
- */
837
- interface DatabaseNotification {
838
- id: string;
839
- type: string;
840
- notifiableId: string | number;
841
- notifiableType: string;
842
- data: Record<string, unknown>;
843
- readAt: Date | null;
844
- createdAt: Date;
845
- }
846
- /**
847
- * Mail message for notifications.
848
- */
849
- interface NotificationMailMessage {
850
- subject: string;
851
- html?: string;
852
- text?: string;
853
- from?: string;
854
- replyTo?: string;
855
- cc?: string | string[];
856
- bcc?: string | string[];
857
- attachments?: NotificationAttachment[];
858
- }
859
- /**
860
- * Notification attachment.
861
- */
862
- interface NotificationAttachment {
863
- filename: string;
864
- content?: string | Buffer;
865
- path?: string;
866
- contentType?: string;
867
- }
868
- /**
869
- * Slack message for notifications.
870
- */
871
- interface SlackMessage {
872
- text?: string;
873
- blocks?: SlackBlock[];
874
- attachments?: SlackAttachment[];
875
- channel?: string;
876
- username?: string;
877
- icon_emoji?: string;
878
- icon_url?: string;
879
- }
880
- /**
881
- * Slack block.
882
- */
883
- interface SlackBlock {
884
- type: string;
885
- text?: {
886
- type: string;
887
- text: string;
888
- emoji?: boolean;
889
- };
890
- elements?: unknown[];
891
- accessory?: unknown;
892
- fields?: Array<{
893
- type: string;
894
- text: string;
895
- }>;
896
- [key: string]: unknown;
897
- }
898
- /**
899
- * Slack attachment.
900
- */
901
- interface SlackAttachment {
902
- color?: string;
903
- fallback?: string;
904
- pretext?: string;
905
- author_name?: string;
906
- author_link?: string;
907
- author_icon?: string;
908
- title?: string;
909
- title_link?: string;
910
- text?: string;
911
- fields?: Array<{
912
- title: string;
913
- value: string;
914
- short?: boolean;
915
- }>;
916
- image_url?: string;
917
- thumb_url?: string;
918
- footer?: string;
919
- footer_icon?: string;
920
- ts?: number;
921
- }
922
- /**
923
- * Notification channel factory.
924
- */
925
- interface NotificationChannelFactory {
926
- (config: Record<string, unknown>): NotificationChannel;
927
- }
928
- /**
929
- * Notification manager options.
930
- */
931
- interface NotificationManagerOptions {
932
- channels?: Record<string, NotificationChannel>;
933
- channelFactories?: Record<string, NotificationChannelFactory>;
934
- }
935
- /**
936
- * Database channel options.
937
- */
938
- interface DatabaseChannelOptions {
939
- /**
940
- * Callback to store the notification.
941
- */
942
- store?: (notifiable: Notifiable, notification: DatabaseNotification) => Promise<void>;
943
- }
944
- /**
945
- * Sent notification record (for testing).
946
- */
947
- interface SentNotification {
948
- notifiable: Notifiable;
949
- notification: Notification;
950
- channels: string[];
951
- timestamp: Date;
952
- }
953
- /**
954
- * Notification class type.
955
- */
956
- interface NotificationClass<T extends Notification = Notification> {
957
- new (...args: unknown[]): T;
958
- shouldQueue?: boolean;
959
- queue?: string;
960
- delay?: number;
961
- getQueueConfig?: () => {
962
- shouldQueue: boolean;
963
- queue?: string;
964
- delay?: number;
965
- };
966
- }
967
-
968
- /**
969
- * Notification manager for sending notifications through multiple channels.
970
- *
971
- * @example
972
- * ```typescript
973
- * const notifications = new NotificationManager()
974
- *
975
- * notifications
976
- * .registerChannel('mail', new MailChannel(mailManager))
977
- * .registerChannel('database', new DatabaseChannel())
978
- * .registerChannel('slack', new SlackChannel(webhookUrl))
979
- *
980
- * // Send notification
981
- * await notifications.send(user, new OrderShipped(order))
982
- *
983
- * // Send to multiple users
984
- * await notifications.sendToMany(admins, new NewUserRegistered(user))
985
- * ```
986
- */
987
- declare class NotificationManager {
988
- protected channels: Map<string, NotificationChannel>;
989
- protected channelFactories: Map<string, NotificationChannelFactory>;
990
- protected resolvedChannels: Map<string, NotificationChannel>;
991
- constructor(options?: NotificationManagerOptions);
992
- /**
993
- * Register a notification channel.
994
- */
995
- registerChannel(name: string, channel: NotificationChannel): this;
996
- /**
997
- * Register a notification channel factory.
998
- */
999
- registerChannelFactory(name: string, factory: NotificationChannelFactory): this;
1000
- /**
1001
- * Get a notification channel by name.
1002
- */
1003
- channel(name: string): NotificationChannel;
1004
- /**
1005
- * Check if a channel is registered.
1006
- */
1007
- hasChannel(name: string): boolean;
1008
- /**
1009
- * Get all registered channel names.
1010
- */
1011
- getChannelNames(): string[];
1012
- /**
1013
- * Send a notification to a notifiable entity.
1014
- * Respects queue configuration on the notification class.
1015
- */
1016
- send(notifiable: Notifiable, notification: Notification): Promise<void>;
1017
- /**
1018
- * Send a notification immediately (bypasses queue).
1019
- */
1020
- sendNow(notifiable: Notifiable, notification: Notification): Promise<void>;
1021
- /**
1022
- * Queue a notification for later delivery.
1023
- */
1024
- protected queue(notifiable: Notifiable, notification: Notification, queueConfig: {
1025
- queue?: string;
1026
- delay?: number;
1027
- }): Promise<void>;
1028
- /**
1029
- * Send notification to multiple notifiables.
1030
- */
1031
- sendToMany(notifiables: Notifiable[], notification: Notification): Promise<void>;
1032
- /**
1033
- * Send notification immediately to multiple notifiables.
1034
- */
1035
- sendNowToMany(notifiables: Notifiable[], notification: Notification): Promise<void>;
1036
- /**
1037
- * Serialize notifiable for queue storage.
1038
- *
1039
- * Routing is resolved here rather than in the worker: `routeNotificationFor`
1040
- * is arbitrary user code — often a closure on an object literal — and cannot
1041
- * be reconstructed from a payload.
1042
- *
1043
- * @param channels - Channels to resolve routes for
1044
- */
1045
- protected serializeNotifiable(notifiable: Notifiable, channels?: string[]): SerializedNotifiable;
1046
- /**
1047
- * Serialize notification for queue storage.
1048
- *
1049
- * Only own enumerable properties are captured. Behaviour is restored by
1050
- * rebuilding the registered class in the job handler, not by serializing it.
1051
- */
1052
- protected serializeNotification(notification: Notification): SerializedNotification;
1053
- /**
1054
- * Bind this manager to the queued-notification job and register it.
1055
- *
1056
- * Call this during boot in a process that runs a worker but may never send
1057
- * a notification itself: without it, the worker cannot resolve the job.
1058
- */
1059
- registerQueueJob(): typeof SendNotificationJob;
1060
- }
1061
- /**
1062
- * Payload for queued notifications.
1063
- */
1064
- interface SendNotificationPayload {
1065
- notifiableData: SerializedNotifiable;
1066
- notificationData: SerializedNotification;
1067
- notificationType: string;
1068
- }
1069
- interface SerializedNotifiable {
1070
- type: string;
1071
- /** Channel routes resolved at dispatch time. Absent on legacy payloads. */
1072
- routes?: Record<string, string | null>;
1073
- data: Record<string, unknown>;
1074
- }
1075
- interface SerializedNotification {
1076
- id: string;
1077
- createdAt: string;
1078
- data: Record<string, unknown>;
1079
- }
1080
- /**
1081
- * Job for sending queued notifications.
1082
- */
1083
- declare class SendNotificationJob extends Job<SendNotificationPayload> {
1084
- static jobName: string;
1085
- static queue: string;
1086
- static maxAttempts: number;
1087
- static notificationManager: NotificationManager | null;
1088
- handle(payload: SendNotificationPayload): Promise<void>;
1089
- /**
1090
- * Rebuild the notifiable from its serialized data.
1091
- */
1092
- protected rebuildNotifiable(serialized: SerializedNotifiable): Notifiable;
1093
- /**
1094
- * Rebuild a real notification instance from its serialized data.
1095
- *
1096
- * The class is looked up in the notification registry and instantiated via
1097
- * its prototype, so prototype methods (`via`, `toMail`, `toDatabase`,
1098
- * `toSlack`, `shouldSend`) are restored without running the constructor.
1099
- */
1100
- protected rebuildNotification(type: string, serialized: SerializedNotification): Notification;
1101
- }
1102
- /**
1103
- * Set the global notification manager.
1104
- */
1105
- declare function setNotificationManager(manager: NotificationManager): void;
1106
- /**
1107
- * Get the global notification manager.
1108
- */
1109
- declare function getNotificationManager(): NotificationManager;
1110
- /**
1111
- * Create a notification manager.
1112
- */
1113
- declare function createNotificationManager(options?: NotificationManagerOptions): NotificationManager;
1114
-
1115
- /**
1116
- * Error response structure.
1117
- */
1118
- interface ErrorResponse {
1119
- message: string;
1120
- errors?: Record<string, string[]>;
1121
- stack?: string;
1122
- exception?: string;
1123
- }
1124
- /**
1125
- * Exception handler options.
1126
- */
1127
- interface ExceptionHandlerOptions {
1128
- /**
1129
- * Whether to show detailed error information.
1130
- * Default: true in development, false in production.
1131
- */
1132
- debug?: boolean;
1133
- /**
1134
- * Custom debug detection function.
1135
- */
1136
- isDebug?: () => boolean;
1137
- }
1138
- /**
1139
- * Exception reporter callback.
1140
- */
1141
- type ExceptionReporter = (error: Error) => void | Promise<void>;
1142
- /**
1143
- * Exception renderer callback.
1144
- */
1145
- type ExceptionRenderer<T extends Error = Error> = (error: T, ctx: Context) => Response | Promise<Response>;
1146
- /**
1147
- * Exception class type.
1148
- */
1149
- type ExceptionClass<T extends Error = Error> = new (...args: any[]) => T;
1150
- /**
1151
- * Renderer registration.
1152
- */
1153
- interface RendererRegistration {
1154
- errorClass: ExceptionClass;
1155
- renderer: ExceptionRenderer;
1156
- }
1157
-
1158
- /**
1159
- * Exception handler for centralized error handling.
1160
- *
1161
- * @example
1162
- * ```typescript
1163
- * const handler = new ExceptionHandler({ debug: false })
1164
- *
1165
- * // Report exceptions (e.g., to Sentry)
1166
- * handler.report(async (error) => {
1167
- * await sentry.captureException(error)
1168
- * })
1169
- *
1170
- * // Custom renderer for validation errors
1171
- * handler.render(ValidationException, (error, ctx) => {
1172
- * return ctx.json({ errors: error.errors }, 422)
1173
- * })
1174
- *
1175
- * // Don't report 404 errors
1176
- * handler.dontReport(NotFoundHttpException)
1177
- *
1178
- * // Use as middleware
1179
- * app.use('*', handler.middleware())
1180
- * ```
1181
- */
1182
- declare class ExceptionHandler {
1183
- /**
1184
- * Exception reporters.
1185
- */
1186
- protected reporters: ExceptionReporter[];
1187
- /**
1188
- * Exception renderers.
1189
- */
1190
- protected renderers: RendererRegistration[];
1191
- /**
1192
- * Exception classes to not report.
1193
- */
1194
- protected dontReportClasses: ExceptionClass[];
1195
- /**
1196
- * Handler options.
1197
- */
1198
- protected options: ExceptionHandlerOptions;
1199
- constructor(options?: ExceptionHandlerOptions);
1200
- /**
1201
- * Register an exception reporter.
1202
- * Reporters are called for every exception (unless in dontReport list).
1203
- */
1204
- report(callback: ExceptionReporter): this;
1205
- /**
1206
- * Register a custom renderer for an exception type.
1207
- */
1208
- render<T extends Error>(errorClass: ExceptionClass<T>, renderer: ExceptionRenderer<T>): this;
1209
- /**
1210
- * Add an exception class to the don't report list.
1211
- */
1212
- dontReport(errorClass: ExceptionClass): this;
1213
- /**
1214
- * Check if debug mode is enabled.
1215
- */
1216
- shouldShowDetails(): boolean;
1217
- /**
1218
- * Handle an exception.
1219
- */
1220
- handle(error: Error, ctx: Context): Promise<Response>;
1221
- /**
1222
- * Report an exception to all reporters.
1223
- */
1224
- protected reportException(error: Error): Promise<void>;
1225
- /**
1226
- * Check if an exception should not be reported.
1227
- */
1228
- protected shouldNotReport(error: Error): boolean;
1229
- protected matchesErrorClass(error: Error, errorClass: ExceptionClass): boolean;
1230
- /**
1231
- * Render an exception to a response.
1232
- */
1233
- protected renderException(error: Error, ctx: Context): Promise<Response>;
1234
- /**
1235
- * Default exception rendering.
1236
- */
1237
- protected renderDefaultException(error: Error, ctx: Context): Response;
1238
- /**
1239
- * Determine whether the request expects an HTML response.
1240
- * Returns false for Inertia, XHR, and JSON API requests so they
1241
- * continue to receive JSON error payloads.
1242
- */
1243
- protected wantsHtmlResponse(ctx: Context): boolean;
1244
- /**
1245
- * Create middleware for exception handling.
1246
- */
1247
- middleware(): Middleware;
1248
- }
1249
- /**
1250
- * Create an exception handler.
1251
- */
1252
- declare function createExceptionHandler(options?: ExceptionHandlerOptions): ExceptionHandler;
1253
- /**
1254
- * Set the global exception handler.
1255
- */
1256
- declare function setExceptionHandler(handler: ExceptionHandler): void;
1257
- /**
1258
- * Get the global exception handler.
1259
- */
1260
- declare function getExceptionHandler(): ExceptionHandler;
1261
- /**
1262
- * Abort the request with an HTTP exception.
1263
- */
1264
- declare function abort(statusCode: number, message?: string, errors?: Record<string, string[]>): never;
1265
- /**
1266
- * Abort if condition is true.
1267
- */
1268
- declare function abortIf(condition: boolean, statusCode: number, message?: string): void;
1269
- /**
1270
- * Abort unless condition is true.
1271
- */
1272
- declare function abortUnless(condition: boolean, statusCode: number, message?: string): void;
1273
-
1274
- /**
1275
- * Type-safe service binding map.
1276
- *
1277
- * Maps service keys to their concrete types for type-safe resolution
1278
- * via `container.make('key')`.
1279
- *
1280
- * @example
1281
- * ```typescript
1282
- * const events = container.make('events') // EventManager
1283
- * const cache = container.make('cache') // CacheManager
1284
- * ```
1285
- */
1286
- interface ServiceBindings {
1287
- app: Application;
1288
- hono: Hono;
1289
- events: EventManager;
1290
- cache: CacheManager;
1291
- queue: QueueManager;
1292
- mail: MailManager;
1293
- log: LogManager;
1294
- i18n: I18nManager;
1295
- notifications: NotificationManager;
1296
- broadcast: BroadcastManager;
1297
- encrypter: Encrypter;
1298
- 'app.keyring': AppKeyring;
1299
- auth: AuthManager;
1300
- oauth: OAuthManager;
1301
- storage: StorageManager;
1302
- health: HealthManager;
1303
- scheduler: Scheduler;
1304
- gate: Gate;
1305
- 'exception.handler': ExceptionHandler;
1306
- }
1307
-
1308
- /**
1309
- * Dependency injection container with type-safe service resolution.
1310
- *
1311
- * @example
1312
- * ```typescript
1313
- * const container = new Container()
1314
- *
1315
- * // Register services
1316
- * container.singleton('events', (c) => new EventManager())
1317
- * container.instance('config', loadConfig())
1318
- *
1319
- * // Type-safe resolution (known bindings)
1320
- * const events = container.make('events') // EventManager
1321
- *
1322
- * // Generic resolution (custom bindings)
1323
- * const db = container.make<Database>('db')
1324
- * ```
1325
- */
1326
- declare class Container {
1327
- protected bindings: Map<string, ServiceBinding>;
1328
- protected aliases: Map<string, string>;
1329
- protected tags: Map<string, Set<string>>;
1330
- protected contextualBindings: ContextualBinding[];
1331
- protected resolvingStack: string[];
1332
- protected scopedInstances: Map<string, unknown>[];
1333
- protected fakes: Map<string, unknown>;
1334
- /** @internal Used by ProviderManager to resolve deferred providers on demand */
1335
- deferredProviderLoader: ((service: string) => Promise<void>) | null;
1336
- /**
1337
- * Bind a service to the container.
1338
- * Each resolution creates a new instance.
1339
- */
1340
- bind<T>(key: string, factory: ServiceFactory<T>): this;
1341
- /**
1342
- * Bind a singleton service to the container.
1343
- * Only one instance is created and reused.
1344
- */
1345
- singleton<T>(key: string, factory: ServiceFactory<T>): this;
1346
- /**
1347
- * Bind an existing instance to the container.
1348
- */
1349
- instance<T>(key: string, value: T): this;
1350
- /**
1351
- * Resolve a service from the container.
1352
- *
1353
- * Known service keys (from ServiceBindings) are automatically typed:
1354
- * ```typescript
1355
- * container.make('events') // EventManager
1356
- * container.make('cache') // CacheManager
1357
- * ```
1358
- *
1359
- * Custom keys require an explicit type parameter:
1360
- * ```typescript
1361
- * container.make<MyService>('myService')
1362
- * ```
1363
- */
1364
- make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
1365
- make<T>(key: string): T;
1366
- /**
1367
- * Resolve a service with additional parameters.
1368
- */
1369
- makeWith<T>(key: string, params: Record<string, unknown>): T;
1370
- /**
1371
- * Check if a service is bound in the container.
1372
- */
1373
- has(key: string): boolean;
1374
- /**
1375
- * Create an alias for a service.
1376
- */
1377
- alias(alias: string, key: string): this;
1378
- /**
1379
- * Tag multiple services with a tag name.
1380
- */
1381
- tag(keys: string[], tagName: string): this;
1382
- /**
1383
- * Resolve all services with a given tag.
1384
- */
1385
- tagged<T = unknown>(tagName: string): T[];
1386
- /**
1387
- * Define a contextual binding.
1388
- */
1389
- when(concrete: string): ContextualBindingBuilder;
1390
- /**
1391
- * Run a callback within a scoped context.
1392
- * Services resolved within the scope are cached and released when the scope ends.
1393
- */
1394
- scoped<T>(callback: () => T): T;
1395
- /**
1396
- * Run an async callback within a scoped context.
1397
- */
1398
- scopedAsync<T>(callback: () => Promise<T>): Promise<T>;
1399
- /**
1400
- * Replace a service binding with a fake instance for testing.
1401
- * Returns a disposable that restores the original binding when disposed.
1402
- *
1403
- * @example
1404
- * ```typescript
1405
- * // Using 'using' declaration (auto-cleanup)
1406
- * using _ = container.fake('events', fakeEventManager)
1407
- *
1408
- * // Manual cleanup
1409
- * const restore = container.fake('mail', fakeMailManager)
1410
- * // ... run tests ...
1411
- * restore[Symbol.dispose]()
1412
- * ```
1413
- */
1414
- fake<K extends keyof ServiceBindings>(key: K, instance: ServiceBindings[K]): Disposable;
1415
- fake(key: string, instance: unknown): Disposable;
1416
- /**
1417
- * Check if a service is currently faked.
1418
- */
1419
- isFaked(key: string): boolean;
1420
- /**
1421
- * Remove all fakes.
1422
- */
1423
- clearFakes(): void;
1424
- /**
1425
- * Flush all resolved singleton instances.
1426
- */
1427
- flush(): void;
1428
- /**
1429
- * Remove a binding from the container.
1430
- */
1431
- forget(key: string): this;
1432
- /**
1433
- * Get all bound service keys.
1434
- */
1435
- getBindings(): string[];
1436
- /**
1437
- * Get all aliases.
1438
- */
1439
- getAliases(): Record<string, string>;
1440
- /**
1441
- * Get all tags.
1442
- */
1443
- getTags(): Record<string, string[]>;
1444
- protected resolveAlias(key: string): string;
1445
- protected findContextualBinding(needs: string): ServiceFactory<unknown> | null;
1446
- }
1447
- /**
1448
- * Create a new container instance.
1449
- */
1450
- declare function createContainer(): Container;
1451
- declare function setContainer(container: Container): void;
1452
- declare function getContainer(): Container;
1453
- declare function resolve<T = unknown>(key: string): T;
1454
-
1455
- /**
1456
- * Constructor shape accepted wherever a provider class can be registered.
1457
- */
1458
- type ServiceProviderConstructor = new (container: Container) => ServiceProvider;
1459
- /**
1460
- * Base service provider class.
1461
- *
1462
- * Service providers are the central place of all application bootstrapping.
1463
- * Your own application, as well as all core services, are bootstrapped via providers.
1464
- *
1465
- * @example
1466
- * ```typescript
1467
- * export class AppServiceProvider extends ServiceProvider {
1468
- * register(): void {
1469
- * // Register bindings
1470
- * this.container.singleton('db', (c) => new Database(c.make('config')))
1471
- * }
1472
- *
1473
- * boot(): void {
1474
- * // Bootstrap after all providers registered
1475
- * const db = this.container.make<Database>('db')
1476
- * db.connect()
1477
- * }
1478
- * }
1479
- * ```
1480
- */
1481
- declare abstract class ServiceProvider implements Provider {
1482
- protected container: Container;
1483
- /**
1484
- * Whether this provider should be deferred.
1485
- * Deferred providers are only loaded when one of their provided services is requested.
1486
- */
1487
- static deferred: boolean;
1488
- /**
1489
- * The services provided by this provider (for deferred loading).
1490
- */
1491
- static provides: string[];
1492
- constructor(container: Container);
1493
- /**
1494
- * Register any application services.
1495
- * This is called before any other providers have booted.
1496
- */
1497
- abstract register(): void | Promise<void>;
1498
- /**
1499
- * Bootstrap any application services.
1500
- * This is called after all providers have registered.
1501
- */
1502
- boot?(): void | Promise<void>;
1503
- /**
1504
- * Get the services provided by the provider.
1505
- */
1506
- provides(): string[];
1507
- /**
1508
- * Check if this provider is deferred.
1509
- */
1510
- isDeferred(): boolean;
1511
- }
1512
- /**
1513
- * Provider manager for registering and booting providers.
1514
- */
1515
- declare class ProviderManager {
1516
- protected container: Container;
1517
- protected providers: ServiceProvider[];
1518
- protected registered: Set<ServiceProvider>;
1519
- protected booted: Set<ServiceProvider>;
1520
- protected deferredProviders: Map<string, ServiceProvider>;
1521
- private allBooted;
1522
- constructor(container: Container);
1523
- /**
1524
- * Register a provider.
1525
- */
1526
- register(providerOrClass: ServiceProvider | ServiceProviderConstructor): this;
1527
- /**
1528
- * Register multiple providers.
1529
- */
1530
- registerMany(providers: Array<ServiceProvider | ServiceProviderConstructor>): this;
1531
- /**
1532
- * Register all non-deferred providers.
1533
- */
1534
- registerAll(): Promise<void>;
1535
- /**
1536
- * Boot all registered providers.
1537
- */
1538
- bootAll(): Promise<void>;
1539
- /**
1540
- * Load a deferred provider for a service.
1541
- */
1542
- loadDeferredProvider(service: string): Promise<void>;
1543
- /**
1544
- * Check if a service is provided by a deferred provider.
1545
- */
1546
- isDeferredService(service: string): boolean;
1547
- /**
1548
- * Get all registered providers.
1549
- */
1550
- getProviders(): ServiceProvider[];
1551
- /**
1552
- * Get all deferred services.
1553
- */
1554
- getDeferredServices(): string[];
1555
- }
1556
-
1557
- /**
1558
- * Parsed argument definition.
1559
- */
1560
- interface ArgumentDefinition {
1561
- name: string;
1562
- description?: string;
1563
- required: boolean;
1564
- array: boolean;
1565
- defaultValue?: string;
1566
- }
1567
- /**
1568
- * Parsed option definition.
1569
- */
1570
- interface OptionDefinition {
1571
- name: string;
1572
- shortcut?: string;
1573
- description?: string;
1574
- requiresValue: boolean;
1575
- defaultValue?: string | boolean;
1576
- array: boolean;
1577
- }
1578
- /**
1579
- * Parsed signature.
1580
- */
1581
- interface ParsedSignature {
1582
- name: string;
1583
- arguments: ArgumentDefinition[];
1584
- options: OptionDefinition[];
1585
- }
1586
- /**
1587
- * Command class type.
1588
- */
1589
- interface CommandClass {
1590
- signature: string;
1591
- description: string;
1592
- new (container?: Container): CommandInstance;
1593
- }
1594
- /**
1595
- * Command instance type.
1596
- */
1597
- interface CommandInstance {
1598
- setInput(argv: string[]): void;
1599
- setOutput(output: OutputInterface): void;
1600
- setKernel(kernel: {
1601
- handle(argv: string[]): Promise<number>;
1602
- }): void;
1603
- run(): Promise<number>;
1604
- }
1605
- /**
1606
- * Output interface.
1607
- */
1608
- interface OutputInterface {
1609
- info(message: string): void;
1610
- error(message: string): void;
1611
- warn(message: string): void;
1612
- success(message: string): void;
1613
- line(message: string): void;
1614
- newLine(count?: number): void;
1615
- table(headers: string[], rows: string[][]): void;
1616
- write(message: string): void;
1617
- }
1618
- /**
1619
- * Input interface.
1620
- */
1621
- interface InputInterface {
1622
- argument<T = string>(name: string): T;
1623
- arguments(): Record<string, string | string[]>;
1624
- option<T = string | boolean>(name: string): T | undefined;
1625
- options(): Record<string, string | boolean | string[]>;
1626
- hasOption(name: string): boolean;
1627
- }
1628
- /**
1629
- * Console kernel options.
1630
- */
1631
- interface ConsoleKernelOptions {
1632
- container?: Container;
1633
- }
1634
- /**
1635
- * Schedule definition for a command.
1636
- */
1637
- interface ScheduledCommand {
1638
- command: string;
1639
- args?: string[];
1640
- expression: string;
1641
- timezone?: string;
1642
- description?: string;
1643
- }
1644
- /**
1645
- * Interactive prompt types.
1646
- */
1647
- interface PromptInterface {
1648
- ask(question: string, defaultValue?: string): Promise<string>;
1649
- confirm(question: string, defaultValue?: boolean): Promise<boolean>;
1650
- choice<T extends string>(question: string, choices: T[], defaultValue?: T): Promise<T>;
1651
- secret(question: string): Promise<string>;
1652
- }
1653
- /**
1654
- * Progress bar interface.
1655
- */
1656
- interface ProgressInterface {
1657
- start(total: number): void;
1658
- advance(step?: number): void;
1659
- finish(): void;
1660
- setProgress(current: number): void;
1661
- }
1662
-
1663
- /**
1664
- * Declarative definition of an application module — a self-contained
1665
- * `modules/<name>/` directory that can register routes and providers, per
1666
- * RFC 0002. Unlike `definePlugin()`, a module has no config stage and no
1667
- * register/boot lifecycle of its own: it's a plain descriptor bundling
1668
- * providers and a route registrar that `Application` folds into its own
1669
- * provider list and route mounting.
1670
- */
1671
- interface ModuleDefinition {
1672
- /** Diagnostic name; also the expected directory name under `modules/`. */
1673
- name: string;
1674
- /**
1675
- * URL prefix applied to all module routes via `router.group(prefix, ...)`.
1676
- * Declarative on purpose — tooling can read a module's URL surface
1677
- * statically without executing the registrar.
1678
- */
1679
- prefix?: string;
1680
- /** Route registrar, invoked after `options.routes` during boot. */
1681
- routes?: (router: Router) => void | Promise<void>;
1682
- /** Providers appended to the application's provider list. */
1683
- providers?: ServiceProviderConstructor[];
1684
- /**
1685
- * Console commands the module owns, exposed so the project's console
1686
- * entrypoint can register them without importing module internals:
1687
- * `kernel.registerMany(billingModule.commands)`. Nothing registers them
1688
- * automatically — `Application` never builds a `ConsoleKernel`, and
1689
- * command registration stays explicit so a bundled deployment resolves
1690
- * the same commands as a local checkout.
1691
- */
1692
- commands?: CommandClass[];
1693
- }
1694
- /**
1695
- * A module as `Application` consumes it — `providers` and `commands`
1696
- * normalized to always be arrays so callers don't repeat the `?? []`
1697
- * fallback. `commands` in particular is read by hand-written console
1698
- * entrypoints (`kernel.registerMany(billingModule.commands)`), where an
1699
- * `undefined` would be a runtime error rather than a no-op.
1700
- */
1701
- interface GurenModule {
1702
- name: string;
1703
- prefix?: string;
1704
- routes?: (router: Router) => void | Promise<void>;
1705
- providers: ServiceProviderConstructor[];
1706
- commands: CommandClass[];
1707
- }
1708
- /**
1709
- * Define a Guren application module without boilerplate.
1710
- *
1711
- * @example
1712
- * ```typescript
1713
- * // modules/billing/index.ts
1714
- * export const billingModule = defineModule({
1715
- * name: 'billing',
1716
- * prefix: '/billing',
1717
- * routes: registerBillingRoutes,
1718
- * providers: [BillingServiceProvider],
1719
- * commands: [InvoiceCommand],
1720
- * })
1721
- *
1722
- * // src/app.ts
1723
- * createApp({ routes, providers, modules: [billingModule] })
1724
- *
1725
- * // src/console.ts
1726
- * kernel.registerMany(billingModule.commands)
1727
- * ```
1728
- */
1729
- declare function defineModule(definition: ModuleDefinition): GurenModule;
1730
- /**
1731
- * Runs a module's route registrar against `router`, applying its `prefix`
1732
- * via `router.group()` when set. Shared by `Application.mountRoutes()` (at
1733
- * boot) and the CLI's route loader (for `guren codegen`/`audit`/`routes`/
1734
- * `openapi:generate`, which need the same route set without booting a real
1735
- * app) so both stay in sync — a bugfix to one path fixes the other.
1736
- *
1737
- * `router.group(prefix, callback)`'s callback is synchronous — it pushes
1738
- * the prefix, invokes the callback, then pops it, with no support for
1739
- * awaiting inside. Capturing the registrar's return value and awaiting it
1740
- * after `group()` returns preserves prefixing for the common case (a
1741
- * synchronous registrar, or an async one that calls `router.get`/`post`/
1742
- * etc. before its first `await`); route calls after an `await` inside an
1743
- * async, prefixed module registrar would run with the prefix already
1744
- * popped. Registrars with no prefix don't go through group() and have no
1745
- * such limitation.
1746
- */
1747
- declare function mountModuleRoutes(router: Router, gurenModule: GurenModule): Promise<void>;
1748
-
1749
- /** Structural type for DI containers, avoiding a hard dependency on Container. */
1750
- interface ContainerLike {
1751
- make(key: string): unknown;
1752
- has?(key: string): boolean;
1753
- }
1754
- /**
1755
- * Duck-type interface for Zod-like schemas.
1756
- * Allows validation without a direct Zod dependency.
1757
- */
1758
- interface ZodLikeSchema<T> {
1759
- safeParse(data: unknown): {
1760
- success: true;
1761
- data: T;
1762
- } | {
1763
- success: false;
1764
- error: {
1765
- issues: Array<{
1766
- path: PropertyKey[];
1767
- message: string;
1768
- }>;
1769
- };
1770
- };
1771
- }
1772
- /**
1773
- * Result type for safe validation methods (discriminated union).
1774
- */
1775
- type SafeValidationResult<T> = {
1776
- success: true;
1777
- data: T;
1778
- } | {
1779
- success: false;
1780
- errors: Record<string, string>;
1781
- };
1782
- type DefaultInertiaProps = Record<string, unknown>;
1783
- type AuthPayload = Record<string, unknown> & {
1784
- user: unknown;
1785
- };
1786
- type InertiaPageContractLike<Component extends string = string, Props extends DefaultInertiaProps = DefaultInertiaProps> = {
1787
- id: Component;
1788
- component?: Component;
1789
- __props?: Props;
1790
- };
1791
- type InertiaResponseMarker<Component extends string, Props extends DefaultInertiaProps> = {
1792
- __gurenInertia: {
1793
- component: Component;
1794
- props: Props;
1795
- };
1796
- };
1797
- type InertiaResponse<Component extends string, Props extends DefaultInertiaProps> = Response & InertiaResponseMarker<Component, Props>;
1798
- type InertiaWithProps = {
1799
- __gurenInertia: {
1800
- props: DefaultInertiaProps;
1801
- };
1802
- };
1803
- type ExtractInertiaProps<T> = Awaited<T> extends infer R ? R extends InertiaWithProps ? R['__gurenInertia']['props'] : never : never;
1804
- type InferInertiaProps<T> = [ExtractInertiaProps<T>] extends [never] ? DefaultInertiaProps : ExtractInertiaProps<T>;
1805
- type ControllerInertiaProps<TController extends Controller, TAction extends keyof TController> = TController[TAction] extends (...args: any[]) => infer TResult ? InferInertiaProps<Awaited<TResult>> : DefaultInertiaProps;
1806
- interface RedirectOptions {
1807
- status?: number;
1808
- headers?: HeadersInit;
1809
- }
1810
- type InertiaResponseOptions = Omit<InertiaOptions, 'url' | 'request'> & {
1811
- url?: string;
1812
- };
1813
- type InertiaPageComponent<TPage extends InertiaPageContractLike> = TPage['id'];
1814
- type InertiaPageProps<TPage extends InertiaPageContractLike> = NonNullable<TPage['__props']>;
1815
- /**
1816
- * Base controller inspired by Laravel's expressive API. Subclasses can access
1817
- * the current Hono context through the protected `ctx` getter and rely on the
1818
- * helper response builders for common patterns.
1819
- *
1820
- * Supports dependency injection via the `static inject` convention:
1821
- * ```typescript
1822
- * class PostController extends Controller {
1823
- * static inject = ['cache', 'events'] as const
1824
- * constructor(private cache: CacheManager, private events: EventManager) { super() }
1825
- * }
1826
- * ```
1827
- */
1828
- declare class Controller {
1829
- #private;
1830
- /**
1831
- * Dependencies to inject from the container.
1832
- * Override in subclasses to declare required services.
1833
- */
1834
- static inject?: readonly string[];
1835
- private context?;
1836
- private parsedBody?;
1837
- private resolvedModels?;
1838
- private _container?;
1839
- setContext(context: Context): void;
1840
- /** @internal Called by the router to inject the DI container. */
1841
- setContainer(container: ContainerLike): void;
1842
- /**
1843
- * Store a resolved model instance from route model binding.
1844
- * @internal Called by the router, not intended for direct use.
1845
- */
1846
- setResolvedModel(modelClass: unknown, instance: unknown): void;
1847
- /**
1848
- * Retrieve a model instance resolved via route model binding.
1849
- *
1850
- * @example
1851
- * ```typescript
1852
- * // routes/web.ts
1853
- * posts.get('/:id', { bind: { id: Post }, name: 'posts.show' }, [PostController, 'show'])
1854
- *
1855
- * // PostController.ts
1856
- * async show() {
1857
- * const post = this.model(Post) // typed as PostRecord
1858
- * return this.inertia(pages.posts.Show, { post })
1859
- * }
1860
- * ```
1861
- */
1862
- protected model<T extends {
1863
- findOrFail(...args: any[]): Promise<any>;
1864
- }>(modelClass: T): Awaited<ReturnType<T['findOrFail']>>;
1865
- protected get ctx(): Context;
1866
- protected get request(): hono.HonoRequest<any, unknown>;
1867
- /**
1868
- * Get an uploaded file from a multipart request.
1869
- *
1870
- * Returns null when the field is missing, is not a file, or the upload is
1871
- * empty. Hono caches the parsed body, so this composes with other body
1872
- * reads in the same request.
1873
- *
1874
- * @example
1875
- * ```typescript
1876
- * const avatar = await this.file('avatar')
1877
- * if (!avatar) {
1878
- * throw ValidationException.withMessages({ avatar: 'Choose a file.' })
1879
- * }
1880
- * await storage.disk().put(`avatars/${avatar.name}`, Buffer.from(await avatar.arrayBuffer()))
1881
- * ```
1882
- */
1883
- protected file(name: string): Promise<File | null>;
1884
- /**
1885
- * Get all uploaded files for a multipart field (e.g. `<input multiple>`).
1886
- * Returns an empty array when none were uploaded.
1887
- */
1888
- protected files(name: string): Promise<File[]>;
1889
- protected get auth(): AuthContext;
1890
- protected make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
1891
- protected make<T>(key: string): T;
1892
- /**
1893
- * Get the authenticated API token or throw AuthenticationException.
1894
- *
1895
- * @example
1896
- * ```typescript
1897
- * const { userId, abilities } = this.apiToken()
1898
- * ```
1899
- */
1900
- protected apiToken(): {
1901
- token: ApiToken;
1902
- userId: string | number;
1903
- abilities: string[];
1904
- };
1905
- /**
1906
- * Get the authenticated user ID from the API token.
1907
- *
1908
- * @example
1909
- * ```typescript
1910
- * const userId = this.apiTokenUserId()
1911
- * ```
1912
- */
1913
- protected apiTokenUserId(): string | number;
1914
- /**
1915
- * Authorize the current user (or guest) for an ability.
1916
- * Throws AuthorizationException (403) when denied.
1917
- *
1918
- * ORM records are plain objects with no constructor information, so pass
1919
- * the model class alongside the record to resolve the policy:
1920
- *
1921
- * @example
1922
- * ```typescript
1923
- * const post = await Post.findOrFail(id)
1924
- * await this.authorize('update', [Post, post])
1925
- * await this.authorize('create', Post)
1926
- * ```
1927
- */
1928
- protected authorize(ability: string, ...args: unknown[]): Promise<void>;
1929
- /**
1930
- * Check whether the current user (or guest) can perform an ability.
1931
- *
1932
- * @example
1933
- * ```typescript
1934
- * if (await this.can('update', [Post, post])) { ... }
1935
- * ```
1936
- */
1937
- protected can(ability: string, ...args: unknown[]): Promise<boolean>;
1938
- private gateUser;
1939
- protected inertia<TPage extends InertiaPageContractLike>(page: TPage, props: InertiaPageProps<TPage>, options?: InertiaResponseOptions): Promise<InertiaResponse<InertiaPageComponent<TPage>, InertiaPageProps<TPage> & ResolvedSharedInertiaProps>>;
1940
- protected inertia<Component extends string, Props extends DefaultInertiaProps>(component: Component, props: Props, options?: InertiaResponseOptions): Promise<InertiaResponse<Component, Props & ResolvedSharedInertiaProps>>;
1941
- protected json<T>(data: T, init?: ResponseInit): Response;
1942
- protected text(body: string, init?: ResponseInit): Response;
1943
- protected redirect(url: string, options?: RedirectOptions): Response;
1944
- /**
1945
- * Return a 204 No Content response.
1946
- */
1947
- protected noContent(): Response;
1948
- /**
1949
- * Return a 201 Created response with JSON data.
1950
- */
1951
- protected created<T>(data?: T, init?: ResponseInit): Response;
1952
- /**
1953
- * Return a 202 Accepted response with optional JSON data.
1954
- */
1955
- protected accepted<T>(data?: T, init?: ResponseInit): Response;
1956
- private jsonStatus;
1957
- /**
1958
- * Get a specific input value from the request body or query parameters.
1959
- * Body values take precedence over query parameters.
1960
- */
1961
- protected input<T = unknown>(key: string, defaultValue?: T): Promise<T | undefined>;
1962
- /**
1963
- * Get a query parameter value.
1964
- */
1965
- protected query(key: string, defaultValue?: string): string | undefined;
1966
- /**
1967
- * Get only the specified keys from the request body.
1968
- */
1969
- protected only(...keys: string[]): Promise<Record<string, unknown>>;
1970
- /**
1971
- * Get all request body values except the specified keys.
1972
- */
1973
- protected except(...keys: string[]): Promise<Record<string, unknown>>;
1974
- /**
1975
- * Check if a key exists in the request body.
1976
- */
1977
- protected has(key: string): Promise<boolean>;
1978
- /** Flatten query string arrays to scalar values for cleaner schema usage. */
1979
- private flattenQueries;
1980
- /**
1981
- * Validate the request body against a Zod-like schema.
1982
- * Throws ValidationException on failure.
1983
- *
1984
- * @example
1985
- * ```typescript
1986
- * const data = await this.validateBody(CreatePostSchema)
1987
- * ```
1988
- */
1989
- protected validateBody<T>(schema: ZodLikeSchema<T>): Promise<T>;
1990
- /**
1991
- * Validate query parameters against a Zod-like schema.
1992
- * Throws ValidationException on failure.
1993
- *
1994
- * @example
1995
- * ```typescript
1996
- * const { page } = this.validateQuery(PageQuerySchema)
1997
- * ```
1998
- */
1999
- protected validateQuery<T>(schema: ZodLikeSchema<T>): T;
2000
- /**
2001
- * Validate route parameters against a Zod-like schema.
2002
- * Throws ValidationException on failure.
2003
- *
2004
- * @example
2005
- * ```typescript
2006
- * const { id } = this.validateParams(PostIdParamSchema)
2007
- * ```
2008
- */
2009
- protected validateParams<T>(schema: ZodLikeSchema<T>): T;
2010
- /**
2011
- * Validate the request body against a Zod-like schema without throwing.
2012
- * Returns a discriminated union: `{ success: true, data }` or `{ success: false, errors }`.
2013
- *
2014
- * @example
2015
- * ```typescript
2016
- * const result = await this.validateBodySafe(CreatePostSchema)
2017
- * if (!result.success) {
2018
- * return this.inertia(pages.posts.New, { errors: result.errors }, { status: 422 })
2019
- * }
2020
- * const { title, body } = result.data
2021
- * ```
2022
- */
2023
- protected validateBodySafe<T>(schema: ZodLikeSchema<T>): Promise<SafeValidationResult<T>>;
2024
- /**
2025
- * Validate query parameters against a Zod-like schema without throwing.
2026
- * Returns a discriminated union: `{ success: true, data }` or `{ success: false, errors }`.
2027
- */
2028
- protected validateQuerySafe<T>(schema: ZodLikeSchema<T>): SafeValidationResult<T>;
2029
- /**
2030
- * Validate route parameters against a Zod-like schema without throwing.
2031
- * Returns a discriminated union: `{ success: true, data }` or `{ success: false, errors }`.
2032
- */
2033
- protected validateParamsSafe<T>(schema: ZodLikeSchema<T>): SafeValidationResult<T>;
2034
- private runValidation;
2035
- private runValidationSafe;
2036
- private getBody;
2037
- }
2038
-
2039
- interface MiddlewareCapabilities {
2040
- authentication?: {
2041
- mode: 'required' | 'guest-only';
2042
- };
2043
- }
2044
-
2045
- /**
2046
- * Constructor type for Controller classes.
2047
- * @template T - The controller type extending Controller
2048
- */
2049
- type ControllerConstructor<T extends Controller = Controller> = (new (...args: any[]) => T) & {
2050
- inject?: readonly string[];
2051
- };
2052
- type ControllerMethod<T extends Controller> = {
2053
- [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
2054
- }[keyof T] & string;
2055
- type ControllerMethodFor<C extends ControllerConstructor> = ControllerMethod<InstanceType<C>>;
2056
- type ControllerAction<C extends ControllerConstructor = ControllerConstructor> = [C, ControllerMethodFor<C>];
2057
- type RouteResult = Response | string | number | boolean | Record<string, unknown> | Array<unknown> | null | void;
2058
- /**
2059
- * Handler for a route - either an inline function or a controller action tuple.
2060
- * Inline handlers receive `next`, so any Hono middleware (e.g.
2061
- * `broadcast.sseMiddleware()`) can be mounted directly as a terminal handler.
2062
- */
2063
- type RouteHandler<C extends ControllerConstructor = ControllerConstructor> = ((c: Context, next: Next) => RouteResult | Promise<RouteResult>) | ControllerAction<C>;
2064
- /**
2065
- * Model binding resolver function.
2066
- */
2067
- type ModelBindingResolver = (value: string) => Promise<unknown>;
2068
- /**
2069
- * Model class with findOrFail static method.
2070
- */
2071
- interface BindableModel {
2072
- findOrFail(id: unknown, key?: string): Promise<unknown>;
2073
- /** Bound values are model classes at runtime; the constructor name is the introspection payload. */
2074
- readonly name?: string;
2075
- }
2076
- type SchemaLike<T = unknown> = ValidationSchema<T> | undefined;
2077
- type InferSchema<TSchema extends SchemaLike<unknown>> = TSchema extends ValidationSchema<infer TValue> ? TValue : never;
2078
- type RouteParamsFor<TSchema extends SchemaLike<unknown>> = [
2079
- TSchema
2080
- ] extends [ValidationSchema<any>] ? InferSchema<TSchema> : Record<string, string>;
2081
- type RouteQueryFor<TSchema extends SchemaLike<unknown>> = [
2082
- TSchema
2083
- ] extends [ValidationSchema<any>] ? InferSchema<TSchema> : Record<string, string | undefined>;
2084
- type RouteBodyFor<TSchema extends SchemaLike<unknown>> = [
2085
- TSchema
2086
- ] extends [ValidationSchema<any>] ? InferSchema<TSchema> : Record<string, unknown>;
2087
- interface TypedRouteContext<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>> {
2088
- ctx: Context;
2089
- params: RouteParamsFor<TParamsSchema>;
2090
- query: RouteQueryFor<TQuerySchema>;
2091
- body: RouteBodyFor<TBodySchema>;
2092
- }
2093
- type TypedRouteHandler<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>> = (input: TypedRouteContext<TParamsSchema, TQuerySchema, TBodySchema>) => ([TOutputSchema] extends [ValidationSchema<any>] ? InferSchema<TOutputSchema> : RouteResult) | Promise<[TOutputSchema] extends [ValidationSchema<any>] ? InferSchema<TOutputSchema> : RouteResult>;
2094
- interface RouteContractOptions<TParamsSchema extends SchemaLike<unknown> = undefined, TQuerySchema extends SchemaLike<unknown> = undefined, TBodySchema extends SchemaLike<unknown> = undefined, TOutputSchema extends SchemaLike<unknown> = undefined> extends RouteOpenApiMetadata {
2095
- name?: string;
2096
- middlewares?: MiddlewareHandler[];
2097
- params?: TParamsSchema;
2098
- query?: TQuerySchema;
2099
- body?: TBodySchema;
2100
- output?: TOutputSchema;
2101
- bind?: Record<string, BindableModel>;
2102
- }
2103
- interface RouteOpenApiMetadata {
2104
- summary?: string;
2105
- description?: string;
2106
- tags?: string[];
2107
- operationId?: string;
2108
- deprecated?: boolean;
2109
- }
2110
- /**
2111
- * Represents a registered route definition for introspection.
2112
- */
2113
- interface RouteDefinition {
2114
- /** HTTP method (GET, POST, PUT, PATCH, DELETE) */
2115
- method: string;
2116
- /** URL path pattern (e.g., '/users/:id') */
2117
- path: string;
2118
- /** Optional route name for URL generation */
2119
- name?: string;
2120
- /** Schema metadata attached via RouteContractOptions */
2121
- schemas?: {
2122
- params?: SchemaLike<unknown>;
2123
- query?: SchemaLike<unknown>;
2124
- body?: SchemaLike<unknown>;
2125
- output?: SchemaLike<unknown>;
2126
- };
2127
- /** Named middleware (aliases or groups) applied to this route */
2128
- middlewareNames?: string[];
2129
- /** Whether inline (unnamed) middleware handlers are attached */
2130
- hasInlineMiddleware?: boolean;
2131
- /**
2132
- * Security capabilities aggregated from the route's middleware chain
2133
- * (named aliases, groups, and inline handlers). Always present on routers
2134
- * from this release — an empty object means "no recognized capability" —
2135
- * so consumers can distinguish that from definitions produced by older
2136
- * servers, where the field is absent. The value shape is internal and may
2137
- * change (RFC 0007).
2138
- */
2139
- capabilities?: MiddlewareCapabilities;
2140
- /** Controller binding when the handler is a [Controller, 'method'] tuple */
2141
- controller?: {
2142
- name: string;
2143
- action: string;
2144
- };
2145
- /** Route model bindings: param name → bound model class name (from `bind`) */
2146
- bindings?: Record<string, string>;
2147
- summary?: string;
2148
- description?: string;
2149
- tags?: string[];
2150
- operationId?: string;
2151
- deprecated?: boolean;
2152
- }
2153
- /**
2154
- * Chainable builder for configuring a registered route.
2155
- * @template M - Union of registered middleware alias names
2156
- */
2157
- interface RouteBuilder<M extends string = never> {
2158
- /** Set the route name for URL generation. */
2159
- name(routeName: string): RouteBuilder<M>;
2160
- /** Attach middleware to this specific route. See {@link RouteMiddlewareInput}. */
2161
- middleware(...items: RouteMiddlewareInput<M>[]): RouteBuilder<M>;
2162
- }
2163
- /**
2164
- * Accepted by `.middleware()`: a registered alias name or a handler function.
2165
- *
2166
- * Resolution is by kind, not by position: every name in a route's chain runs
2167
- * before every handler, across scopes as well as within one call. So an inline
2168
- * handler on an outer group runs *after* a named one on an inner group, the
2169
- * reverse of how they read. Use aliases throughout when relative order matters.
2170
- *
2171
- * Aliases are also the only form that lands in `RouteDefinition.middlewareNames`,
2172
- * which is how `guren audit` reports middleware it cannot otherwise identify.
2173
- * Guards the framework stamps with a capability (`requireAuthenticated`,
2174
- * `requireGuest`) are recognized either way.
2175
- */
2176
- type RouteMiddlewareInput<M extends string = never> = M | MiddlewareHandler;
2177
- /** Storage form of {@link RouteMiddlewareInput}, unparameterized by alias union. */
2178
- type MiddlewareScopeEntry = string | MiddlewareHandler;
2179
- interface RouterMountOptions {
2180
- container?: Container;
2181
- }
2182
- /**
2183
- * Available actions for resource routes.
2184
- */
2185
- type ResourceAction = 'index' | 'create' | 'store' | 'show' | 'edit' | 'update' | 'destroy';
2186
- /**
2187
- * Options for configuring resource routes.
2188
- */
2189
- interface ResourceRouteOptions {
2190
- name?: string;
2191
- param?: string;
2192
- only?: ResourceAction[];
2193
- except?: ResourceAction[];
2194
- }
2195
- /**
2196
- * Instance-based router for app-local route registration and mounting.
2197
- * @template M - Union of registered middleware alias names (e.g. `'auth' | 'guest'`)
2198
- */
2199
- declare class Router<M extends string = never> {
2200
- private readonly registry;
2201
- private readonly prefixStack;
2202
- private readonly namedRoutes;
2203
- private readonly middlewareStack;
2204
- private readonly middlewareAliases;
2205
- private readonly middlewareGroups;
2206
- private readonly modelBindings;
2207
- /** Model class names for router-level bind(param, Model) calls — resolver-only binds carry no name. */
2208
- private readonly modelBindingNames;
2209
- aliasMiddleware<N extends string>(name: N, handler: MiddlewareHandler): Router<M | N>;
2210
- groupMiddleware<N extends string>(name: N, middlewareNames: M[]): Router<M | N>;
2211
- /**
2212
- * Open a middleware scope for the routes registered through the returned
2213
- * builder. See {@link RouteMiddlewareInput}.
2214
- */
2215
- middleware(...items: RouteMiddlewareInput<M>[]): RouterMiddlewareGroupBuilder<M>;
2216
- bind(param: string, modelOrResolver: BindableModel | ModelBindingResolver): this;
2217
- on<C extends ControllerConstructor>(method: string, path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2218
- on<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2219
- on<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2220
- get<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2221
- get<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2222
- get<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2223
- post<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2224
- post<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2225
- post<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2226
- put<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2227
- put<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2228
- put<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2229
- patch<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2230
- patch<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2231
- patch<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2232
- delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2233
- delete<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2234
- delete<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2235
- group(prefix: string, callback: (router: Router<M>) => void): this;
2236
- route(name: string, params?: Record<string, string | number>): string;
2237
- hasRoute(name: string): boolean;
2238
- resource<C extends ControllerConstructor>(path: string, controller: C, options?: ResourceRouteOptions): this;
2239
- mount(app: Hono, options?: RouterMountOptions): void;
2240
- clear(): void;
2241
- resetMiddleware(): void;
2242
- definitions(): RouteDefinition[];
2243
- applyMiddlewareScope<T>(items: readonly MiddlewareScopeEntry[], callback: () => T): T;
2244
- private register;
2245
- private add;
2246
- /**
2247
- * Security capabilities present on a route's middleware chain, aggregated
2248
- * across named aliases (group-expanded) and inline handlers. Unlike
2249
- * `resolveMiddlewareNames`, unregistered names are skipped rather than
2250
- * thrown: `definitions()` must stay side-effect-free for introspection of
2251
- * routers that never mount (audit, codegen), and an unresolvable alias
2252
- * simply contributes no capabilities.
2253
- */
2254
- private aggregateCapabilities;
2255
- private resolveMiddlewareNames;
2256
- }
2257
- declare class RouterMiddlewareGroupBuilder<M extends string = never> {
2258
- private readonly router;
2259
- private readonly items;
2260
- constructor(router: Router<M>, items: readonly MiddlewareScopeEntry[]);
2261
- group(callback: (router: Router<M>) => void): Router<M>;
2262
- get<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2263
- get<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2264
- get<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2265
- post<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2266
- post<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2267
- post<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2268
- put<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2269
- put<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2270
- put<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2271
- patch<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2272
- patch<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2273
- patch<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2274
- delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2275
- delete<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
2276
- delete<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
2277
- }
2278
-
2279
- interface HstsOptions {
2280
- /** Max age in seconds. */
2281
- maxAge: number;
2282
- /** Include subdomains. Default: false */
2283
- includeSubDomains?: boolean;
2284
- /** Enable HSTS preload. Default: false */
2285
- preload?: boolean;
2286
- }
2287
- interface SecurityHeadersOptions {
2288
- /** X-Frame-Options header. Set to false to disable. Default: 'SAMEORIGIN' */
2289
- frameOptions?: string | false;
2290
- /** X-Content-Type-Options header. Set to false to disable. Default: 'nosniff' */
2291
- contentTypeOptions?: string | false;
2292
- /** X-XSS-Protection header. Set to false to disable. Default: '0' */
2293
- xssProtection?: string | false;
2294
- /** Referrer-Policy header. Set to false to disable. Default: 'strict-origin-when-cross-origin' */
2295
- referrerPolicy?: string | false;
2296
- /** X-Permitted-Cross-Domain-Policies header. Set to false to disable. Default: 'none' */
2297
- crossDomainPolicies?: string | false;
2298
- /**
2299
- * Strict-Transport-Security header.
2300
- * Default: `{ maxAge: 31536000 }` (1 year) when NODE_ENV is 'production', false otherwise.
2301
- * Browsers ignore HSTS on plain-HTTP responses, so the production default is safe behind TLS terminators.
2302
- */
2303
- hsts?: HstsOptions | false;
2304
- }
2305
- /**
2306
- * Middleware that sets common HTTP security headers on every response.
2307
- *
2308
- * @example
2309
- * ```ts
2310
- * import { createSecurityHeaders } from '@guren/core'
2311
- *
2312
- * app.use('*', createSecurityHeaders())
2313
- *
2314
- * // With HSTS enabled
2315
- * app.use('*', createSecurityHeaders({
2316
- * hsts: { maxAge: 31536000, includeSubDomains: true },
2317
- * }))
2318
- *
2319
- * // Disable specific headers
2320
- * app.use('*', createSecurityHeaders({
2321
- * frameOptions: false,
2322
- * xssProtection: false,
2323
- * }))
2324
- * ```
2325
- */
2326
- declare function createSecurityHeaders(options?: SecurityHeadersOptions): MiddlewareHandler;
2327
-
2328
- interface HostAuthorizationOptions {
2329
- /** Allowed hosts. Supports exact matches and wildcard subdomains (e.g., '*.example.com'). */
2330
- allowedHosts: string[];
2331
- /** Paths to exclude from host checking (e.g., ['/healthcheck', '/up']). */
2332
- exclude?: string[];
2333
- /** Custom response when host is not authorized. Default: 403 Forbidden. */
2334
- onError?: (ctx: Context) => Response | Promise<Response>;
2335
- }
2336
- /**
2337
- * Middleware that validates the Host header against an allowed list.
2338
- * Protects against DNS rebinding and host header attacks.
2339
- *
2340
- * @example
2341
- * ```ts
2342
- * import { createHostAuthorizationMiddleware } from '@guren/core'
2343
- *
2344
- * app.use('*', createHostAuthorizationMiddleware({
2345
- * allowedHosts: ['example.com', '*.example.com', 'localhost:3000'],
2346
- * exclude: ['/healthcheck'],
2347
- * }))
2348
- * ```
2349
- */
2350
- declare function createHostAuthorizationMiddleware(options: HostAuthorizationOptions): MiddlewareHandler;
2351
-
2352
- declare const GUREN_ASCII_ART: string;
2353
- interface DevBannerOptions {
2354
- hostname: string;
2355
- port: number;
2356
- assetsUrl?: string;
2357
- }
2358
- declare function logDevServerBanner({ hostname, port, assetsUrl, }: DevBannerOptions): void;
2359
-
2360
- interface StartViteDevServerOptions {
2361
- root?: string;
2362
- config?: InlineConfig;
2363
- host?: boolean | string;
2364
- port?: number;
2365
- }
2366
- interface StartedViteDevServer {
2367
- server: ViteDevServer;
2368
- localUrl: string;
2369
- networkUrls: string[];
2370
- }
2371
- declare function startViteDevServer(options?: StartViteDevServerOptions): Promise<StartedViteDevServer>;
2372
-
2373
- type BootCallback = (app: Hono) => void | Promise<void>;
2374
-
2375
- type RouteRegistration = (router: Router) => void | Promise<void>;
2376
- type ApplicationFeatures = Record<string, unknown>;
2377
- interface ApplicationOptions {
2378
- readonly boot?: BootCallback;
2379
- readonly providers?: Array<ServiceProviderConstructor>;
2380
- readonly auth?: AuthPluginOptions;
2381
- readonly discover?: boolean;
2382
- readonly routes?: RouteRegistration;
2383
- /**
2384
- * Application modules (RFC 0002) — each module's providers are appended
2385
- * to `providers` below, and its route registrar runs after `routes`
2386
- * (wrapped in `router.group(prefix, ...)` when the module declares one).
2387
- */
2388
- readonly modules?: GurenModule[];
2389
- readonly features?: ApplicationFeatures;
2390
- /**
2391
- * Configure or disable the default security headers middleware.
2392
- * Set to `false` to disable entirely, or pass `SecurityHeadersOptions` to customize.
2393
- * Enabled by default with safe Rails-matching defaults.
2394
- */
2395
- readonly securityHeaders?: SecurityHeadersOptions | false;
2396
- /**
2397
- * Configure host authorization middleware for DNS rebinding protection.
2398
- * Pass `HostAuthorizationOptions` to enable, or `false` / omit to disable.
2399
- * The `create-app` template includes a default localhost configuration.
2400
- */
2401
- readonly hostAuthorization?: HostAuthorizationOptions | false;
2402
- }
2403
- interface AuthPluginOptions {
2404
- autoSession?: boolean;
2405
- sessionOptions?: CreateSessionMiddlewareOptions;
2406
- /**
2407
- * Automatically register CSRF middleware when session is enabled.
2408
- * Defaults to `true`. Set to `false` to disable (e.g., for pure API servers).
2409
- */
2410
- autoCsrf?: boolean;
2411
- /**
2412
- * Options passed to the CSRF middleware when `autoCsrf` is enabled.
2413
- */
2414
- csrfOptions?: CsrfOptions;
2415
- }
2416
- interface ApplicationListenOptions {
2417
- port?: number;
2418
- hostname?: string;
2419
- assetsUrl?: string;
2420
- vite?: StartViteDevServerOptions | false;
2421
- }
2422
- /**
2423
- * Application wires an app-local router into a running Hono instance.
2424
- *
2425
- * It embeds a DI Container as the backbone of the framework, binding core
2426
- * services and managing providers through the container's ProviderManager.
2427
- */
2428
- declare class Application {
2429
- private readonly options;
2430
- readonly hono: Hono;
2431
- readonly container: Container;
2432
- readonly router: Router;
2433
- private readonly providerManager;
2434
- private readonly authManager;
2435
- private viteDevServer?;
2436
- private bunServer?;
2437
- private viteTeardownRegistered;
2438
- private bunTeardownRegistered;
2439
- private autoSessionAttached;
2440
- private routesRegistered;
2441
- constructor(options?: ApplicationOptions);
2442
- get auth(): AuthManager;
2443
- get authOptions(): AuthPluginOptions | undefined;
2444
- markAutoSessionAttached(): void;
2445
- hasAutoSessionAttached(): boolean;
2446
- /**
2447
- * Mounts the application router onto the Hono instance.
2448
- */
2449
- mountRoutes(): Promise<void>;
2450
- /**
2451
- * Allows registering global middlewares directly on the underlying Hono app.
2452
- */
2453
- use(path: string, ...middleware: MiddlewareHandler[]): void;
2454
- /**
2455
- * Executes provider registration, boot callback, mounts routes, and boots providers.
2456
- */
2457
- boot(): Promise<void>;
2458
- /**
2459
- * Registers default security middleware (headers + host authorization).
2460
- */
2461
- private mountSecurityDefaults;
2462
- private mountHostAuthorization;
2463
- /**
2464
- * Mounts an opt-in, dev-only framework endpoint: the MCP endpoint
2465
- * (/_guren/mcp) and the docs viewer (/_guren/docs) both work this way.
2466
- *
2467
- * Only the dynamic import is allowed to fail silently — these
2468
- * providers reach optional dependencies (the MCP SDK, @guren/cli) that
2469
- * an app need not have installed, and `missing` names that case. A
2470
- * failure inside the provider's own boot is a real problem and is
2471
- * rethrown, rather than leaving the developer with a silent 404.
2472
- */
2473
- private mountDevEndpoint;
2474
- /**
2475
- * Fetch handler to integrate with Bun.serve or any standard Fetch runtime.
2476
- */
2477
- fetch(request: Request, env?: unknown, executionCtx?: ExecutionContext): Promise<Response>;
2478
- /**
2479
- * Convenience helper to start a Bun server when available.
2480
- */
2481
- listen(options?: ApplicationListenOptions): Promise<void>;
2482
- /**
2483
- * Register a service provider.
2484
- */
2485
- register(provider: ServiceProviderConstructor): this;
2486
- /**
2487
- * Register multiple service providers.
2488
- */
2489
- registerMany(providers: Array<ServiceProviderConstructor>): this;
2490
- /**
2491
- * Logs the rich development server banner to the console.
2492
- */
2493
- logDevServerBanner(options: DevBannerOptions): void;
2494
- private closeViteDevServer;
2495
- private registerViteTeardown;
2496
- private registerBunTeardown;
2497
- }
2498
- declare function createApp(options?: ApplicationOptions): Application;
2499
-
2500
- /**
2501
- * Parses the incoming request payload supporting both JSON bodies and form submissions.
2502
- * Falls back to an empty object if the payload cannot be parsed.
2503
- */
2504
- declare function parseRequestPayload(ctx: Context): Promise<Record<string, unknown>>;
2505
- interface ValidationIssueLike {
2506
- path: PropertyKey[];
2507
- message: string;
2508
- }
2509
- interface ValidationErrorLike {
2510
- issues: ValidationIssueLike[];
2511
- }
2512
- /**
2513
- * Converts a Zod-style validation error into a flat record usable by forms.
2514
- */
2515
- declare function formatValidationErrors(error: ValidationErrorLike, fallbackMessage?: string): Record<string, string>;
2516
-
2517
- declare const VALIDATED_DATA_KEY = "guren:validated";
2518
- interface ValidationSchema<T = unknown> {
2519
- parse(data: unknown): T;
2520
- safeParse(data: unknown): {
2521
- success: true;
2522
- data: T;
2523
- } | {
2524
- success: false;
2525
- error: ValidationErrorLike;
2526
- };
2527
- }
2528
- interface ValidateRequestOptions {
2529
- /**
2530
- * Custom error handler when validation fails.
2531
- * Defaults to returning a 422 JSON response with formatted errors.
2532
- */
2533
- onError?: (ctx: Context, errors: Record<string, string>) => Response | Promise<Response>;
2534
- /**
2535
- * HTTP status code for validation errors.
2536
- * Defaults to 422 (Unprocessable Entity).
2537
- */
2538
- status?: number;
2539
- /**
2540
- * Fallback message when no field-specific errors are available.
2541
- */
2542
- fallbackMessage?: string;
2543
- }
2544
- /**
2545
- * Get validated data from the request context.
2546
- * Returns undefined if validation middleware hasn't run or validation failed.
2547
- */
2548
- declare function getValidatedData<T = Record<string, unknown>>(ctx: Context): T | undefined;
2549
- /**
2550
- * Creates a validation middleware that validates the request body against a Zod schema.
2551
- *
2552
- * @example
2553
- * ```ts
2554
- * import { z } from 'zod'
2555
- * import { validateRequest, getValidatedData } from '@guren/server'
2556
- *
2557
- * const CreateUserSchema = z.object({
2558
- * name: z.string().min(1),
2559
- * email: z.email(),
2560
- * })
2561
- *
2562
- * app.post('/users', validateRequest(CreateUserSchema), (c) => {
2563
- * const data = getValidatedData<z.infer<typeof CreateUserSchema>>(c)
2564
- * // data is typed and validated
2565
- * return c.json({ user: data })
2566
- * })
2567
- * ```
2568
- */
2569
- declare function validateRequest<T>(schema: ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
2570
- /**
2571
- * Creates a validation middleware from a schema factory function.
2572
- * Useful when the schema depends on request context.
2573
- *
2574
- * @example
2575
- * ```ts
2576
- * app.post('/users/:role', validateRequestWith((ctx) => {
2577
- * const role = ctx.req.param('role')
2578
- * return role === 'admin' ? AdminSchema : UserSchema
2579
- * }), handler)
2580
- * ```
2581
- */
2582
- declare function validateRequestWith<T>(schemaFactory: (ctx: Context) => ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
2583
- /**
2584
- * Validates data against a schema and throws if invalid.
2585
- * Useful for manual validation in handlers.
2586
- *
2587
- * @example
2588
- * ```ts
2589
- * app.post('/data', async (c) => {
2590
- * const payload = await parseRequestPayload(c)
2591
- * const data = validate(MySchema, payload)
2592
- * // throws ValidationError if invalid
2593
- * return c.json(data)
2594
- * })
2595
- * ```
2596
- */
2597
- declare function validate<T>(schema: ValidationSchema<T>, data: unknown): T;
2598
- /**
2599
- * Validates data against a schema and returns a result object.
2600
- * Does not throw on validation failure.
2601
- */
2602
- declare function validateSafe<T>(schema: ValidationSchema<T>, data: unknown): {
2603
- success: true;
2604
- data: T;
2605
- } | {
2606
- success: false;
2607
- errors: Record<string, string>;
2608
- };
2609
-
2610
- export { type InertiaSsrContext as $, Application as A, type DatabaseNotification as B, type CommandClass as C, type DevBannerOptions as D, type ErrorResponse as E, type ExceptionClass as F, GUREN_ASCII_ART as G, ExceptionHandler as H, type InputInterface as I, type ExceptionHandlerOptions as J, type ExceptionRenderer as K, type ExceptionReporter as L, type FailedJob as M, NotificationManager as N, type OutputInterface as O, type ParsedSignature as P, QueueManager as Q, type GurenModule as R, ServiceProvider as S, type HostAuthorizationOptions as T, type HstsOptions as U, type InertiaDocumentContext as V, type InertiaDocumentOptions as W, type InertiaOptions as X, type InertiaPagePayload as Y, type InertiaResponse as Z, type InertiaSharedProps as _, Container as a, csrfField as a$, type InertiaSsrOptions as a0, type InertiaSsrRenderer as a1, type InertiaSsrResult as a2, type InferInertiaProps as a3, Job as a4, type JobClass as a5, type JobFailureHandler as a6, type JobHandler as a7, type JobOptions as a8, type ModuleDefinition as a9, type SecurityHeadersOptions as aA, type SentNotification as aB, type ServiceBinding as aC, type ServiceClass as aD, type ServiceFactory as aE, type ServiceProviderClass as aF, type ServiceProviderOptions as aG, type SharedInertiaPropsResolver as aH, type SlackAttachment as aI, type SlackBlock as aJ, type SlackMessage as aK, VALIDATED_DATA_KEY as aL, type ValidateRequestOptions as aM, type ValidationSchema as aN, type WorkerOptions as aO, abort as aP, abortIf as aQ, abortUnless as aR, clearJobRegistry as aS, createApp as aT, createContainer as aU, createCsrfMiddleware as aV, createExceptionHandler as aW, createHostAuthorizationMiddleware as aX, createNotificationManager as aY, createQueueManager as aZ, createSecurityHeaders as a_, type Notifiable as aa, Notification as ab, type NotificationAttachment as ac, type NotificationChannel as ad, type NotificationChannelFactory as ae, type NotificationClass as af, type NotificationMailMessage as ag, type NotificationManagerOptions as ah, type ProgressInterface as ai, type PromptInterface as aj, ProviderManager as ak, type QueueConfig as al, type QueueDriver as am, type QueueDriverFactory as an, type QueuedJob as ao, type RendererRegistration as ap, type ResolvedSharedInertiaProps as aq, type ResourceRouteOptions as ar, type RouteBuilder as as, type RouteContractOptions as at, type RouteDefinition as au, type RouteMiddlewareInput as av, type RouteOpenApiMetadata as aw, type ResourceAction as ax, Router as ay, type ScheduledCommand as az, type ConsoleKernelOptions as b, defineModule as b0, formatValidationErrors as b1, getContainer as b2, getCsrfToken as b3, getExceptionHandler as b4, getInertiaSharedPropsResolver as b5, getJob as b6, getNotificationManager as b7, getQueueDriver as b8, getRegisteredJobs as b9, getValidatedData as ba, inertia as bb, mountModuleRoutes as bc, parseRequestPayload as bd, registerJob as be, resolve as bf, resolveJobName as bg, setContainer as bh, setExceptionHandler as bi, setInertiaDocument as bj, setInertiaSharedProps as bk, setInertiaSsrRenderer as bl, setNotificationManager as bm, setQueueDriver as bn, shareInertiaProps as bo, validate as bp, validateRequest as bq, validateRequestWith as br, validateSafe as bs, verifyCsrfToken as bt, type StartViteDevServerOptions as c, type StartedViteDevServer as d, type ServiceProviderConstructor as e, type OptionDefinition as f, type CommandInstance as g, type ServiceBindings as h, type ApplicationListenOptions as i, type ApplicationOptions as j, type ArgumentDefinition as k, logDevServerBanner as l, type AuthPayload as m, type AuthPluginOptions as n, CSRF_FORM_FIELD as o, CSRF_HEADER_NAME as p, CSRF_TOKEN_KEY as q, type Provider as r, startViteDevServer as s, type ContextualBinding as t, type ContextualBindingBuilder as u, type ContextualNeedsBuilder as v, Controller as w, type ControllerInertiaProps as x, type CsrfOptions as y, type DatabaseChannelOptions as z };