@guren/server 1.5.0 → 2.1.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 (53) hide show
  1. package/dist/{AuthManager-C84xF5ks.d.ts → AuthManager-DBP4KYsx.d.ts} +1 -1
  2. package/dist/{ConsoleKernel-D0dkFt6u.d.ts → ConsoleKernel-CJg975mp.d.ts} +1 -1
  3. package/dist/DocsViewerServiceProvider-D7RGJPGM.js +75 -0
  4. package/dist/{I18nManager-CmUqj6bU.d.ts → I18nManager-BiSoczfV.d.ts} +1 -1
  5. package/dist/McpServiceProvider-7BB5FPF3.js +8 -0
  6. package/dist/auth/index.d.ts +39 -29
  7. package/dist/auth/index.js +2 -2
  8. package/dist/broadcasting/index.js +2 -2
  9. package/dist/cache/index.js +2 -2
  10. package/dist/chunk-2V3YID4H.js +20 -0
  11. package/dist/chunk-AZOYI43J.js +18 -0
  12. package/dist/{chunk-DCYKSYAT.js → chunk-B5E5VBDI.js} +54 -2
  13. package/dist/{chunk-NYQGAWDN.js → chunk-BZMZEFRG.js} +7 -11
  14. package/dist/{chunk-4SBGSJNT.js → chunk-CWI4AJ47.js} +2 -1
  15. package/dist/{chunk-NQCZQAJL.js → chunk-DSDX3ASM.js} +21 -2
  16. package/dist/{chunk-SHYRVOMJ.js → chunk-EARA7JM4.js} +3 -3
  17. package/dist/{chunk-MC752CQT.js → chunk-EI5GYMAT.js} +2 -1
  18. package/dist/{chunk-AUXQISW5.js → chunk-HONCNQXZ.js} +38 -5
  19. package/dist/{chunk-CSRQTEQA.js → chunk-HWEWL6TE.js} +6 -1
  20. package/dist/chunk-JBG4AR24.js +18 -0
  21. package/dist/{chunk-RNXTRWKL.js → chunk-K6CUBJX6.js} +9 -15
  22. package/dist/{chunk-Z3HXKWI6.js → chunk-KTNJG7R7.js} +4 -0
  23. package/dist/{chunk-74HTZG3V.js → chunk-LAJQCSSF.js} +24 -0
  24. package/dist/{chunk-H32L2NE3.js → chunk-LVJCZCAV.js} +20 -13
  25. package/dist/{chunk-5AD7LYWO.js → chunk-N7PLD7MB.js} +9 -8
  26. package/dist/{chunk-ONSDE37A.js → chunk-SFQP6O52.js} +1 -0
  27. package/dist/{chunk-XMQZENBP.js → chunk-TVY72CLV.js} +3 -1
  28. package/dist/chunk-WIXGT4TN.js +18 -0
  29. package/dist/{email-verification-H_WlpsVH.d.ts → email-verification-D60YF2ZO.d.ts} +5 -3
  30. package/dist/encryption/index.js +2 -2
  31. package/dist/events/index.js +1 -1
  32. package/dist/i18n/index.d.ts +2 -2
  33. package/dist/index.d.ts +333 -333
  34. package/dist/index.js +242 -88
  35. package/dist/lambda/index.d.ts +5 -5
  36. package/dist/mail/index.js +3 -2
  37. package/dist/mcp/index.d.ts +14 -4
  38. package/dist/mcp/index.js +3 -2
  39. package/dist/notifications/index.d.ts +5 -5
  40. package/dist/notifications/index.js +3 -2
  41. package/dist/queue/index.d.ts +5 -5
  42. package/dist/queue/index.js +1 -1
  43. package/dist/redis/index.d.ts +4 -4
  44. package/dist/redis/index.js +7 -0
  45. package/dist/runtime/index.d.ts +5 -5
  46. package/dist/runtime/index.js +24 -9
  47. package/dist/scheduling/index.js +2 -2
  48. package/dist/storage/index.js +2 -1
  49. package/dist/{Application-Bi-olFMF.d.ts → validation-yAL53e1S.d.ts} +776 -721
  50. package/package.json +3 -3
  51. package/dist/McpServiceProvider-TZWQWXCT.js +0 -7
  52. package/dist/{api-token-COQHXyM_.d.ts → api-token-D24VPr_E.d.ts} +101 -101
  53. package/dist/{client-BQwF2b9Y.d.ts → rate-limit-D9J2b4S1.d.ts} +36 -36
@@ -1,13 +1,13 @@
1
1
  import * as hono from 'hono';
2
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-COQHXyM_.js';
4
- import { A as AuthManager } from './AuthManager-C84xF5ks.js';
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
5
  import { InlineConfig, ViteDevServer } from 'vite';
6
6
  import { E as EventManager } from './EventManager-CmIoLt7r.js';
7
7
  import { C as CacheManager } from './CacheManager-BmDzUKrF.js';
8
8
  import { M as MailManager } from './MailManager-DpMvYiP9.js';
9
9
  import { L as LogManager } from './LogManager-7mxnkaPM.js';
10
- import { I as I18nManager } from './I18nManager-CmUqj6bU.js';
10
+ import { I as I18nManager } from './I18nManager-BiSoczfV.js';
11
11
  import { B as BroadcastManager } from './BroadcastManager-D8KoJxiV.js';
12
12
  import { E as Encrypter, A as AppKeyring } from './app-key-CsBfRC_Q.js';
13
13
  import { S as StorageManager } from './StorageManager-oZTHqaza.js';
@@ -250,187 +250,69 @@ declare function getInertiaSharedPropsResolver(): SharedInertiaPropsResolver<Res
250
250
  declare function shareInertiaProps<Props extends Record<string, unknown>>(resolverFn: SharedInertiaPropsResolver<Props>): void;
251
251
 
252
252
  /**
253
- * Parses the incoming request payload supporting both JSON bodies and form submissions.
254
- * Falls back to an empty object if the payload cannot be parsed.
253
+ * Service factory function.
255
254
  */
256
- declare function parseRequestPayload(ctx: Context): Promise<Record<string, unknown>>;
257
- interface ValidationIssueLike {
258
- path: PropertyKey[];
259
- message: string;
260
- }
261
- interface ValidationErrorLike {
262
- issues: ValidationIssueLike[];
263
- }
255
+ type ServiceFactory<T> = (container: Container) => T;
264
256
  /**
265
- * Converts a Zod-style validation error into a flat record usable by forms.
257
+ * Service class constructor.
266
258
  */
267
- declare function formatValidationErrors(error: ValidationErrorLike, fallbackMessage?: string): Record<string, string>;
268
-
269
- declare const VALIDATED_DATA_KEY = "guren:validated";
270
- interface ValidationSchema<T = unknown> {
271
- parse(data: unknown): T;
272
- safeParse(data: unknown): {
273
- success: true;
274
- data: T;
275
- } | {
276
- success: false;
277
- error: ValidationErrorLike;
278
- };
279
- }
280
- interface ValidateRequestOptions {
281
- /**
282
- * Custom error handler when validation fails.
283
- * Defaults to returning a 422 JSON response with formatted errors.
284
- */
285
- onError?: (ctx: Context, errors: Record<string, string>) => Response | Promise<Response>;
286
- /**
287
- * HTTP status code for validation errors.
288
- * Defaults to 422 (Unprocessable Entity).
289
- */
290
- status?: number;
291
- /**
292
- * Fallback message when no field-specific errors are available.
293
- */
294
- fallbackMessage?: string;
295
- }
259
+ type ServiceClass<T> = new (...args: unknown[]) => T;
296
260
  /**
297
- * Get validated data from the request context.
298
- * Returns undefined if validation middleware hasn't run or validation failed.
261
+ * Service binding configuration.
299
262
  */
300
- declare function getValidatedData<T = Record<string, unknown>>(ctx: Context): T | undefined;
263
+ interface ServiceBinding {
264
+ factory: ServiceFactory<unknown>;
265
+ singleton: boolean;
266
+ instance?: unknown;
267
+ }
301
268
  /**
302
- * Creates a validation middleware that validates the request body against a Zod schema.
303
- *
304
- * @example
305
- * ```ts
306
- * import { z } from 'zod'
307
- * import { validateRequest, getValidatedData } from '@guren/server'
308
- *
309
- * const CreateUserSchema = z.object({
310
- * name: z.string().min(1),
311
- * email: z.email(),
312
- * })
313
- *
314
- * app.post('/users', validateRequest(CreateUserSchema), (c) => {
315
- * const data = getValidatedData<z.infer<typeof CreateUserSchema>>(c)
316
- * // data is typed and validated
317
- * return c.json({ user: data })
318
- * })
319
- * ```
269
+ * Contextual binding builder interface.
320
270
  */
321
- declare function validateRequest<T>(schema: ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
271
+ interface ContextualBindingBuilder {
272
+ needs(abstract: string): ContextualNeedsBuilder;
273
+ }
322
274
  /**
323
- * Creates a validation middleware from a schema factory function.
324
- * Useful when the schema depends on request context.
325
- *
326
- * @example
327
- * ```ts
328
- * app.post('/users/:role', validateRequestWith((ctx) => {
329
- * const role = ctx.req.param('role')
330
- * return role === 'admin' ? AdminSchema : UserSchema
331
- * }), handler)
332
- * ```
275
+ * Contextual needs builder interface.
333
276
  */
334
- declare function validateRequestWith<T>(schemaFactory: (ctx: Context) => ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
277
+ interface ContextualNeedsBuilder {
278
+ give<T>(factory: ServiceFactory<T> | T): void;
279
+ }
335
280
  /**
336
- * Validates data against a schema and throws if invalid.
337
- * Useful for manual validation in handlers.
338
- *
339
- * @example
340
- * ```ts
341
- * app.post('/data', async (c) => {
342
- * const payload = await parseRequestPayload(c)
343
- * const data = validate(MySchema, payload)
344
- * // throws ValidationError if invalid
345
- * return c.json(data)
346
- * })
347
- * ```
281
+ * Contextual binding configuration.
348
282
  */
349
- declare function validate<T>(schema: ValidationSchema<T>, data: unknown): T;
283
+ interface ContextualBinding {
284
+ concrete: string;
285
+ needs: string;
286
+ factory: ServiceFactory<unknown>;
287
+ }
350
288
  /**
351
- * Validates data against a schema and returns a result object.
352
- * Does not throw on validation failure.
289
+ * Service provider options.
353
290
  */
354
- declare function validateSafe<T>(schema: ValidationSchema<T>, data: unknown): {
355
- success: true;
356
- data: T;
357
- } | {
358
- success: false;
359
- errors: Record<string, string>;
360
- };
361
-
362
- interface HstsOptions {
363
- /** Max age in seconds. */
364
- maxAge: number;
365
- /** Include subdomains. Default: false */
366
- includeSubDomains?: boolean;
367
- /** Enable HSTS preload. Default: false */
368
- preload?: boolean;
369
- }
370
- interface SecurityHeadersOptions {
371
- /** X-Frame-Options header. Set to false to disable. Default: 'SAMEORIGIN' */
372
- frameOptions?: string | false;
373
- /** X-Content-Type-Options header. Set to false to disable. Default: 'nosniff' */
374
- contentTypeOptions?: string | false;
375
- /** X-XSS-Protection header. Set to false to disable. Default: '0' */
376
- xssProtection?: string | false;
377
- /** Referrer-Policy header. Set to false to disable. Default: 'strict-origin-when-cross-origin' */
378
- referrerPolicy?: string | false;
379
- /** X-Permitted-Cross-Domain-Policies header. Set to false to disable. Default: 'none' */
380
- crossDomainPolicies?: string | false;
291
+ interface ServiceProviderOptions {
381
292
  /**
382
- * Strict-Transport-Security header.
383
- * Default: `{ maxAge: 31536000 }` (1 year) when NODE_ENV is 'production', false otherwise.
384
- * Browsers ignore HSTS on plain-HTTP responses, so the production default is safe behind TLS terminators.
293
+ * Whether this provider should be deferred.
385
294
  */
386
- hsts?: HstsOptions | false;
295
+ deferred?: boolean;
296
+ /**
297
+ * Services this provider provides (for deferred loading).
298
+ */
299
+ provides?: string[];
387
300
  }
388
301
  /**
389
- * Middleware that sets common HTTP security headers on every response.
390
- *
391
- * @example
392
- * ```ts
393
- * import { createSecurityHeaders } from '@guren/core'
394
- *
395
- * app.use('*', createSecurityHeaders())
396
- *
397
- * // With HSTS enabled
398
- * app.use('*', createSecurityHeaders({
399
- * hsts: { maxAge: 31536000, includeSubDomains: true },
400
- * }))
401
- *
402
- * // Disable specific headers
403
- * app.use('*', createSecurityHeaders({
404
- * frameOptions: false,
405
- * xssProtection: false,
406
- * }))
407
- * ```
302
+ * Provider interface for container-based service providers.
408
303
  */
409
- declare function createSecurityHeaders(options?: SecurityHeadersOptions): MiddlewareHandler;
410
-
411
- interface HostAuthorizationOptions {
412
- /** Allowed hosts. Supports exact matches and wildcard subdomains (e.g., '*.example.com'). */
413
- allowedHosts: string[];
414
- /** Paths to exclude from host checking (e.g., ['/healthcheck', '/up']). */
415
- exclude?: string[];
416
- /** Custom response when host is not authorized. Default: 403 Forbidden. */
417
- onError?: (ctx: Context) => Response | Promise<Response>;
304
+ interface Provider {
305
+ register?(context: unknown): void | Promise<void>;
306
+ boot?(context: unknown): void | Promise<void>;
418
307
  }
419
308
  /**
420
- * Middleware that validates the Host header against an allowed list.
421
- * Protects against DNS rebinding and host header attacks.
422
- *
423
- * @example
424
- * ```ts
425
- * import { createHostAuthorizationMiddleware } from '@guren/core'
426
- *
427
- * app.use('*', createHostAuthorizationMiddleware({
428
- * allowedHosts: ['example.com', '*.example.com', 'localhost:3000'],
429
- * exclude: ['/healthcheck'],
430
- * }))
431
- * ```
309
+ * Service provider class type.
432
310
  */
433
- declare function createHostAuthorizationMiddleware(options: HostAuthorizationOptions): MiddlewareHandler;
311
+ interface ServiceProviderClass {
312
+ new (container: Container): Provider;
313
+ deferred?: boolean;
314
+ provides?: string[];
315
+ }
434
316
 
435
317
  /**
436
318
  * Serialized job data stored in the queue.
@@ -1423,46 +1305,487 @@ interface ServiceBindings {
1423
1305
  'exception.handler': ExceptionHandler;
1424
1306
  }
1425
1307
 
1426
- /** Structural type for DI containers, avoiding a hard dependency on Container. */
1427
- interface ContainerLike {
1428
- make(key: string): unknown;
1429
- has?(key: string): boolean;
1430
- }
1431
- /**
1432
- * Duck-type interface for Zod-like schemas.
1433
- * Allows validation without a direct Zod dependency.
1434
- */
1435
- interface ZodLikeSchema<T> {
1436
- safeParse(data: unknown): {
1437
- success: true;
1438
- data: T;
1439
- } | {
1440
- success: false;
1441
- error: {
1442
- issues: Array<{
1443
- path: PropertyKey[];
1444
- message: string;
1445
- }>;
1446
- };
1447
- };
1448
- }
1449
1308
  /**
1450
- * Result type for safe validation methods (discriminated union).
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
+ * ```
1451
1325
  */
1452
- type SafeValidationResult<T> = {
1453
- success: true;
1454
- data: T;
1455
- } | {
1456
- success: false;
1457
- errors: Record<string, string>;
1458
- };
1459
- type DefaultInertiaProps = Record<string, unknown>;
1460
- type AuthPayload = Record<string, unknown> & {
1461
- user: unknown;
1462
- };
1463
- type InertiaPageContractLike<Component extends string = string, Props extends DefaultInertiaProps = DefaultInertiaProps> = {
1464
- id: Component;
1465
- component?: Component;
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;
1466
1789
  __props?: Props;
1467
1790
  };
1468
1791
  type InertiaResponseMarker<Component extends string, Props extends DefaultInertiaProps> = {
@@ -1713,217 +2036,11 @@ declare class Controller {
1713
2036
  private getBody;
1714
2037
  }
1715
2038
 
1716
- /**
1717
- * Service factory function.
1718
- */
1719
- type ServiceFactory<T> = (container: Container) => T;
1720
- /**
1721
- * Service class constructor.
1722
- */
1723
- type ServiceClass<T> = new (...args: unknown[]) => T;
1724
- /**
1725
- * Service binding configuration.
1726
- */
1727
- interface ServiceBinding {
1728
- factory: ServiceFactory<unknown>;
1729
- singleton: boolean;
1730
- instance?: unknown;
1731
- }
1732
- /**
1733
- * Contextual binding builder interface.
1734
- */
1735
- interface ContextualBindingBuilder {
1736
- needs(abstract: string): ContextualNeedsBuilder;
1737
- }
1738
- /**
1739
- * Contextual needs builder interface.
1740
- */
1741
- interface ContextualNeedsBuilder {
1742
- give<T>(factory: ServiceFactory<T> | T): void;
1743
- }
1744
- /**
1745
- * Contextual binding configuration.
1746
- */
1747
- interface ContextualBinding {
1748
- concrete: string;
1749
- needs: string;
1750
- factory: ServiceFactory<unknown>;
1751
- }
1752
- /**
1753
- * Service provider options.
1754
- */
1755
- interface ServiceProviderOptions {
1756
- /**
1757
- * Whether this provider should be deferred.
1758
- */
1759
- deferred?: boolean;
1760
- /**
1761
- * Services this provider provides (for deferred loading).
1762
- */
1763
- provides?: string[];
1764
- }
1765
- /**
1766
- * Provider interface for container-based service providers.
1767
- */
1768
- interface Provider {
1769
- register?(context: unknown): void | Promise<void>;
1770
- boot?(context: unknown): void | Promise<void>;
1771
- }
1772
- /**
1773
- * Service provider class type.
1774
- */
1775
- interface ServiceProviderClass {
1776
- new (container: Container): Provider;
1777
- deferred?: boolean;
1778
- provides?: string[];
1779
- }
1780
-
1781
- /**
1782
- * Dependency injection container with type-safe service resolution.
1783
- *
1784
- * @example
1785
- * ```typescript
1786
- * const container = new Container()
1787
- *
1788
- * // Register services
1789
- * container.singleton('events', (c) => new EventManager())
1790
- * container.instance('config', loadConfig())
1791
- *
1792
- * // Type-safe resolution (known bindings)
1793
- * const events = container.make('events') // EventManager
1794
- *
1795
- * // Generic resolution (custom bindings)
1796
- * const db = container.make<Database>('db')
1797
- * ```
1798
- */
1799
- declare class Container {
1800
- protected bindings: Map<string, ServiceBinding>;
1801
- protected aliases: Map<string, string>;
1802
- protected tags: Map<string, Set<string>>;
1803
- protected contextualBindings: ContextualBinding[];
1804
- protected resolvingStack: string[];
1805
- protected scopedInstances: Map<string, unknown>[];
1806
- protected fakes: Map<string, unknown>;
1807
- /** @internal Used by ProviderManager to resolve deferred providers on demand */
1808
- deferredProviderLoader: ((service: string) => Promise<void>) | null;
1809
- /**
1810
- * Bind a service to the container.
1811
- * Each resolution creates a new instance.
1812
- */
1813
- bind<T>(key: string, factory: ServiceFactory<T>): this;
1814
- /**
1815
- * Bind a singleton service to the container.
1816
- * Only one instance is created and reused.
1817
- */
1818
- singleton<T>(key: string, factory: ServiceFactory<T>): this;
1819
- /**
1820
- * Bind an existing instance to the container.
1821
- */
1822
- instance<T>(key: string, value: T): this;
1823
- /**
1824
- * Resolve a service from the container.
1825
- *
1826
- * Known service keys (from ServiceBindings) are automatically typed:
1827
- * ```typescript
1828
- * container.make('events') // EventManager
1829
- * container.make('cache') // CacheManager
1830
- * ```
1831
- *
1832
- * Custom keys require an explicit type parameter:
1833
- * ```typescript
1834
- * container.make<MyService>('myService')
1835
- * ```
1836
- */
1837
- make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
1838
- make<T>(key: string): T;
1839
- /**
1840
- * Resolve a service with additional parameters.
1841
- */
1842
- makeWith<T>(key: string, params: Record<string, unknown>): T;
1843
- /**
1844
- * Check if a service is bound in the container.
1845
- */
1846
- has(key: string): boolean;
1847
- /**
1848
- * Create an alias for a service.
1849
- */
1850
- alias(alias: string, key: string): this;
1851
- /**
1852
- * Tag multiple services with a tag name.
1853
- */
1854
- tag(keys: string[], tagName: string): this;
1855
- /**
1856
- * Resolve all services with a given tag.
1857
- */
1858
- tagged<T = unknown>(tagName: string): T[];
1859
- /**
1860
- * Define a contextual binding.
1861
- */
1862
- when(concrete: string): ContextualBindingBuilder;
1863
- /**
1864
- * Run a callback within a scoped context.
1865
- * Services resolved within the scope are cached and released when the scope ends.
1866
- */
1867
- scoped<T>(callback: () => T): T;
1868
- /**
1869
- * Run an async callback within a scoped context.
1870
- */
1871
- scopedAsync<T>(callback: () => Promise<T>): Promise<T>;
1872
- /**
1873
- * Replace a service binding with a fake instance for testing.
1874
- * Returns a disposable that restores the original binding when disposed.
1875
- *
1876
- * @example
1877
- * ```typescript
1878
- * // Using 'using' declaration (auto-cleanup)
1879
- * using _ = container.fake('events', fakeEventManager)
1880
- *
1881
- * // Manual cleanup
1882
- * const restore = container.fake('mail', fakeMailManager)
1883
- * // ... run tests ...
1884
- * restore[Symbol.dispose]()
1885
- * ```
1886
- */
1887
- fake<K extends keyof ServiceBindings>(key: K, instance: ServiceBindings[K]): Disposable;
1888
- fake(key: string, instance: unknown): Disposable;
1889
- /**
1890
- * Check if a service is currently faked.
1891
- */
1892
- isFaked(key: string): boolean;
1893
- /**
1894
- * Remove all fakes.
1895
- */
1896
- clearFakes(): void;
1897
- /**
1898
- * Flush all resolved singleton instances.
1899
- */
1900
- flush(): void;
1901
- /**
1902
- * Remove a binding from the container.
1903
- */
1904
- forget(key: string): this;
1905
- /**
1906
- * Get all bound service keys.
1907
- */
1908
- getBindings(): string[];
1909
- /**
1910
- * Get all aliases.
1911
- */
1912
- getAliases(): Record<string, string>;
1913
- /**
1914
- * Get all tags.
1915
- */
1916
- getTags(): Record<string, string[]>;
1917
- protected resolveAlias(key: string): string;
1918
- protected findContextualBinding(needs: string): ServiceFactory<unknown> | null;
2039
+ interface MiddlewareCapabilities {
2040
+ authentication?: {
2041
+ mode: 'required' | 'guest-only';
2042
+ };
1919
2043
  }
1920
- /**
1921
- * Create a new container instance.
1922
- */
1923
- declare function createContainer(): Container;
1924
- declare function setContainer(container: Container): void;
1925
- declare function getContainer(): Container;
1926
- declare function resolve<T = unknown>(key: string): T;
1927
2044
 
1928
2045
  /**
1929
2046
  * Constructor type for Controller classes.
@@ -2011,6 +2128,15 @@ interface RouteDefinition {
2011
2128
  middlewareNames?: string[];
2012
2129
  /** Whether inline (unnamed) middleware handlers are attached */
2013
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;
2014
2140
  /** Controller binding when the handler is a [Controller, 'method'] tuple */
2015
2141
  controller?: {
2016
2142
  name: string;
@@ -2031,9 +2157,25 @@ interface RouteDefinition {
2031
2157
  interface RouteBuilder<M extends string = never> {
2032
2158
  /** Set the route name for URL generation. */
2033
2159
  name(routeName: string): RouteBuilder<M>;
2034
- /** Attach named middleware to this specific route. */
2035
- middleware(...names: M[]): RouteBuilder<M>;
2160
+ /** Attach middleware to this specific route. See {@link RouteMiddlewareInput}. */
2161
+ middleware(...items: RouteMiddlewareInput<M>[]): RouteBuilder<M>;
2036
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;
2037
2179
  interface RouterMountOptions {
2038
2180
  container?: Container;
2039
2181
  }
@@ -2066,7 +2208,11 @@ declare class Router<M extends string = never> {
2066
2208
  private readonly modelBindingNames;
2067
2209
  aliasMiddleware<N extends string>(name: N, handler: MiddlewareHandler): Router<M | N>;
2068
2210
  groupMiddleware<N extends string>(name: N, middlewareNames: M[]): Router<M | N>;
2069
- middleware(...names: M[]): RouterMiddlewareGroupBuilder<M>;
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>;
2070
2216
  bind(param: string, modelOrResolver: BindableModel | ModelBindingResolver): this;
2071
2217
  on<C extends ControllerConstructor>(method: string, path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2072
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>;
@@ -2091,324 +2237,117 @@ declare class Router<M extends string = never> {
2091
2237
  hasRoute(name: string): boolean;
2092
2238
  resource<C extends ControllerConstructor>(path: string, controller: C, options?: ResourceRouteOptions): this;
2093
2239
  mount(app: Hono, options?: RouterMountOptions): void;
2094
- clear(): void;
2095
- resetMiddleware(): void;
2096
- definitions(): RouteDefinition[];
2097
- applyMiddlewareScope<T>(names: string[], callback: () => T): T;
2098
- private register;
2099
- private add;
2100
- private resolveMiddlewareNames;
2101
- }
2102
- declare class RouterMiddlewareGroupBuilder<M extends string = never> {
2103
- private readonly router;
2104
- private readonly names;
2105
- constructor(router: Router<M>, names: string[]);
2106
- group(callback: (router: Router<M>) => void): Router<M>;
2107
- get<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2108
- 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>;
2109
- post<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2110
- 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>;
2111
- put<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2112
- 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>;
2113
- patch<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2114
- 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>;
2115
- delete<C extends ControllerConstructor>(path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
2116
- 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>;
2117
- }
2118
-
2119
- /**
2120
- * Constructor shape accepted wherever a provider class can be registered.
2121
- */
2122
- type ServiceProviderConstructor = new (container: Container) => ServiceProvider;
2123
- /**
2124
- * Base service provider class.
2125
- *
2126
- * Service providers are the central place of all application bootstrapping.
2127
- * Your own application, as well as all core services, are bootstrapped via providers.
2128
- *
2129
- * @example
2130
- * ```typescript
2131
- * export class AppServiceProvider extends ServiceProvider {
2132
- * register(): void {
2133
- * // Register bindings
2134
- * this.container.singleton('db', (c) => new Database(c.make('config')))
2135
- * }
2136
- *
2137
- * boot(): void {
2138
- * // Bootstrap after all providers registered
2139
- * const db = this.container.make<Database>('db')
2140
- * db.connect()
2141
- * }
2142
- * }
2143
- * ```
2144
- */
2145
- declare abstract class ServiceProvider implements Provider {
2146
- protected container: Container;
2147
- /**
2148
- * Whether this provider should be deferred.
2149
- * Deferred providers are only loaded when one of their provided services is requested.
2150
- */
2151
- static deferred: boolean;
2152
- /**
2153
- * The services provided by this provider (for deferred loading).
2154
- */
2155
- static provides: string[];
2156
- constructor(container: Container);
2157
- /**
2158
- * Register any application services.
2159
- * This is called before any other providers have booted.
2160
- */
2161
- abstract register(): void | Promise<void>;
2162
- /**
2163
- * Bootstrap any application services.
2164
- * This is called after all providers have registered.
2165
- */
2166
- boot?(): void | Promise<void>;
2167
- /**
2168
- * Get the services provided by the provider.
2169
- */
2170
- provides(): string[];
2171
- /**
2172
- * Check if this provider is deferred.
2173
- */
2174
- isDeferred(): boolean;
2175
- }
2176
- /**
2177
- * Provider manager for registering and booting providers.
2178
- */
2179
- declare class ProviderManager {
2180
- protected container: Container;
2181
- protected providers: ServiceProvider[];
2182
- protected registered: Set<ServiceProvider>;
2183
- protected booted: Set<ServiceProvider>;
2184
- protected deferredProviders: Map<string, ServiceProvider>;
2185
- private allBooted;
2186
- constructor(container: Container);
2187
- /**
2188
- * Register a provider.
2189
- */
2190
- register(providerOrClass: ServiceProvider | ServiceProviderConstructor): this;
2191
- /**
2192
- * Register multiple providers.
2193
- */
2194
- registerMany(providers: Array<ServiceProvider | ServiceProviderConstructor>): this;
2195
- /**
2196
- * Register all non-deferred providers.
2197
- */
2198
- registerAll(): Promise<void>;
2199
- /**
2200
- * Boot all registered providers.
2201
- */
2202
- bootAll(): Promise<void>;
2203
- /**
2204
- * Load a deferred provider for a service.
2205
- */
2206
- loadDeferredProvider(service: string): Promise<void>;
2207
- /**
2208
- * Check if a service is provided by a deferred provider.
2209
- */
2210
- isDeferredService(service: string): boolean;
2211
- /**
2212
- * Get all registered providers.
2213
- */
2214
- getProviders(): ServiceProvider[];
2215
- /**
2216
- * Get all deferred services.
2217
- */
2218
- getDeferredServices(): string[];
2219
- }
2220
-
2221
- /**
2222
- * Parsed argument definition.
2223
- */
2224
- interface ArgumentDefinition {
2225
- name: string;
2226
- description?: string;
2227
- required: boolean;
2228
- array: boolean;
2229
- defaultValue?: string;
2230
- }
2231
- /**
2232
- * Parsed option definition.
2233
- */
2234
- interface OptionDefinition {
2235
- name: string;
2236
- shortcut?: string;
2237
- description?: string;
2238
- requiresValue: boolean;
2239
- defaultValue?: string | boolean;
2240
- array: boolean;
2241
- }
2242
- /**
2243
- * Parsed signature.
2244
- */
2245
- interface ParsedSignature {
2246
- name: string;
2247
- arguments: ArgumentDefinition[];
2248
- options: OptionDefinition[];
2249
- }
2250
- /**
2251
- * Command class type.
2252
- */
2253
- interface CommandClass {
2254
- signature: string;
2255
- description: string;
2256
- new (container?: Container): CommandInstance;
2257
- }
2258
- /**
2259
- * Command instance type.
2260
- */
2261
- interface CommandInstance {
2262
- setInput(argv: string[]): void;
2263
- setOutput(output: OutputInterface): void;
2264
- setKernel(kernel: {
2265
- handle(argv: string[]): Promise<number>;
2266
- }): void;
2267
- run(): Promise<number>;
2268
- }
2269
- /**
2270
- * Output interface.
2271
- */
2272
- interface OutputInterface {
2273
- info(message: string): void;
2274
- error(message: string): void;
2275
- warn(message: string): void;
2276
- success(message: string): void;
2277
- line(message: string): void;
2278
- newLine(count?: number): void;
2279
- table(headers: string[], rows: string[][]): void;
2280
- write(message: string): void;
2281
- }
2282
- /**
2283
- * Input interface.
2284
- */
2285
- interface InputInterface {
2286
- argument<T = string>(name: string): T;
2287
- arguments(): Record<string, string | string[]>;
2288
- option<T = string | boolean>(name: string): T | undefined;
2289
- options(): Record<string, string | boolean | string[]>;
2290
- hasOption(name: string): boolean;
2291
- }
2292
- /**
2293
- * Console kernel options.
2294
- */
2295
- interface ConsoleKernelOptions {
2296
- container?: Container;
2297
- }
2298
- /**
2299
- * Schedule definition for a command.
2300
- */
2301
- interface ScheduledCommand {
2302
- command: string;
2303
- args?: string[];
2304
- expression: string;
2305
- timezone?: string;
2306
- description?: string;
2307
- }
2308
- /**
2309
- * Interactive prompt types.
2310
- */
2311
- interface PromptInterface {
2312
- ask(question: string, defaultValue?: string): Promise<string>;
2313
- confirm(question: string, defaultValue?: boolean): Promise<boolean>;
2314
- choice<T extends string>(question: string, choices: T[], defaultValue?: T): Promise<T>;
2315
- secret(question: string): Promise<string>;
2316
- }
2317
- /**
2318
- * Progress bar interface.
2319
- */
2320
- interface ProgressInterface {
2321
- start(total: number): void;
2322
- advance(step?: number): void;
2323
- finish(): void;
2324
- setProgress(current: number): void;
2325
- }
2326
-
2327
- /**
2328
- * Declarative definition of an application module — a self-contained
2329
- * `modules/<name>/` directory that can register routes and providers, per
2330
- * RFC 0002. Unlike `definePlugin()`, a module has no config stage and no
2331
- * register/boot lifecycle of its own: it's a plain descriptor bundling
2332
- * providers and a route registrar that `Application` folds into its own
2333
- * provider list and route mounting.
2334
- */
2335
- interface ModuleDefinition {
2336
- /** Diagnostic name; also the expected directory name under `modules/`. */
2337
- name: string;
2240
+ clear(): void;
2241
+ resetMiddleware(): void;
2242
+ definitions(): RouteDefinition[];
2243
+ applyMiddlewareScope<T>(items: readonly MiddlewareScopeEntry[], callback: () => T): T;
2244
+ private register;
2245
+ private add;
2338
2246
  /**
2339
- * URL prefix applied to all module routes via `router.group(prefix, ...)`.
2340
- * Declarative on purpose — tooling can read a module's URL surface
2341
- * statically without executing the registrar.
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.
2342
2253
  */
2343
- prefix?: string;
2344
- /** Route registrar, invoked after `options.routes` during boot. */
2345
- routes?: (router: Router) => void | Promise<void>;
2346
- /** Providers appended to the application's provider list. */
2347
- providers?: ServiceProviderConstructor[];
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;
2348
2298
  /**
2349
- * Console commands the module owns, exposed so the project's console
2350
- * entrypoint can register them without importing module internals:
2351
- * `kernel.registerMany(billingModule.commands)`. Nothing registers them
2352
- * automatically — `Application` never builds a `ConsoleKernel`, and
2353
- * command registration stays explicit so a bundled deployment resolves
2354
- * the same commands as a local checkout.
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.
2355
2302
  */
2356
- commands?: CommandClass[];
2357
- }
2358
- /**
2359
- * A module as `Application` consumes it — `providers` and `commands`
2360
- * normalized to always be arrays so callers don't repeat the `?? []`
2361
- * fallback. `commands` in particular is read by hand-written console
2362
- * entrypoints (`kernel.registerMany(billingModule.commands)`), where an
2363
- * `undefined` would be a runtime error rather than a no-op.
2364
- */
2365
- interface GurenModule {
2366
- name: string;
2367
- prefix?: string;
2368
- routes?: (router: Router) => void | Promise<void>;
2369
- providers: ServiceProviderConstructor[];
2370
- commands: CommandClass[];
2303
+ hsts?: HstsOptions | false;
2371
2304
  }
2372
2305
  /**
2373
- * Define a Guren application module without boilerplate.
2306
+ * Middleware that sets common HTTP security headers on every response.
2374
2307
  *
2375
2308
  * @example
2376
- * ```typescript
2377
- * // modules/billing/index.ts
2378
- * export const billingModule = defineModule({
2379
- * name: 'billing',
2380
- * prefix: '/billing',
2381
- * routes: registerBillingRoutes,
2382
- * providers: [BillingServiceProvider],
2383
- * commands: [InvoiceCommand],
2384
- * })
2309
+ * ```ts
2310
+ * import { createSecurityHeaders } from '@guren/core'
2385
2311
  *
2386
- * // src/app.ts
2387
- * createApp({ routes, providers, modules: [billingModule] })
2312
+ * app.use('*', createSecurityHeaders())
2388
2313
  *
2389
- * // src/console.ts
2390
- * kernel.registerMany(billingModule.commands)
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
+ * }))
2391
2324
  * ```
2392
2325
  */
2393
- declare function defineModule(definition: ModuleDefinition): GurenModule;
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
+ }
2394
2336
  /**
2395
- * Runs a module's route registrar against `router`, applying its `prefix`
2396
- * via `router.group()` when set. Shared by `Application.mountRoutes()` (at
2397
- * boot) and the CLI's route loader (for `guren codegen`/`audit`/`routes`/
2398
- * `openapi:generate`, which need the same route set without booting a real
2399
- * app) so both stay in sync — a bugfix to one path fixes the other.
2337
+ * Middleware that validates the Host header against an allowed list.
2338
+ * Protects against DNS rebinding and host header attacks.
2400
2339
  *
2401
- * `router.group(prefix, callback)`'s callback is synchronous — it pushes
2402
- * the prefix, invokes the callback, then pops it, with no support for
2403
- * awaiting inside. Capturing the registrar's return value and awaiting it
2404
- * after `group()` returns preserves prefixing for the common case (a
2405
- * synchronous registrar, or an async one that calls `router.get`/`post`/
2406
- * etc. before its first `await`); route calls after an `await` inside an
2407
- * async, prefixed module registrar would run with the prefix already
2408
- * popped. Registrars with no prefix don't go through group() and have no
2409
- * such limitation.
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
+ * ```
2410
2349
  */
2411
- declare function mountModuleRoutes(router: Router, gurenModule: GurenModule): Promise<void>;
2350
+ declare function createHostAuthorizationMiddleware(options: HostAuthorizationOptions): MiddlewareHandler;
2412
2351
 
2413
2352
  declare const GUREN_ASCII_ART: string;
2414
2353
  interface DevBannerOptions {
@@ -2522,10 +2461,16 @@ declare class Application {
2522
2461
  private mountSecurityDefaults;
2523
2462
  private mountHostAuthorization;
2524
2463
  /**
2525
- * Mounts the MCP endpoint at /_guren/mcp when enabled.
2526
- * This allows AI coding agents to introspect the project.
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.
2527
2472
  */
2528
- private mountMcpEndpoint;
2473
+ private mountDevEndpoint;
2529
2474
  /**
2530
2475
  * Fetch handler to integrate with Bun.serve or any standard Fetch runtime.
2531
2476
  */
@@ -2552,4 +2497,114 @@ declare class Application {
2552
2497
  }
2553
2498
  declare function createApp(options?: ApplicationOptions): Application;
2554
2499
 
2555
- 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, defineModule 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 SentNotification as aA, type ServiceBinding as aB, type ServiceClass as aC, type ServiceFactory as aD, type ServiceProviderClass as aE, type ServiceProviderOptions as aF, type SharedInertiaPropsResolver as aG, type SlackAttachment as aH, type SlackBlock as aI, type SlackMessage as aJ, VALIDATED_DATA_KEY as aK, type ValidateRequestOptions as aL, type ValidationSchema as aM, type WorkerOptions as aN, abort as aO, abortIf as aP, abortUnless as aQ, clearJobRegistry as aR, createApp as aS, createContainer as aT, createCsrfMiddleware as aU, createExceptionHandler as aV, createHostAuthorizationMiddleware as aW, createNotificationManager as aX, createQueueManager as aY, createSecurityHeaders as aZ, csrfField 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 RouteOpenApiMetadata as av, type ResourceAction as aw, Router as ax, type ScheduledCommand as ay, type SecurityHeadersOptions as az, type ConsoleKernelOptions as b, formatValidationErrors as b0, getContainer as b1, getCsrfToken as b2, getExceptionHandler as b3, getInertiaSharedPropsResolver as b4, getJob as b5, getNotificationManager as b6, getQueueDriver as b7, getRegisteredJobs as b8, getValidatedData as b9, inertia as ba, mountModuleRoutes as bb, parseRequestPayload as bc, registerJob as bd, resolve as be, resolveJobName as bf, setContainer as bg, setExceptionHandler as bh, setInertiaDocument as bi, setInertiaSharedProps as bj, setInertiaSsrRenderer as bk, setNotificationManager as bl, setQueueDriver as bm, shareInertiaProps as bn, validate as bo, validateRequest as bp, validateRequestWith as bq, validateSafe as br, verifyCsrfToken as bs, 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 };
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 };