@stacksjs/router 0.72.56 → 0.72.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -8,6 +8,8 @@ export type { MiddlewareConfig, Request } from './middleware';
8
8
  // so the path doesn't depend on a 5-level relative reach across the
9
9
  // framework defaults tree (stacksjs/stacks#1863, T-10).
10
10
  export type { RouteDefinition, RouteRegistry } from './route-types';
11
+ export type { UrlParams } from './stacks-router';
12
+ export type { ChainableRoute, RouterAction, StacksHandler, StacksRouterInstance } from './stacks-router';
11
13
  export type { PathParamRejection, SanitizePathParamOptions } from './path-sanitize';
12
14
  export type { ApplicationHealthCheck, ApplicationHealthResult, HealthProbe, HealthProbeOptions } from './health';
13
15
  export type { StreamOptions } from './stacks-router';
@@ -24,7 +26,7 @@ export type {
24
26
  export * from '@stacksjs/bun-router';
25
27
  // Export Stacks-specific action resolver and URL helper
26
28
  export { assertRouteMiddlewareResolvable,
27
- configureViewDirectories, clearMiddlewareCache, createStacksRouter, disableViewRouting, findUnresolvableRouteMiddleware, installMiddlewareHotReload, resetBootHooks, route, runBootHooks, serve, serverResponse, url, warnOnMultipleRouterInstances } from './stacks-router';
29
+ configureViewDirectories, clearCsrfModuleCache, clearMiddlewareCache, createStacksRouter, disableViewRouting, findUnresolvableRouteMiddleware, installMiddlewareHotReload, resetBootHooks, route, runBootHooks, serve, serverResponse, url, warnOnMultipleRouterInstances } from './stacks-router';
28
30
  // Export request context helpers
29
31
  export { cacheRequestQuery, clearCurrentRequest, getCurrentRequest, getTraceId, request, runWithRequest, setCurrentRequest, withTraceId } from './request-context';
30
32
  // Export Middleware class for defining route middleware
@@ -42,7 +44,24 @@ export {
42
44
  trackQuery,
43
45
  } from './error-handler';
44
46
  // Export route introspection helpers
45
- export { listRegisteredRoutes, routeParams } from './stacks-router';
47
+ export { listNamedRoutes, listRegisteredRoutes, routeParams } from './stacks-router';
48
+ // Registering an action by import rather than by name: the seam that lets a
49
+ // route hand over the action object it already has, instead of a string that
50
+ // only a runtime `import()` can make sense of. `listRegisteredRoutes()` reports
51
+ // it, which is how the OpenAPI generator reads such a route's schema without a
52
+ // file path to import.
53
+ export { isRouterAction, wrapAction } from './stacks-router';
54
+ /*
55
+ * Typed routes, bound to this application's router.
56
+ *
57
+ * The builder, the route-map contract and the client itself all come from
58
+ * `@stacksjs/bun-router` (re-exported above by the star export at the top of
59
+ * this file) - `createTypedClient`, `TypedRouter`, `RoutesOf`, `defineEndpoint`
60
+ * and the rest are available from here without being named again. Only the
61
+ * binding to the `route` singleton is specific to Stacks, and that is what
62
+ * `./typed-router` adds; it deliberately shadows the star-exported name.
63
+ */
64
+ export { createTypedRouter } from './typed-router';
46
65
  // Route-model binding (stacksjs/stacks#2231): what lets `can:view,site`
47
66
  // reach `SitePolicy.view(user, site)` instead of handing the policy layer a
48
67
  // raw path string it can never match a policy against.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var {require}=import.meta;import"./request-augmentation";export*from"@stacksjs/bun-router";export{assertRouteMiddlewareResolvable,configureViewDirectories,clearMiddlewareCache,createStacksRouter,disableViewRouting,findUnresolvableRouteMiddleware,installMiddlewareHotReload,resetBootHooks,route,runBootHooks,serve,serverResponse,url,warnOnMultipleRouterInstances}from"./stacks-router";export{cacheRequestQuery,clearCurrentRequest,getCurrentRequest,getTraceId,request,runWithRequest,setCurrentRequest,withTraceId}from"./request-context";export{Middleware}from"./middleware";export{loadRoutes}from"./route-loader";export{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse,createNotFoundResponse,createValidationErrorResponse,getQueryShapeCounts,trackQuery}from"./error-handler";export{listRegisteredRoutes,routeParams}from"./stacks-router";export{clearRouteModelBindings,defineRouteModelBinding,resolveRouteModel,routeModelBindings,setRouteModelFallback}from"./route-model-binding";export{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";export{rateLimit,rateLimitStatus,clearRateLimit}from"./rate-limit";export{PathParamError,safePathParam,sanitizePathParam}from"./path-sanitize";export{checkApplicationHealth,runHealthProbes}from"./health";export{stream}from"./stacks-router";export{signedUrl,signUrl,verifySignedUrl,verifySignedUrlMiddleware}from"./signed-url";export{EncryptedSessionStore}from"./encrypted-session-store";export{createSessionStore,createStacksSessionStore,DatabaseSessionStore,FileSessionStore,MemorySessionStore,RedisSessionStore}from"./session-factory";import("@stacksjs/database").then(({setQueryTracker})=>{if(typeof setQueryTracker==="function"){const{trackQuery}=require("./error-handler");setQueryTracker(trackQuery)}}).catch(()=>{});
1
+ var {require}=import.meta;import"./request-augmentation";export*from"@stacksjs/bun-router";export{assertRouteMiddlewareResolvable,configureViewDirectories,clearCsrfModuleCache,clearMiddlewareCache,createStacksRouter,disableViewRouting,findUnresolvableRouteMiddleware,installMiddlewareHotReload,resetBootHooks,route,runBootHooks,serve,serverResponse,url,warnOnMultipleRouterInstances}from"./stacks-router";export{cacheRequestQuery,clearCurrentRequest,getCurrentRequest,getTraceId,request,runWithRequest,setCurrentRequest,withTraceId}from"./request-context";export{Middleware}from"./middleware";export{loadRoutes}from"./route-loader";export{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse,createNotFoundResponse,createValidationErrorResponse,getQueryShapeCounts,trackQuery}from"./error-handler";export{listNamedRoutes,listRegisteredRoutes,routeParams}from"./stacks-router";export{isRouterAction,wrapAction}from"./stacks-router";export{createTypedRouter}from"./typed-router";export{clearRouteModelBindings,defineRouteModelBinding,resolveRouteModel,routeModelBindings,setRouteModelFallback}from"./route-model-binding";export{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";export{rateLimit,rateLimitStatus,clearRateLimit}from"./rate-limit";export{PathParamError,safePathParam,sanitizePathParam}from"./path-sanitize";export{checkApplicationHealth,runHealthProbes}from"./health";export{stream}from"./stacks-router";export{signedUrl,signUrl,verifySignedUrl,verifySignedUrlMiddleware}from"./signed-url";export{EncryptedSessionStore}from"./encrypted-session-store";export{createSessionStore,createStacksSessionStore,DatabaseSessionStore,FileSessionStore,MemorySessionStore,RedisSessionStore}from"./session-factory";import("@stacksjs/database").then(({setQueryTracker})=>{if(typeof setQueryTracker==="function"){const{trackQuery}=require("./error-handler");setQueryTracker(trackQuery)}}).catch(()=>{});
@@ -1,3 +1,4 @@
1
+ import type { MiddlewareReference } from '@stacksjs/bun-router';
1
2
  /**
2
3
  * Route registry types — owned by `@stacksjs/router` because the router
3
4
  * consumes them. `app/Routes.ts` (the project-level route map) imports
@@ -7,6 +8,6 @@
7
8
  export declare interface RouteDefinition {
8
9
  path: string
9
10
  prefix?: string
10
- middleware?: string | string[]
11
+ middleware?: MiddlewareReference | MiddlewareReference[]
11
12
  }
12
13
  export type RouteRegistry = Record<string, string | RouteDefinition>;
@@ -1,4 +1,5 @@
1
- import type { EnhancedRequest } from '@stacksjs/bun-router';
1
+ import type { EnhancedRequest, KnownRouteName } from '@stacksjs/bun-router';
2
+ import type { UrlParams } from './stacks-router';
2
3
  /**
3
4
  * Sign an existing URL (full or path-only). Returns a new URL string
4
5
  * with `expires` (optional) and `signature` query params appended.
@@ -18,7 +19,7 @@ export declare function signUrl(input: string, options?: SignedUrlOptions): stri
18
19
  * // → https://app.example.com/api/email/verify?user=42&expires=1716470400&signature=…
19
20
  * ```
20
21
  */
21
- export declare function signedUrl(routeName: string, params?: Record<string, string | number>, options?: SignedUrlOptions): string;
22
+ export declare function signedUrl<TName extends KnownRouteName>(routeName: TName, params?: UrlParams<TName>, options?: SignedUrlOptions): string;
22
23
  /**
23
24
  * Verify the `signature` (and optional `expires`) on an incoming URL.
24
25
  * Returns a discriminated result so callers can pick their own status
@@ -1,8 +1,8 @@
1
1
  import type { Server } from 'bun';
2
2
  import './request-augmentation';
3
3
  import { Router } from '@stacksjs/bun-router';
4
- import type { ActionHandler, EnhancedRequest, Route, ServerOptions } from '@stacksjs/bun-router';
5
- import type { ActionValidations, ValidationResult } from '@stacksjs/actions';
4
+ import type { ActionHandler, ActionPath, EnhancedRequest, ExtractRouteParams, KnownRouteName, MiddlewareReference, PathForRouteName, RequestFor, Route, ServerOptions } from '@stacksjs/bun-router';
5
+ import type { ActionResult, ActionValidations, ValidationResult } from '@stacksjs/actions';
6
6
  /**
7
7
  * Run every registered boot hook, once per process.
8
8
  *
@@ -16,35 +16,28 @@ export declare function runBootHooks(): Promise<void>;
16
16
  /** For tests, and for a process that genuinely re-boots. */
17
17
  export declare function resetBootHooks(): void;
18
18
  export declare function warnOnMultipleRouterInstances(): boolean;
19
- /**
20
- * Generate a full URL for a named route, like Laravel's route() helper.
21
- *
22
- * Validates path parameters at call time so a typo'd argument
23
- * (`url('user.post', { userId: 1 })` against `/users/{id}`) throws
24
- * immediately with a list of expected names instead of silently
25
- * producing a URL with `{id}` left literal in the path.
26
- *
27
- * @example
28
- * ```typescript
29
- * // Define a named route
30
- * route.get('/api/email/unsubscribe', 'Actions/UnsubscribeAction').name('email.unsubscribe')
31
- *
32
- * // Generate URL
33
- * url('email.unsubscribe', { token: 'abc-123' })
34
- * // → https://stacksjs.com/api/email/unsubscribe?token=abc-123
35
- *
36
- * // With path parameters
37
- * route.get('/users/{id}/posts/{postId}', handler).name('user.post')
38
- * url('user.post', { id: 42, postId: 7 })
39
- * // → https://stacksjs.com/users/42/posts/7
40
- * ```
41
- */
42
- export declare function url(routeName: string, params?: Record<string, string | number>): string;
19
+ // False positive: this is an overload signature, which has no body for its
20
+ // parameters to be used in. The implementation below uses them.
21
+ // eslint-disable-next-line unused-imports/no-unused-vars
22
+ export declare function url<TName extends KnownRouteName>(routeName: TName, ...params: RequiresUrlParams<TName> extends true ? [params: UrlParams<TName>] : [params?: UrlParams<TName>]): string;
43
23
  /**
44
24
  * List the placeholder names a named route expects — handy for
45
25
  * codegen/test cases and for detecting typos before runtime.
46
26
  */
47
27
  export declare function routeParams(routeName: string): string[];
28
+ /**
29
+ * Every named route, as `name → path`.
30
+ *
31
+ * `listRegisteredRoutes()` reports a name by searching the named registry for a
32
+ * matching path, which answers "what is this route called" and cannot answer
33
+ * "what routes are there names for" - two routes on one path give the first
34
+ * name found, and a name whose route was never registered is invisible.
35
+ *
36
+ * The type generator needs the second question: it writes this map into the
37
+ * router's type registry so `url('users.shwo')` stops compiling. Reading the
38
+ * registry directly is the only way to get every name.
39
+ */
40
+ export declare function listNamedRoutes(): Record<string, string>;
48
41
  /**
49
42
  * Snapshot of the registered routes — `{ method, path, name?, handler? }` per
50
43
  * route. Used by `buddy route:list`, the dev-server startup banner, and the
@@ -59,7 +52,7 @@ export declare function routeParams(routeName: string): string[];
59
52
  * taking no input at all. The registry has known the real answer the whole
60
53
  * time; it was simply not being reported.
61
54
  */
62
- export declare function listRegisteredRoutes(): Array<{ method: string, path: string, name?: string, handler?: string }>;
55
+ export declare function listRegisteredRoutes(): Array<{ method: string, path: string, name?: string, handler?: string, action?: RouterAction }>;
63
56
  /**
64
57
  * Clear the middleware cache (useful for hot-reload in development).
65
58
  *
@@ -144,6 +137,23 @@ export declare function precognitionRequest(req: EnhancedRequest): { only: strin
144
137
  * serve this 204 to a caller that meant to submit.
145
138
  */
146
139
  export declare function precognitionSuccess(): Response;
140
+ /** Whether a route handler is an action rather than a plain function. */
141
+ export declare function isRouterAction(handler: unknown): handler is RouterAction;
142
+ /**
143
+ * Turn a resolved action into the function the route actually runs.
144
+ *
145
+ * Split out of the string-resolution path so registering an action by import
146
+ * (`createTypedRouter().get('/x', ShowAction)`) and registering it by name
147
+ * (`route.get('/x', 'Actions/ShowAction')`) share one runtime path. The two
148
+ * forms differ only in when the module is loaded and in what the compiler can
149
+ * see; everything below - validation, precognition, `authorize`, `before`,
150
+ * result formatting, error reporting - is the same code for both.
151
+ *
152
+ * `handlerKey` identifies the action for the CSRF skip cache and for error
153
+ * labels. It is the handler string when there is one, and the route key
154
+ * otherwise.
155
+ */
156
+ export declare function wrapAction(action: RouterAction, handlerKey: string): RouteHandlerFn;
147
157
  /**
148
158
  * Run an action's declarative `validations:` against the request.
149
159
  *
@@ -153,6 +163,8 @@ export declare function precognitionSuccess(): Response;
153
163
  */
154
164
  export declare function validateActionInput(req: EnhancedRequest, validations: ActionValidations): Promise<ValidationResult>;
155
165
  export declare function stream(source: ReadableStream | AsyncIterable<string | Uint8Array>, options?: StreamOptions): Response;
166
+ /** Test / hot-reload seam: forget the resolved module. */
167
+ export declare function clearCsrfModuleCache(): void;
156
168
  export declare function enhanceRequest(req: EnhancedRequest): EnhancedRequest;
157
169
  /**
158
170
  * Create a Stacks-enhanced router
@@ -252,24 +264,50 @@ declare interface StacksRouterConfig {
252
264
  }
253
265
  declare interface GroupOptions {
254
266
  prefix?: string
255
- middleware?: string | string[]
267
+ middleware?: MiddlewareReference | MiddlewareReference[]
256
268
  apiResponse?: boolean
257
269
  }
258
- declare interface ResourceRouteOptions {
259
- only?: ResourceAction[]
260
- except?: ResourceAction[]
261
- middleware?: string | string[]
270
+ /** The file-name half each CRUD action is composed from. */
271
+ declare interface ResourceKindOf {
272
+ index: 'Index'
273
+ store: 'Store'
274
+ show: 'Show'
275
+ update: 'Update'
276
+ destroy: 'Destroy'
262
277
  }
263
278
  /**
264
279
  * Chainable route interface for middleware and naming support
265
280
  */
266
- declare interface ChainableRoute {
267
- middleware: (name: string | readonly string[]) => ChainableRoute
281
+ export declare interface ChainableRoute {
282
+ middleware: (name: MiddlewareReference | readonly MiddlewareReference[]) => ChainableRoute
268
283
  name: (routeName: string) => ChainableRoute
269
284
  skipCsrf: () => ChainableRoute
270
285
  requireCsrf: () => ChainableRoute
271
286
  rateLimit: (max: number, window: 'second' | 'minute' | 'hour' | 'day' | number) => ChainableRoute
272
287
  }
288
+ /**
289
+ * Anything the router is willing to treat as an action.
290
+ *
291
+ * Structural rather than `instanceof Action`, because an action can also be a
292
+ * plain object with a `handle()` - the framework's own defaults include both
293
+ * shapes - and because a duplicated install would make an `instanceof` check
294
+ * reject a perfectly good action from the other copy of the package.
295
+ */
296
+ export declare interface RouterAction {
297
+ handle: (req: any) => unknown
298
+ validations?: ActionValidations
299
+ authorize?: (req: any) => unknown
300
+ before?: (req: any) => unknown
301
+ skipCsrf?: boolean
302
+ csrf?: boolean
303
+ apiResponse?: boolean
304
+ model?: unknown
305
+ modelDefinition?: unknown
306
+ name?: string
307
+ responses?: unknown
308
+ responseHeaders?: unknown
309
+ requestHeaders?: unknown
310
+ }
273
311
  /**
274
312
  * Helper for streaming responses — wraps a `ReadableStream` or async
275
313
  * generator with the right headers for the chosen content type.
@@ -306,18 +344,47 @@ export declare interface StreamOptions {
306
344
  export declare interface StacksRouterInstance {
307
345
  bunRouter: Router
308
346
  routes: Route[]
309
- get: (path: string, handler: StacksHandler) => ChainableRoute
310
- post: (path: string, handler: StacksHandler) => ChainableRoute
311
- put: (path: string, handler: StacksHandler) => ChainableRoute
312
- patch: (path: string, handler: StacksHandler) => ChainableRoute
313
- delete: (path: string, handler: StacksHandler) => ChainableRoute
314
- options: (path: string, handler: StacksHandler) => ChainableRoute
347
+ get: {
348
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
349
+ (path: string, handler: StacksHandler): ChainableRoute
350
+ }
351
+ post: {
352
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
353
+ (path: string, handler: StacksHandler): ChainableRoute
354
+ }
355
+ put: {
356
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
357
+ (path: string, handler: StacksHandler): ChainableRoute
358
+ }
359
+ patch: {
360
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
361
+ (path: string, handler: StacksHandler): ChainableRoute
362
+ }
363
+ delete: {
364
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
365
+ (path: string, handler: StacksHandler): ChainableRoute
366
+ }
367
+ options: {
368
+ <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
369
+ (path: string, handler: StacksHandler): ChainableRoute
370
+ }
315
371
  group: (options: GroupOptions, callback: () => void | Promise<void>) => StacksRouterInstance | Promise<StacksRouterInstance>
316
- resource: (name: string, handler: string, options?: ResourceRouteOptions) => StacksRouterInstance
317
- match: (methods: string[], path: string, handler: StacksHandler) => ChainableRoute
372
+ resource: <TBase extends string, TOnly extends ResourceAction = never, TExcept extends ResourceAction = never>(
373
+ name: string,
374
+ handler: TBase & ResourceBaseCheck<TBase, ActiveResourceActions<TOnly, TExcept>>,
375
+ options?: {
376
+ only?: readonly TOnly[]
377
+ except?: readonly TExcept[]
378
+ middleware?: MiddlewareReference | MiddlewareReference[]
379
+ },
380
+ ) => StacksRouterInstance
381
+ match: {
382
+ <TPath extends string>(methods: string[], path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
383
+ (methods: string[], path: string, handler: StacksHandler): ChainableRoute
384
+ }
318
385
  health: () => StacksRouterInstance
319
386
  use: (middleware: ActionHandler | ((req: EnhancedRequest, next: () => Promise<Response>) => Response | Promise<Response>)) => StacksRouterInstance
320
- register: (routePath: string, options?: { prefix?: string, middleware?: string | string[] }) => Promise<StacksRouterInstance>
387
+ register: (routePath: string, options?: { prefix?: string, middleware?: MiddlewareReference | MiddlewareReference[] }) => Promise<StacksRouterInstance>
321
388
  booting: (name: string, run: () => void | Promise<void>) => StacksRouterInstance
322
389
  serve: (options?: ServerOptions) => Promise<Server<unknown>>
323
390
  handleRequest: (req: Request) => Promise<Response>
@@ -326,8 +393,110 @@ export declare interface StacksRouterInstance {
326
393
  loadDiscoveredRoutes: () => Promise<void>
327
394
  }
328
395
  declare type RouteHandlerFn = (_req: EnhancedRequest) => Response | Promise<Response>;
329
- declare type StacksHandler = string | RouteHandlerFn;
396
+ /**
397
+ * An inline handler, as a route file writes one.
398
+ *
399
+ * Wider than {@link RouteHandlerFn} on purpose: a function handler's return
400
+ * value goes through `formatResult`, which turns an object into JSON, a string
401
+ * into text, `null` into a 204 and a stream into a streamed response. The type
402
+ * said `Response`, so `route.get('/x', () => ({ ok: true }))` - which works,
403
+ * and is the shape most handlers actually want - did not compile, and the
404
+ * workaround was to reach for `Response.json` or an `any`.
405
+ *
406
+ * `RouteHandlerFn` stays as it is: that is what a WRAPPED handler returns, and
407
+ * by then `formatResult` has already run.
408
+ */
409
+ declare type InlineRouteHandler = (_req: EnhancedRequest) => ActionResult | Promise<ActionResult>;
410
+ /**
411
+ * The same, with `request.params` narrowed to what the path declares.
412
+ *
413
+ * Declared as the FIRST overload on every route method so an inline arrow is
414
+ * contextually typed by it. A single parameter typed as the whole
415
+ * {@link StacksHandler} union gives TypeScript nothing to type an arrow with -
416
+ * `route.get('/users/{id}', req => req.params.slugTypo)` compiled and returned
417
+ * `undefined`, which is the failure a typed router exists to prevent.
418
+ */
419
+ declare type TypedInlineRouteHandler<TPath extends string> = (_req: RequestFor<TPath>) => ActionResult | Promise<ActionResult>;
420
+ export type StacksHandler = ActionPath | InlineRouteHandler | RouterAction;
330
421
  declare type ResourceAction = 'index' | 'store' | 'show' | 'update' | 'destroy';
422
+ /** `'PostAction'` → `'Post'`; anything else is left alone. */
423
+ declare type StripActionSuffix<T extends string> = T extends `${infer Base}Action` ? Base : T;
424
+ /** `'Post'` → `'Actions/Post'`; an explicit `'Actions/…'` base is left alone. */
425
+ declare type WithActionsPrefix<T extends string> = T extends `Actions/${string}` ? T : `Actions/${T}`;
426
+ /**
427
+ * The actions a call actually registers.
428
+ *
429
+ * `only` wins over `except`, matching the runtime: it checks `options.only`
430
+ * first and never looks at `except` when both are given.
431
+ */
432
+ declare type ActiveResourceActions<TOnly extends ResourceAction, TExcept extends ResourceAction> = [TOnly] extends [never]
433
+ ? ([TExcept] extends [never] ? ResourceAction : Exclude<ResourceAction, TExcept>)
434
+ : TOnly;
435
+ /** The action files a call needs, given its base and its active actions. */
436
+ declare type RequiredResourceActions<TBase extends string, TActive extends ResourceAction> = `${WithActionsPrefix<StripActionSuffix<TBase>>}${ResourceKindOf[TActive]}Action`;
437
+ /** Of those, the ones that do not exist. */
438
+ declare type MissingResourceActions<TBase extends string, TActive extends ResourceAction> = Exclude<RequiredResourceActions<TBase, TActive>, ActionPath>;
439
+ /**
440
+ * Every action a `resource()` call will register has to exist.
441
+ *
442
+ * Not "at least one of them" - that waves through the case this is really for.
443
+ * `Actions/Cms/Page` has Index, Store, Update and Destroy but no Show, so
444
+ * `route.resource('pages', 'Actions/Cms/Page')` registers a `GET /pages/{id}`
445
+ * that 500s the first time anybody opens a page, while
446
+ * `{ except: ['show'] }` is completely fine. Only the exact set answers that,
447
+ * which is why `only` and `except` are inferred as literals and read here.
448
+ *
449
+ * Resolves to `unknown` when nothing is missing - an intersection with
450
+ * `unknown` is the base itself - and otherwise to an object the base cannot
451
+ * satisfy, whose property name puts the missing files in the error message.
452
+ */
453
+ declare type ResourceBaseCheck<TBase extends string, TActive extends ResourceAction> = [MissingResourceActions<TBase, TActive>] extends [never]
454
+ ? unknown
455
+ : { 'these actions do not exist': MissingResourceActions<TBase, TActive> }
456
+ /**
457
+ * Generate a full URL for a named route, like Laravel's route() helper.
458
+ *
459
+ * Validates path parameters at call time so a typo'd argument
460
+ * (`url('user.post', { userId: 1 })` against `/users/{id}`) throws
461
+ * immediately with a list of expected names instead of silently
462
+ * producing a URL with `{id}` left literal in the path.
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * // Define a named route
467
+ * route.get('/api/email/unsubscribe', 'Actions/UnsubscribeAction').name('email.unsubscribe')
468
+ *
469
+ * // Generate URL
470
+ * url('email.unsubscribe', { token: 'abc-123' })
471
+ * // → https://stacksjs.com/api/email/unsubscribe?token=abc-123
472
+ *
473
+ * // With path parameters
474
+ * route.get('/users/{id}/posts/{postId}', handler).name('user.post')
475
+ * url('user.post', { id: 42, postId: 7 })
476
+ * // → https://stacksjs.com/users/42/posts/7
477
+ * ```
478
+ */
479
+ /**
480
+ * The params a named route needs, plus anything else that becomes query string.
481
+ *
482
+ * The required half comes from the path the name resolves to, so
483
+ * `url('user.post', { id: 42 })` against `/users/{id}/posts/{postId}` stops
484
+ * compiling instead of throwing at call time. Extra keys stay allowed: the
485
+ * implementation appends whatever it did not consume as a query string, which
486
+ * is what `url('email.unsubscribe', { token })` relies on.
487
+ */
488
+ export type UrlParams<TName extends string> = { [K in keyof ExtractRouteParams<PathForRouteName<TName>>]: string | number }
489
+ & Record<string, string | number>;
490
+ /** The keys of `T` that are not optional. */
491
+ declare type RequiredParamKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];
492
+ /**
493
+ * Whether `url()` must be given a second argument.
494
+ *
495
+ * Keyed on REQUIRED params: a path whose only placeholder is optional is
496
+ * reachable with nothing at all, and demanding an empty object for it would be
497
+ * the type getting in the way of the truth.
498
+ */
499
+ declare type RequiresUrlParams<TName extends string> = [RequiredParamKeys<ExtractRouteParams<PathForRouteName<TName>>>] extends [never] ? false : true;
331
500
  /**
332
501
  * Per-request read-routing context.
333
502
  *
@@ -1,6 +1,6 @@
1
1
  import{response}from"@stacksjs/bun-router";import{Middleware}from"./middleware";import"./request-augmentation";import process from"node:process";import{Buffer}from"node:buffer";import{existsSync}from"node:fs";import{timingSafeEqual}from"node:crypto";import{collect}from"@stacksjs/collections";import{log,report}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{UploadedFile}from"@stacksjs/storage";import{applyRequestEnhancements,Router}from"@stacksjs/bun-router";import{checkApplicationHealth}from"./health";const ROUTER_INSTANCES_KEY=Symbol.for("@stacksjs/router:loaded-instances"),loadedRouterInstances=globalThis[ROUTER_INSTANCES_KEY]??=new Set;loadedRouterInstances.add(import.meta.path);const MULTI_INSTANCE_WARNED_KEY=Symbol.for("@stacksjs/router:multi-instance-warned"),bootHooks=[];let bootHooksRun=!1;export async function runBootHooks(){if(bootHooksRun)return;bootHooksRun=!0;for(const hook of bootHooks)try{await hook.run()}catch(error){log.error(`[router] boot hook "${hook.name}" failed:`,error)}}export function resetBootHooks(){bootHooks.length=0;bootHooksRun=!1}export function warnOnMultipleRouterInstances(){if(loadedRouterInstances.size<=1)return!1;const g=globalThis;if(!g[MULTI_INSTANCE_WARNED_KEY]){g[MULTI_INSTANCE_WARNED_KEY]=!0;const paths=[...loadedRouterInstances].map((p)=>` - ${p}`).join(`
2
2
  `);log.warn(`${loadedRouterInstances.size} distinct @stacksjs/router modules loaded in one process; they now share one route table (stacksjs/stacks#1982) so routing still works, but this is a duplicated install worth fixing. It usually means an app vendors storage/framework/core AND installs the published @stacksjs/* dist, and a tsconfig \`paths\` mapping (\`@stacksjs/* -> ./*/src\`) splits module resolution between core files and root files. See stacksjs/stacks#1975.
3
3
  Loaded instances:
4
- ${paths}`)}return!0}let __defaultsPkgRoot;function resolveDefaultsPath(rel){const vendored=p.storagePath(`framework/defaults/${rel}`);if(existsSync(vendored))return vendored;if(__defaultsPkgRoot===void 0)try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());__defaultsPkgRoot=pkgJson.slice(0,pkgJson.lastIndexOf("/"))}catch{__defaultsPkgRoot=null}return __defaultsPkgRoot?`${__defaultsPkgRoot}/${rel}`:vendored}import{runWithRequest}from"./request-context";import{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";import{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse}from"./error-handler";import{rateLimit as enforceRateLimit}from"./rate-limit";import{applySecurityHeaders}from"./security-headers";import{isCursorPaginator,isPaginator,isSimplePaginator}from"@stacksjs/orm";const csrfSkipRegistry=new Set,csrfRequireRegistry=new Set,routeRateLimitRegistry=new Map;function rateLimitWindowToSeconds(window){if(typeof window==="number"){if(!Number.isFinite(window)||window<=0)throw Error(`[Router] .rateLimit(): window must be a positive number of seconds, got ${window}`);return Math.floor(window)}switch(window){case"second":return 1;case"minute":return 60;case"hour":return 3600;case"day":return 86400;default:throw Error(`[Router] .rateLimit(): unknown period '${String(window)}'`)}}class BoundedMap{max;map=new Map;constructor(max){this.max=max}get(key){return this.map.get(key)}has(key){return this.map.has(key)}set(key,value){if(this.map.has(key))this.map.delete(key);this.map.set(key,value);if(this.map.size>this.max){const oldest=this.map.keys().next().value;if(oldest!==void 0)this.map.delete(oldest)}return this}delete(key){return this.map.delete(key)}clear(){this.map.clear()}get size(){return this.map.size}}function isExposeRoutesAuthorized(req){const flag=process.env.STACKS_EXPOSE_ROUTES??"";if(!flag)return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");if(flag==="1")return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");const url=new URL(req.url),submitted=req.headers.get("x-stacks-routes-token")||req.headers.get("X-Stacks-Routes-Token")||url.searchParams.get("token")||"";if(typeof submitted!=="string"||submitted.length===0||submitted.length!==flag.length)return!1;try{return timingSafeEqual(Buffer.from(submitted),Buffer.from(flag))}catch{return!1}}async function applyCorsIfConfigured(req,response){if(!req._corsConfig||!response)return response;try{const{applyCorsHeaders}=await import(resolveDefaultsPath("app/Middleware/Cors.ts"));return applyCorsHeaders(req,response,req._corsConfig)}catch(err){log.warn("[router] CORS header injection failed",{error:err});return response}}const ACTION_CACHE_MAX=5000,actionSkipsCsrfCache=new BoundedMap(ACTION_CACHE_MAX),routeHandlerKeyRegistry=new BoundedMap(ACTION_CACHE_MAX),CSRF_PROTECTED_METHODS=new Set(["POST","PUT","PATCH","DELETE"]),namedRouteRegistry=new Map;function compileNamedRoute(path){const paramNames=extractRouteParamNames(path),colonRegex=new Map;for(const name of paramNames)colonRegex.set(name,new RegExp(`(^|/):${name}(?=$|/)`,"g"));return{path,paramNames,colonRegex}}function extractRouteParamNames(routePath){const names=new Set;for(const m of routePath.matchAll(/\{(\w+)\}/g))if(m[1])names.add(m[1]);for(const m of routePath.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(m[1])names.add(m[1]);return[...names]}export function url(routeName,params={}){const named=namedRouteRegistry.get(routeName);if(!named)throw Error(`Route '${routeName}' is not defined. Available routes: ${[...namedRouteRegistry.keys()].join(", ")}`);const missing=named.paramNames.filter((name)=>!(name in params)||params[name]===void 0);if(missing.length>0)throw Error(`url('${routeName}'): missing required path param${missing.length>1?"s":""} [${missing.join(", ")}] for path '${named.path}'. Pass them as the second argument: url('${routeName}', { ${named.paramNames.join(", ")} })`);let appUrl;try{appUrl=process.env.APP_URL||"https://localhost"}catch{appUrl="https://localhost"}appUrl=appUrl.replace(/\/$/,"");if(!appUrl.startsWith("http"))appUrl=`https://${appUrl}`;let resolvedPath=named.path;const queryParams={};for(const[key,value]of Object.entries(params)){const curly=`{${key}}`;if(resolvedPath.includes(curly))resolvedPath=resolvedPath.replaceAll(curly,encodeURIComponent(String(value)));else{const re=named.colonRegex.get(key);if(re&&re.test(resolvedPath)){re.lastIndex=0;resolvedPath=resolvedPath.replace(re,`$1${encodeURIComponent(String(value))}`)}else queryParams[key]=String(value)}}const queryString=Object.keys(queryParams).length>0?`?${new URLSearchParams(queryParams).toString()}`:"";return`${appUrl}${resolvedPath}${queryString}`}export function routeParams(routeName){const named=namedRouteRegistry.get(routeName);return named?[...named.paramNames]:[]}export function listRegisteredRoutes(){const out=[],seen=new Set;for(const key of routeMiddlewareRegistry.keys()){if(seen.has(key))continue;seen.add(key);const idx=key.indexOf(":");if(idx===-1)continue;const method=key.slice(0,idx),path=key.slice(idx+1);let routeName;for(const[n,named]of namedRouteRegistry.entries())if(named.path===path){routeName=n;break}out.push({method,path,name:routeName,handler:routeHandlerKeyRegistry.get(key)})}return out.sort((a,b)=>a.path.localeCompare(b.path))}const DEFAULT_MIDDLEWARE_PRIORITY=10,_warnedInvalidPriorities=new Set;function warnInvalidMiddlewarePriority(name,raw){const key=`${name}:${String(raw)}`;if(_warnedInvalidPriorities.has(key))return;_warnedInvalidPriorities.add(key);log.warn(`[Router] Middleware '${name}' declared an invalid priority (${String(raw)}). Priorities must be a finite non-negative number; falling back to default ${DEFAULT_MIDDLEWARE_PRIORITY}.`)}function adaptMiddlewareForBunRouter(middleware){if(middleware instanceof Middleware)return middleware.toRouterHandler();if(middleware&&typeof middleware==="object"&&typeof middleware.handle==="function"&&typeof middleware!=="function"){const handle=middleware.handle.bind(middleware);return async(req,next)=>{try{await handle(req)}catch(thrown){if(thrown instanceof Response)return thrown;throw thrown}return next()}}return middleware}const middlewareCache=new Map;let middlewareAliasesPromise=null;async function getMiddlewareAliases(){if(middlewareAliasesPromise)return middlewareAliasesPromise;middlewareAliasesPromise=(async()=>{try{return(await import(p.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(resolveDefaultsPath("app/Middleware.ts"))).default||{}}catch{return{}}}})();return middlewareAliasesPromise}const PASCAL_SPLIT_REGEX=/[-_\s]+/,pascalCaseCache=new Map;function toPascalCase(input){if(!input)return input;const cached=pascalCaseCache.get(input);if(cached!==void 0)return cached;const out=input.split(PASCAL_SPLIT_REGEX).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join("");pascalCaseCache.set(input,out);return out}async function resolveMiddlewareName(name){const resolved=(await getMiddlewareAliases())[name]||toPascalCase(name);log.debug(`[middleware] Resolved: ${name} \u2192 ${resolved}`);return resolved}async function loadMiddleware(name){if(middlewareCache.has(name))return middlewareCache.get(name)??null;const className=await resolveMiddlewareName(name);let userPathError;try{const userPath=p.appPath(`Middleware/${className}.ts`),handler=(await import(userPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${userPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){userPathError=err}try{const defaultPath=resolveDefaultsPath(`app/Middleware/${className}.ts`),handler=(await import(defaultPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${defaultPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){const userMsg=userPathError instanceof Error?userPathError.message:String(userPathError);log.error(`[Router] Failed to load middleware '${name}' (resolved to '${className}'). app/Middleware: ${userMsg}; defaults:`,err);return null}}export function clearMiddlewareCache(){middlewareCache.clear();middlewareAliasesPromise=null;actionSkipsCsrfCache.clear();routeHandlerKeyRegistry.clear()}export function installMiddlewareHotReload(){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")return()=>{};let fsWatchers=[];(async()=>{try{const fs=await import("node:fs"),targets=[p.appPath("Middleware"),p.appPath("Middleware.ts")];for(const target of targets)try{if(!fs.existsSync(target))continue;const w=fs.watch(target,{recursive:!0},()=>{log.debug("[middleware] hot-reload: clearing cache");clearMiddlewareCache()});fsWatchers.push(w)}catch{}}catch{}})();return()=>{for(const w of fsWatchers)try{w.close()}catch{}fsWatchers=[]}}const routeMiddlewareRegistry=new Map;export function clearRouteMiddlewareRegistry(){routeMiddlewareRegistry.clear()}const routeApiResponseRegistry=new Set;function parseMiddlewareName(middleware){const colonIndex=middleware.indexOf(":");if(colonIndex===-1)return{name:middleware};return{name:middleware.substring(0,colonIndex),params:middleware.substring(colonIndex+1)}}export async function findUnresolvableRouteMiddleware(){const usage=new Map;for(const[routeKey,entries]of routeMiddlewareRegistry)for(const entry of entries){const{name}=parseMiddlewareName(entry),routes=usage.get(name)??[];routes.push(routeKey);usage.set(name,routes)}if(!usage.has("csrf"))usage.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);const unresolvable=[];for(const[alias,routes]of usage){const handler=await loadMiddleware(alias);if(!handler||typeof handler.handle!=="function")unresolvable.push({alias,routes})}return unresolvable}export async function assertRouteMiddlewareResolvable(){const unresolvable=await findUnresolvableRouteMiddleware();if(unresolvable.length===0)return;const detail=unresolvable.map((u)=>`"${u.alias}" (used by ${u.routes.join(", ")})`).join("; ");throw Error(`[Router] Unresolvable middleware alias(es): ${detail}. Check the alias map in app/Middleware.ts or add app/Middleware/<Class>.ts.`)}function createMiddlewareHandler(routeKey,handler){const wrappedBase=wrapHandler(handler,!0);let actionPrefetch=null;if(typeof handler==="string"){const method=routeKey.slice(0,routeKey.indexOf(":")).toUpperCase();if(CSRF_PROTECTED_METHODS.has(method))actionPrefetch=resolveStringHandler(handler).then(()=>{return}).catch(()=>{return})}return async(req)=>{try{await parseRequestBody(req)}catch(err){const error=err instanceof Error?err:Error(String(err));return createMiddlewareErrorResponse(error,req)}const enhancedReq=enhanceRequest(req);await seedCsrfTokenForRender(enhancedReq);if(actionPrefetch)await actionPrefetch;if(routeApiResponseRegistry.has(routeKey))req._forceJson=!0;return runWithRequest(enhancedReq,async()=>{const rl=routeRateLimitRegistry.get(routeKey);if(rl)try{await enforceRateLimit(routeKey,rl.max).over(rl.windowSeconds)}catch(err){return createMiddlewareErrorResponse(err,req)}const userMiddleware=routeMiddlewareRegistry.get(routeKey)||[],method=req.method.toUpperCase(),middlewareEntries=[...userMiddleware],alreadyHasCsrf=userMiddleware.some((m)=>m==="csrf"||m.startsWith("csrf:")),routeSkipped=csrfSkipRegistry.has(routeKey),routeRequired=csrfRequireRegistry.has(routeKey),handlerKey=routeHandlerKeyRegistry.get(routeKey),actionSkipped=handlerKey?actionSkipsCsrfCache.get(handlerKey)===!0:!1;if(CSRF_PROTECTED_METHODS.has(method)&&!alreadyHasCsrf&&(routeRequired||!routeSkipped&&!actionSkipped))middlewareEntries.unshift("csrf");if(middlewareEntries.length>0){const lvl=(process.env.LOG_LEVEL||"info").toLowerCase();if(lvl!=="info"&&lvl!=="warn"&&lvl!=="error"){const schemeEnd=req.url.indexOf("://"),pathStart=schemeEnd===-1?0:req.url.indexOf("/",schemeEnd+3),q=req.url.indexOf("?",pathStart<0?0:pathStart),urlPath=pathStart<0?"/":req.url.slice(pathStart,q===-1?void 0:q);log.debug(`[middleware] Executing chain: [${middlewareEntries.join(", ")}] for ${method} ${urlPath}`)}}const resolved=[];for(const middlewareEntry of middlewareEntries){const{name:middlewareName,params}=parseMiddlewareName(middlewareEntry);if(params){enhancedReq._middlewareParams=enhancedReq._middlewareParams||{};enhancedReq._middlewareParams[middlewareName]=params}const middleware=await loadMiddleware(middlewareName);if(!middleware||typeof middleware.handle!=="function"){log.error(`[Router] Middleware '${middlewareName}' on ${routeKey} could not be resolved - failing closed`);const failClosedError=Error(`Middleware '${middlewareName}' could not be resolved`),failClosedResponse=await createErrorResponse(failClosedError,enhancedReq,{status:500});return await applyCorsIfConfigured(enhancedReq,failClosedResponse)}const rawPriority=middleware.priority;let priority=DEFAULT_MIDDLEWARE_PRIORITY;if(typeof rawPriority==="number"&&Number.isFinite(rawPriority)&&rawPriority>=0)priority=rawPriority;else if(rawPriority!==void 0)warnInvalidMiddlewarePriority(middlewareName,rawPriority);resolved.push({name:middlewareName,handler:middleware,priority})}resolved.sort((a,b)=>a.priority-b.priority);const middlewareTimings=[];for(const{name:middlewareName,handler:middleware}of resolved){const mwStart=process.hrtime.bigint();let mwTimer;try{const MIDDLEWARE_TIMEOUT_MS=30000,timeoutPromise=new Promise((_,reject)=>{mwTimer=setTimeout(()=>reject(Error(`Middleware '${middlewareName}' exceeded ${MIDDLEWARE_TIMEOUT_MS}ms`)),MIDDLEWARE_TIMEOUT_MS)});await Promise.race([middleware.handle(enhancedReq),timeoutPromise]);const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs})}catch(error){const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs});log.debug(`[middleware] Blocked by: ${middlewareName}`);if(error instanceof Response){try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)error.headers.set("Server-Timing",parts.join(", "));if(reqId)error.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,error)}const err=error instanceof Error?error:Error(String(error)),errorResponse="statusCode"in err||"status"in err?await createMiddlewareErrorResponse(err,enhancedReq):await(()=>{log.error(`[Router] Middleware '${middlewareName}' threw an unexpected error:`,err);return createErrorResponse(err,enhancedReq,{status:500})})();try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)errorResponse.headers.set("Server-Timing",parts.join(", "));if(reqId)errorResponse.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,errorResponse)}finally{clearTimeout(mwTimer)}}let response=await wrappedBase(enhancedReq);clearTrackedQueries();if(response){if(req.method==="GET"||req.method==="HEAD"||req.method==="OPTIONS")try{const{seedCsrfCookieIfMissing}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts"));response=seedCsrfCookieIfMissing(enhancedReq,response,enhancedReq._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed",{error:err})}}if(response)response=await applyCorsIfConfigured(enhancedReq,response);const{_requestId:reqId,_startNs:startNs}=enhancedReq,durMs=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,setHeaders=(h)=>{const after=enhancedReq._afterResponse;if(Array.isArray(after))for(const callback of after)try{if(typeof callback==="function")callback({status:response?.status??0,durationMs:durMs??0})}catch{}const requested=enhancedReq._responseHeaders;if(requested&&typeof requested==="object"){for(const[name,value]of Object.entries(requested))if(typeof value==="string")h.set(name,value)}if(reqId)h.set("X-Request-ID",reqId);if(durMs!=null){const parts=[`total;dur=${durMs.toFixed(1)}`];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}h.set("Server-Timing",parts.join(", "))}applySecurityHeaders(h)};if(response&&typeof response.headers?.set==="function"){if(response.status>=400&&(response.headers.get("content-type")||"").includes("json")&&reqId)try{const text=await response.clone().text(),parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"){const newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(JSON.stringify({...parsed,request_id:reqId}),{status:response.status,statusText:response.statusText,headers:newHeaders})}}catch{}try{setHeaders(response.headers)}catch{try{const cloned=response.clone(),newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(cloned.body,{status:response.status,statusText:response.statusText,headers:newHeaders})}catch{}}}if(enhancedReq._compress===!0&&response)try{const{applyCompression}=await import(resolveDefaultsPath("app/Middleware/Compress.ts"));return await applyCompression(enhancedReq,response)}catch(err){log.warn(`[router] Compression failed; sending uncompressed response: ${err instanceof Error?err.message:String(err)}`)}return response})}}function createInertRoute(){const inert={middleware:()=>inert,name:()=>inert,skipCsrf:()=>inert,requireCsrf:()=>inert,rateLimit:()=>inert};return inert}function createChainableRoute(routeKey,shadowed=!1){if(shadowed)return createInertRoute();if(!routeMiddlewareRegistry.has(routeKey))routeMiddlewareRegistry.set(routeKey,[]);const routePath=routeKey.includes(":")?routeKey.substring(routeKey.indexOf(":")+1):routeKey,chain={middleware(name){const middlewareList=routeMiddlewareRegistry.get(routeKey);if(!middlewareList)return chain;for(const entry of Array.isArray(name)?name:[name]){if(typeof entry!=="string")throw TypeError(`[Router] middleware() on ${routeKey} was given a ${typeof entry}; it takes an alias or an array of aliases`);middlewareList.push(entry)}return chain},name(routeName){namedRouteRegistry.set(routeName,compileNamedRoute(routePath));return chain},skipCsrf(){csrfSkipRegistry.add(routeKey);csrfRequireRegistry.delete(routeKey);return chain},requireCsrf(){csrfRequireRegistry.add(routeKey);csrfSkipRegistry.delete(routeKey);return chain},rateLimit(max,window){if(!Number.isFinite(max)||max<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(max)}`);const windowSeconds=rateLimitWindowToSeconds(window);routeRateLimitRegistry.set(routeKey,{max:Math.floor(max),windowSeconds});return chain}};return chain}async function fileExists(path){try{return await Bun.file(path).exists()}catch{return!1}}function assertSafeHandlerPath(handlerPath){if(typeof handlerPath!=="string"||handlerPath.length===0)throw Error(`[Router] Refusing to resolve handler '${String(handlerPath)}': empty or non-string`);if(handlerPath.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if(handlerPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(handlerPath))throw Error(`[Router] Refusing to resolve absolute handler path '${handlerPath}'`);if(handlerPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[Router] Refusing to resolve handler path '${handlerPath}' (contains '..' segment)`)}const _moduleImportCache=new Map;function cachedImport(fullPath){let p=_moduleImportCache.get(fullPath);if(!p){p=import(fullPath);_moduleImportCache.set(fullPath,p)}return p}const _resolvedHandlerCache=new Map;function resolveStringHandler(handlerPath){let resolved=_resolvedHandlerCache.get(handlerPath);if(!resolved){resolved=resolveStringHandlerUncached(handlerPath);_resolvedHandlerCache.set(handlerPath,resolved);resolved.catch(()=>_resolvedHandlerCache.delete(handlerPath))}return resolved}function validationFailureResponse(errors){return response.validationError(errors)}export function precognitionRequest(req){const header=req.headers?.get?.("Precognition"),viaHeader=typeof header==="string"&&header.toLowerCase()==="true";let viaQuery=!1;try{viaQuery=new URL(req.url).searchParams.get("_validate")==="1"}catch{viaQuery=!1}if(!viaHeader&&!viaQuery)return null;return{only:(req.headers?.get?.("Precognition-Validate-Only")??"").split(",").map((field)=>field.trim()).filter(Boolean)}}export function precognitionSuccess(){return new Response(null,{status:204,headers:{Precognition:"true","Precognition-Success":"true",Vary:"Precognition, Precognition-Validate-Only"}})}async function resolveStringHandlerUncached(handlerPath){assertSafeHandlerPath(handlerPath);let modulePath=handlerPath;modulePath=modulePath.endsWith(".ts")?modulePath.slice(0,-3):modulePath;if(modulePath.includes("Controller")){const[controllerPath,methodName="index"]=modulePath.split("@"),userPath=p.appPath(`${controllerPath}.ts`),defaultPath=resolveDefaultsPath(`app/${controllerPath}.ts`),fullPath=await fileExists(userPath)?userPath:defaultPath;try{const controller=await cachedImport(fullPath);if(!controller.default||typeof controller.default!=="function")throw Error(`Controller ${controllerPath} does not export a default class`);const instance=new controller.default;if(typeof instance[methodName]!=="function")throw Error(`Method ${methodName} not found in controller ${controllerPath}`);return async(req)=>{const result=await instance[methodName](req);return formatResult(result,req)}}catch(error){log.error(`[Router] Failed to load controller '${fullPath}':`,error);throw error}}let fullPath;if(modulePath.includes("storage/framework/orm"))fullPath=modulePath;else if(modulePath.includes("OrmAction"))fullPath=p.storagePath(`framework/actions/src/${modulePath}.ts`);else if(modulePath.includes("Actions")){const userPath=p.projectPath(`app/${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}else{const userPath=p.appPath(`${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}try{const action=(await cachedImport(fullPath)).default;if(!action)throw Error(`Action '${handlerPath}' has no default export`);if(typeof action.handle!=="function"){log.error(`[Router] Action '${handlerPath}' structure:`,Object.keys(action));throw Error(`Action '${handlerPath}' has no handle() method. Got: ${typeof action.handle}`)}const actionSkipsCsrf=action.skipCsrf===!0||action.csrf===!1;actionSkipsCsrfCache.set(handlerPath,actionSkipsCsrf);const actionForcesJson=action.apiResponse===!0;return async(req)=>{if(actionSkipsCsrf)req._skipCsrf=!0;if(actionForcesJson)req._forceJson=!0;req._requestValidationRules=action.validations??modelValidationRules(action.modelDefinition??action.model);try{const precognition=precognitionRequest(req);if(precognition){if(!action.validations)return precognitionSuccess();const rules=precognition.only.length>0?Object.fromEntries(Object.entries(action.validations).filter(([field])=>precognition.only.includes(field))):action.validations,precognitionResult=await validateActionInput(req,rules);return precognitionResult.valid?precognitionSuccess():validationFailureResponse(precognitionResult.errors)}if(action.validations){const validationResult=await validateActionInput(req,action.validations);if(!validationResult.valid)return validationFailureResponse(validationResult.errors)}if(typeof action.authorize==="function"){const auth=await action.authorize(req);if(auth instanceof Response)return auth;if(auth===!1)return Response.json({error:"Forbidden"},{status:403})}if(typeof action.before==="function"){const pre=await action.before(req);if(pre instanceof Response)return pre}const result=await action.handle(req);return formatResult(result,req)}catch(handleError){report(handleError,{label:`[Router] action.handle() for '${handlerPath}'`});throw handleError}}}catch(importError){log.error(`[Router] Failed to import action '${fullPath}':`,importError);throw importError}}export async function validateActionInput(req,validations){const errors={},input=await getRequestInput(req,validations);for(const[field,validation]of Object.entries(validations)){const value=input[field];let result;try{result=validation.rule.validate(value)}catch{result={valid:!1,errors:[{message:`${field} validation failed`}]}}if(!result.valid){const fieldErrors=[],label=field.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(c)=>c.toUpperCase()),decorate=(msg)=>msg.toLowerCase().startsWith(field.toLowerCase())||msg.includes(label)?msg:`${label} ${msg}`;if(result.errors&&result.errors.length>0)if(validation.message){const firstMessage=result.errors[0]?.message??"";fieldErrors.push(typeof validation.message==="string"?validation.message:validation.message[field]||decorate(firstMessage))}else result.errors.forEach((err)=>fieldErrors.push(decorate(err.message)));else fieldErrors.push(validation.message?typeof validation.message==="string"?validation.message:`${label} is invalid`:`${label} is invalid`);errors[field]=fieldErrors}}return{valid:Object.keys(errors).length===0,errors}}function modelValidationRules(model){if(!model?.attributes||typeof model.attributes!=="object")return;const rules={};for(const[field,attribute]of Object.entries(model.attributes)){const validation=attribute?.validation;if(validation?.rule)rules[field]=validation}return Object.keys(rules).length>0?rules:void 0}async function getRequestInput(req,validations){const input={},q=req.query;if(q)for(const key in q)input[key]=q[key];else new URL(req.url).searchParams.forEach((value,key)=>{input[key]=value});if(req.params)Object.assign(input,req.params);if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);else if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(typeof req.allFiles==="function")try{const files=req.allFiles();for(const key of Object.keys(files??{}))if(!(key in input))input[key]=files[key]}catch{}if(!validations)return input;for(const[field,validation]of Object.entries(validations)){const value=input[field];if(typeof value!=="string")continue;const validatorName=validation.rule?.name;if(validatorName==="number"){const n=Number(value);if(Number.isFinite(n))input[field]=n}else if(validatorName==="boolean"){if(value==="true"||value==="1")input[field]=!0;else if(value==="false"||value==="0")input[field]=!1}}return input}function formatResult(result,req){if(result instanceof Response)return result;if(result instanceof ReadableStream)return new Response(result,{headers:{"Content-Type":"application/octet-stream"}});const apiShaped=req._forceJson===!0||isApiRequest(req);if(result===null||result===void 0)return apiShaped?new Response(null,{status:204}):new Response("",{status:200});if(typeof result==="object"){const linkHeader=buildPaginatorLinkHeader(result);if(linkHeader)return Response.json(result,{headers:{Link:linkHeader}});return Response.json(result)}if(apiShaped)return Response.json(result);return new Response(String(result),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function buildPaginatorLinkHeader(value){if(!isPaginator(value)&&!isSimplePaginator(value)&&!isCursorPaginator(value))return null;const v=value,parts=[];if(v.prev_page_url)parts.push(`<${v.prev_page_url}>; rel="prev"`);if(v.next_page_url)parts.push(`<${v.next_page_url}>; rel="next"`);if(v.first_page_url)parts.push(`<${v.first_page_url}>; rel="first"`);if(v.last_page_url)parts.push(`<${v.last_page_url}>; rel="last"`);return parts.length>0?parts.join(", "):null}export function stream(source,options={}){const baseHeaders={};if(options.type==="sse"){baseHeaders["Content-Type"]="text/event-stream; charset=utf-8";baseHeaders["Cache-Control"]="no-cache";baseHeaders.Connection="keep-alive"}else if(options.type==="ndjson")baseHeaders["Content-Type"]="application/x-ndjson; charset=utf-8";else baseHeaders["Content-Type"]=options.contentType??"application/octet-stream";const body=source instanceof ReadableStream?source:new ReadableStream({async start(controller){try{for await(const chunk of source)controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):chunk);controller.close()}catch(err){controller.error(err)}}}),merged=new Headers(baseHeaders);if(options.headers)new Headers(options.headers).forEach((value,key)=>merged.set(key,value));return new Response(body,{status:options.status??200,headers:merged})}function getAllInputFor(req){const cached=req._allInputCache;if(cached)return cached;const input={},query=req.query;if(query)for(const key in query)input[key]=query[key];if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(req.params&&typeof req.params==="object")Object.assign(input,req.params);req._allInputCache=input;return input}function flashInputFor(req,keys){const input=getAllInputFor(req);req._oldInput=keys?Object.fromEntries(keys.filter((key)=>(key in input)).map((key)=>[key,input[key]])):{...input}}const REQUEST_METHODS={get(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},input(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},all(){return getAllInputFor(this)},only(keys){const input=getAllInputFor(this),result={};for(const key of keys)if(key in input)result[key]=input[key];return result},except(keys){const result={...getAllInputFor(this)};for(const key of keys)delete result[key];return result},has(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>(k in input)&&input[k]!==void 0);return key in input&&input[key]!==void 0},hasAny(keys){const input=getAllInputFor(this);return keys.some((k)=>(k in input)&&input[k]!==void 0)},filled(key){const input=getAllInputFor(this),isFilled=(k)=>{const value=input[k];return value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0)};if(Array.isArray(key))return key.every(isFilled);return isFilled(key)},missing(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>!(k in input)||input[k]===void 0);return!(key in input)||input[key]===void 0},merge(data){Object.assign(getAllInputFor(this),data)},keys(){return Object.keys(getAllInputFor(this))},string(key,defaultValue=""){const value=getAllInputFor(this)[key];return value!==void 0&&value!==null?String(value):defaultValue},integer(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?Math.trunc(value):defaultValue;const str=String(value).trim();if(!/^-?\d+$/.test(str))return defaultValue;const parsed=Number.parseInt(str,10);return Number.isFinite(parsed)?parsed:defaultValue},float(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?value:defaultValue;const str=String(value).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(str))return defaultValue;const parsed=Number.parseFloat(str);return Number.isFinite(parsed)?parsed:defaultValue},boolean(key,defaultValue=!1){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return defaultValue;if(typeof value==="boolean")return value;if(value==="true"||value==="1"||value===1)return!0;if(value==="false"||value==="0"||value===0)return!1;return defaultValue},array(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return value;return value!==void 0&&value!==null?[value]:[]},date(key){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return null;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?null:parsed},enum(key,enumType){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return null;if(Object.values(enumType).includes(value))return value;const enumKey=String(value);return enumKey in enumType?enumType[enumKey]:null},collect(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return collect(value);return collect(value===void 0||value===null?[]:[value])},whenHas(key,callback,defaultCallback){const input=getAllInputFor(this);if(key in input&&input[key]!==void 0)callback(input[key]);else defaultCallback?.()},whenFilled(key,callback,defaultCallback){const value=getAllInputFor(this)[key];if(value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0))callback(value);else defaultCallback?.()},isValue(key,value){return getAllInputFor(this)[key]===value},async validate(rules,messages={}){const selectedRules=rules??this._requestValidationRules;if(!selectedRules||Object.keys(selectedRules).length===0){const input=getAllInputFor(this);this._validatedInput=input;return input}const normalized={};for(const[field,definition]of Object.entries(selectedRules)){if(typeof definition==="string")throw TypeError(`String validation rules are not supported for "${field}". Use schema validators.`);if(definition&&typeof definition==="object"&&"rule"in definition){const message=messages[field];normalized[field]=message?{...definition,message}:definition}else normalized[field]=definition}const{validate}=await import("@stacksjs/validation"),validated=await validate(this,normalized);this._validatedInput=validated;return validated},getValidated(){return this._validatedInput??{}},safe(){const data=this._validatedInput??{};return{all:()=>({...data}),get:(key,defaultValue)=>(key in data)?data[key]:defaultValue,only:(keys)=>Object.fromEntries(keys.filter((key)=>(key in data)).map((key)=>[key,data[key]])),except:(keys)=>Object.fromEntries(Object.entries(data).filter(([key])=>!keys.includes(key)))}},old(key,defaultValue){return this._oldInput?.[key]??defaultValue},flashInput(keys){flashInputFor(this,keys)},flashInputOnly(keys){flashInputFor(this,keys)},flashInputExcept(keys){const input=getAllInputFor(this);this._oldInput=Object.fromEntries(Object.entries(input).filter(([key])=>!keys.includes(key)))},file(key){const file=(this.files||{})[key];if(!file)return null;const rawFile=Array.isArray(file)?file[0]:file;return rawFile?new UploadedFile(rawFile):null},getFiles(key){const file=(this.files||{})[key];if(!file)return[];return(Array.isArray(file)?file:[file]).map((f)=>new UploadedFile(f))},hasFile(key){const files=this.files||{};return key in files&&files[key]!==void 0},allFiles(){const files=this.files||{},result={};for(const[key,value]of Object.entries(files))if(Array.isArray(value))result[key]=value.map((f)=>new UploadedFile(f));else result[key]=new UploadedFile(value);return result},getParams(){return{...this.params}},isEmpty(){return Object.keys(getAllInputFor(this)).length===0},browser(){return this.headers.get("sec-ch-ua")||this.headers.get("user-agent")},ipForRateLimit(){const ip=this.ip;if(typeof ip==="function")return ip.call(this)||null;return typeof ip==="string"&&ip?ip:null},getMethod(){return this.method.toUpperCase()},async user(){return this._authenticatedUser},async userToken(){return this._currentAccessToken},async tokenCan(ability){if(typeof ability!=="string"||ability.length===0)return!1;const token=this._currentAccessToken;if(!token||typeof token!=="object")return!1;if(!Array.isArray(token.abilities))return!1;if(token.abilities.includes("*"))return!0;return token.abilities.includes(ability)},async tokenCant(ability){return!await this.tokenCan(ability)},async can(ability,...args){if(typeof ability!=="string"||ability.length===0)return!1;const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;return Gate.allows(ability,user,...args)},async cannot(ability,...args){return!await this.can(ability,...args)},async authorize(ability,...args){const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;await Gate.authorize(ability,user,...args)}};async function seedCsrfTokenForRender(req){const method=req.method?.toUpperCase?.()??"GET";if(method!=="GET"&&method!=="HEAD")return;const cookieHeader=req.headers?.get?.("cookie")??"";if(cookieHeader.includes("X-CSRF-Token=")||cookieHeader.includes("csrf-token="))return;try{const{generateCsrfToken,CSRF_COOKIE_NAME}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts")),token=generateCsrfToken();req._csrfToken=token;try{const merged=cookieHeader?`${cookieHeader}; ${CSRF_COOKIE_NAME}=${token}`:`${CSRF_COOKIE_NAME}=${token}`;req.headers.set("cookie",merged)}catch{}}catch{}}export function enhanceRequest(req){const routeParams=Object.fromEntries(Object.entries(req.params||{}).map(([key,value])=>{try{return[key,decodeURIComponent(value)]}catch{return[key,value]}}));req.params=routeParams;applyRequestEnhancements(req,routeParams);if(!req._requestId)req._requestId=incomingRequestId(req)??crypto.randomUUID();let query=req.query;if(!query){const url=new URL(req.url);query={};url.searchParams.forEach((value,key)=>{query[key]=value});req.query=query}Object.assign(req,REQUEST_METHODS);return req}function incomingRequestId(req){try{const supplied=req.headers?.get?.("x-request-id")?.trim();if(supplied&&/^[\w.:-]{8,200}$/.test(supplied))return supplied}catch{}return}function wrapHandler(handler,skipParsing=!1){if(typeof handler==="string"){const handlerPath=handler;return async(req)=>{try{if(!skipParsing){await parseRequestBody(req);req=enhanceRequest(req)}return await(await resolveStringHandler(handlerPath))(req)}catch(error){report(error,{label:`[Router] ${handlerPath}`});const rawStatus=error?.statusCode??error?.status,status=typeof rawStatus==="number"&&Number.isInteger(rawStatus)&&rawStatus>=400&&rawStatus<600?rawStatus:void 0;return await createErrorResponse(error instanceof Error?error:Error(String(error)),req,{handlerPath,status})}}}const fn=handler;return async(req)=>{const result=await fn(req);return formatResult(result,req)}}async function parseRequestBody(req){if(req._bodyParsed)return;req._bodyParsed=!0;const contentType=req.headers.get("content-type")||"";try{if(JSON_CONTENT_TYPE.test(contentType)){const raw=await req.clone().text();req._rawBody=raw;if(raw.length===0)req.jsonBody={};else try{const body=JSON.parse(raw);req.jsonBody=body&&typeof body==="object"?body:{}}catch(parseErr){const message=parseErr instanceof Error?parseErr.message:"Invalid JSON",{HttpError}=await import("@stacksjs/error-handling");throw new HttpError(400,`Invalid JSON body: ${message}`)}}else if(contentType.includes("application/x-www-form-urlencoded")){const text=await req.clone().text(),params=new URLSearchParams(text),formBody={};params.forEach((value,key)=>{formBody[key]=value});req.formBody=formBody}else if(contentType.includes("multipart/form-data")){const formData=await req.clone().formData(),formBody={},files={};formData.forEach((value,key)=>{if(value instanceof File)if(files[key])if(Array.isArray(files[key]))files[key].push(value);else files[key]=[files[key],value];else files[key]=value;else formBody[key]=value});Reflect.set(req,"formBody",formBody);Reflect.set(req,"files",files)}}catch(e){if(typeof(e?.status??e?.statusCode)==="number")throw e;log.debug("[stacks-router] Body parsing failed:",e)}}export function createStacksRouter(config={}){const bunRouter=new Router({verbose:config.verbose??!1});let currentPrefix="",currentGroupMiddleware=[],currentGroupApiResponse=!1;const registeredRouteKeys=new Set;function registerRoute(method,path,_handler){const fullPath=currentPrefix+path,routeKey=`${method}:${fullPath}`;log.debug(`[router] ${method} ${fullPath} \u2192 ${typeof _handler==="string"?_handler:"function"}`);const shadowed=registeredRouteKeys.has(routeKey);if(!shadowed)registeredRouteKeys.add(routeKey);if(!shadowed&&currentGroupMiddleware.length>0)routeMiddlewareRegistry.set(routeKey,[...currentGroupMiddleware]);if(!shadowed&&currentGroupApiResponse)routeApiResponseRegistry.add(routeKey);if(!shadowed&&typeof _handler==="string")routeHandlerKeyRegistry.set(routeKey,_handler);return{fullPath,routeKey,shadowed}}const stacksRouter={bunRouter,get routes(){return bunRouter.routes},get(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("GET",path,handler);bunRouter.get(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},post(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("POST",path,handler);bunRouter.post(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},put(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("PUT",path,handler);bunRouter.put(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},patch(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("PATCH",path,handler);bunRouter.patch(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},delete(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("DELETE",path,handler);bunRouter.delete(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},options(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("OPTIONS",path,handler);bunRouter.options(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},group(options,callback){const previousPrefix=currentPrefix,previousMiddleware=[...currentGroupMiddleware],previousApiResponse=currentGroupApiResponse;if(options.prefix)currentPrefix=previousPrefix+options.prefix;const middlewareList=options.middleware?Array.isArray(options.middleware)?options.middleware:[options.middleware]:void 0;if(middlewareList)currentGroupMiddleware=[...currentGroupMiddleware,...middlewareList];if(options.apiResponse===!0)currentGroupApiResponse=!0;log.debug(`[router] Entering group: prefix=${options.prefix||"/"} middleware=[${middlewareList?.join(", ")||""}]${currentGroupApiResponse?" apiResponse=true":""}`);const result=callback();if(result instanceof Promise)return result.then(()=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter}).catch((err)=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;throw err});currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter},resource(name,handler,options){const actions=["index","store","show","update","destroy"],activeActions=options?.only?actions.filter((a)=>options.only.includes(a)):options?.except?actions.filter((a)=>!options.except.includes(a)):actions,handlerBase=handler.replace(/Action$/,"");log.debug(`[router] Resource: /${name} \u2192 ${handler} [${activeActions.join(", ")}]`);const registerResourceRoutes=()=>{for(const action of activeActions)switch(action){case"index":stacksRouter.get(`/${name}`,`${handlerBase}IndexAction`);break;case"store":stacksRouter.post(`/${name}`,`${handlerBase}StoreAction`);break;case"show":stacksRouter.get(`/${name}/:id`,`${handlerBase}ShowAction`);break;case"update":stacksRouter.put(`/${name}/:id`,`${handlerBase}UpdateAction`);break;case"destroy":stacksRouter.delete(`/${name}/:id`,`${handlerBase}DestroyAction`);break}};if(options?.middleware)stacksRouter.group({middleware:options.middleware},registerResourceRoutes);else registerResourceRoutes();return stacksRouter},match(methods,path,handler){log.debug(`[router] Match: [${methods.join(", ")}] ${path} \u2192 ${typeof handler==="string"?handler:"function"}`);let firstShadowed=!1;for(const[index,method]of methods.entries()){const m=method.toUpperCase(),{fullPath,routeKey,shadowed}=registerRoute(m,path,handler);if(index===0)firstShadowed=shadowed;const wrappedHandler=createMiddlewareHandler(routeKey,handler);switch(m){case"GET":bunRouter.get(fullPath,wrappedHandler);break;case"POST":bunRouter.post(fullPath,wrappedHandler);break;case"PUT":bunRouter.put(fullPath,wrappedHandler);break;case"PATCH":bunRouter.patch(fullPath,wrappedHandler);break;case"DELETE":bunRouter.delete(fullPath,wrappedHandler);break;case"OPTIONS":bunRouter.options(fullPath,wrappedHandler);break}}return createChainableRoute(`${methods[0]}:${currentPrefix}${path}`,firstShadowed)},health(){bunRouter.get("/api/health",async()=>{const health=await checkApplicationHealth();return Response.json(health,{status:health.status==="healthy"?200:503})});bunRouter.get("/__routes",(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});return Response.json(listRegisteredRoutes())});bunRouter.get("/__storage/:path",async(req)=>{const url=new URL(req.url),token=url.searchParams.get("token"),params=req.params,rawPath=params?.path?decodeURIComponent(params.path):decodeURIComponent(url.pathname.replace(/^\/__storage\//,""));if(!token||typeof rawPath!=="string"||rawPath.length===0)return new Response("Forbidden",{status:403});const{verifySignedStorageToken,Storage}=await import("@stacksjs/storage");if(!verifySignedStorageToken(token,rawPath).valid)return new Response("Forbidden",{status:403});try{const adapter=Storage.disk();if(!await adapter.fileExists(rawPath))return new Response("Not Found",{status:404});const buf=await adapter.readToBuffer(rawPath),mime=await adapter.mimeType(rawPath).catch(()=>"application/octet-stream");return new Response(buf,{status:200,headers:{"Content-Type":mime,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(err){log.error("[storage] signed-url fetch failed:",err);return new Response("Internal Error",{status:500})}});bunRouter.get("/__openapi.json",async(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});try{const{generateOpenApi}=await import("@stacksjs/api"),spec=await generateOpenApi({write:!1,portable:!1});return Response.json(spec)}catch(err){return Response.json({error:"OpenAPI generation failed",message:err instanceof Error?err.message:String(err)},{status:500})}});return stacksRouter},use(middleware){const adapted=adaptMiddlewareForBunRouter(middleware);bunRouter.globalMiddleware.push(adapted);return stacksRouter},booting(name,run){bootHooks.push({name,run});return stacksRouter},async serve(options={}){warnOnMultipleRouterInstances();configureViewDirectories(bunRouter);wrapHandleRequestForCsrf(bunRouter);await runBootHooks();return bunRouter.serve(options)},async handleRequest(req){return bunRouter.handleRequest(req)},getAllowedMethods(pathname,domain){return bunRouter.getAllowedMethods(pathname,domain)},async register(routePath,options){log.debug(`[router] Register: ${routePath} prefix=${options?.prefix||"none"}`);const callback=async()=>{await import(routePath)};if(options?.prefix||options?.middleware)await stacksRouter.group({prefix:options.prefix,middleware:options.middleware},callback);else await callback();return stacksRouter},async importRoutes(){log.debug("[router] Loading user routes from registry...");try{const{loadRoutes}=await import("./route-loader"),{appPath}=await import("@stacksjs/path"),routeRegistry=(await import(appPath("Routes.ts"))).default;await loadRoutes(routeRegistry)}catch(error){log.error("Failed to load route registry:",error);throw error}log.debug("[router] Loading ORM routes...");const ormRoutesCandidates=[p.frameworkPath("orm/routes.ts"),p.frameworkPath("core/orm/routes.ts")];let ormRoutesLoaded=!1;for(const candidate of ormRoutesCandidates)try{if(await Bun.file(candidate).exists()){await import(candidate);ormRoutesLoaded=!0;break}}catch(error){log.warn(`[router] ORM routes candidate failed to load, falling back to next: ${candidate}
4
+ ${paths}`)}return!0}let __defaultsPkgRoot;const __defaultsPathCache=new Map;function resolveDefaultsPath(rel){const cached=__defaultsPathCache.get(rel);if(cached!==void 0)return cached;const vendored=p.storagePath(`framework/defaults/${rel}`);let resolved;if(existsSync(vendored))resolved=vendored;else{if(__defaultsPkgRoot===void 0)try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());__defaultsPkgRoot=pkgJson.slice(0,pkgJson.lastIndexOf("/"))}catch{__defaultsPkgRoot=null}resolved=__defaultsPkgRoot?`${__defaultsPkgRoot}/${rel}`:vendored}__defaultsPathCache.set(rel,resolved);return resolved}import{runWithRequest}from"./request-context";import{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";import{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse}from"./error-handler";import{rateLimit as enforceRateLimit}from"./rate-limit";import{applySecurityHeaders}from"./security-headers";import{isCursorPaginator,isPaginator,isSimplePaginator}from"@stacksjs/orm";const csrfSkipRegistry=new Set,csrfRequireRegistry=new Set,routeRateLimitRegistry=new Map;function rateLimitWindowToSeconds(window){if(typeof window==="number"){if(!Number.isFinite(window)||window<=0)throw Error(`[Router] .rateLimit(): window must be a positive number of seconds, got ${window}`);return Math.floor(window)}switch(window){case"second":return 1;case"minute":return 60;case"hour":return 3600;case"day":return 86400;default:throw Error(`[Router] .rateLimit(): unknown period '${String(window)}'`)}}class BoundedMap{max;map=new Map;constructor(max){this.max=max}get(key){return this.map.get(key)}has(key){return this.map.has(key)}set(key,value){if(this.map.has(key))this.map.delete(key);this.map.set(key,value);if(this.map.size>this.max){const oldest=this.map.keys().next().value;if(oldest!==void 0)this.map.delete(oldest)}return this}delete(key){return this.map.delete(key)}clear(){this.map.clear()}get size(){return this.map.size}}function isExposeRoutesAuthorized(req){const flag=process.env.STACKS_EXPOSE_ROUTES??"";if(!flag)return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");if(flag==="1")return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");const url=new URL(req.url),submitted=req.headers.get("x-stacks-routes-token")||req.headers.get("X-Stacks-Routes-Token")||url.searchParams.get("token")||"";if(typeof submitted!=="string"||submitted.length===0||submitted.length!==flag.length)return!1;try{return timingSafeEqual(Buffer.from(submitted),Buffer.from(flag))}catch{return!1}}async function applyCorsIfConfigured(req,response){if(!req._corsConfig||!response)return response;try{const{applyCorsHeaders}=await import(resolveDefaultsPath("app/Middleware/Cors.ts"));return applyCorsHeaders(req,response,req._corsConfig)}catch(err){log.warn("[router] CORS header injection failed",{error:err});return response}}const ACTION_CACHE_MAX=5000,actionSkipsCsrfCache=new BoundedMap(ACTION_CACHE_MAX),routeHandlerKeyRegistry=new BoundedMap(ACTION_CACHE_MAX),routeActionRegistry=new Map,CSRF_PROTECTED_METHODS=new Set(["POST","PUT","PATCH","DELETE"]),namedRouteRegistry=new Map;function compileNamedRoute(path){const paramNames=extractRouteParamNames(path),colonRegex=new Map;for(const name of paramNames)colonRegex.set(name,new RegExp(`(^|/):${name}(?=$|/)`,"g"));return{path,paramNames,colonRegex}}function extractRouteParamNames(routePath){const names=new Set;for(const m of routePath.matchAll(/\{(\w+)\}/g))if(m[1])names.add(m[1]);for(const m of routePath.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(m[1])names.add(m[1]);return[...names]}export function url(routeName,params={}){const named=namedRouteRegistry.get(routeName);if(!named)throw Error(`Route '${routeName}' is not defined. Available routes: ${[...namedRouteRegistry.keys()].join(", ")}`);const missing=named.paramNames.filter((name)=>!(name in params)||params[name]===void 0);if(missing.length>0)throw Error(`url('${routeName}'): missing required path param${missing.length>1?"s":""} [${missing.join(", ")}] for path '${named.path}'. Pass them as the second argument: url('${routeName}', { ${named.paramNames.join(", ")} })`);let appUrl;try{appUrl=process.env.APP_URL||"https://localhost"}catch{appUrl="https://localhost"}appUrl=appUrl.replace(/\/$/,"");if(!appUrl.startsWith("http"))appUrl=`https://${appUrl}`;let resolvedPath=named.path;const queryParams={};for(const[key,value]of Object.entries(params)){const curly=`{${key}}`;if(resolvedPath.includes(curly))resolvedPath=resolvedPath.replaceAll(curly,encodeURIComponent(String(value)));else{const re=named.colonRegex.get(key);if(re&&re.test(resolvedPath)){re.lastIndex=0;resolvedPath=resolvedPath.replace(re,`$1${encodeURIComponent(String(value))}`)}else queryParams[key]=String(value)}}const queryString=Object.keys(queryParams).length>0?`?${new URLSearchParams(queryParams).toString()}`:"";return`${appUrl}${resolvedPath}${queryString}`}export function routeParams(routeName){const named=namedRouteRegistry.get(routeName);return named?[...named.paramNames]:[]}export function listNamedRoutes(){const out={};for(const[name,named]of namedRouteRegistry.entries())out[name]=named.path;return out}export function listRegisteredRoutes(){const out=[],seen=new Set;for(const key of routeMiddlewareRegistry.keys()){if(seen.has(key))continue;seen.add(key);const idx=key.indexOf(":");if(idx===-1)continue;const method=key.slice(0,idx),path=key.slice(idx+1);let routeName;for(const[n,named]of namedRouteRegistry.entries())if(named.path===path){routeName=n;break}out.push({method,path,name:routeName,handler:routeHandlerKeyRegistry.get(key),action:routeActionRegistry.get(key)})}return out.sort((a,b)=>a.path.localeCompare(b.path))}const MIDDLEWARE_TIMEOUT_MS=30000;let _debugLoggingCache;function isDebugLogging(){if(_debugLoggingCache===void 0){const level=(process.env.LOG_LEVEL||"info").toLowerCase();_debugLoggingCache=level!=="info"&&level!=="warn"&&level!=="error"}return _debugLoggingCache}const DEFAULT_MIDDLEWARE_PRIORITY=10,_warnedInvalidPriorities=new Set;function warnInvalidMiddlewarePriority(name,raw){const key=`${name}:${String(raw)}`;if(_warnedInvalidPriorities.has(key))return;_warnedInvalidPriorities.add(key);log.warn(`[Router] Middleware '${name}' declared an invalid priority (${String(raw)}). Priorities must be a finite non-negative number; falling back to default ${DEFAULT_MIDDLEWARE_PRIORITY}.`)}function adaptMiddlewareForBunRouter(middleware){if(middleware instanceof Middleware)return middleware.toRouterHandler();if(middleware&&typeof middleware==="object"&&typeof middleware.handle==="function"&&typeof middleware!=="function"){const handle=middleware.handle.bind(middleware);return async(req,next)=>{try{await handle(req)}catch(thrown){if(thrown instanceof Response)return thrown;throw thrown}return next()}}return middleware}const middlewareCache=new Map;let middlewareAliasesPromise=null;async function getMiddlewareAliases(){if(middlewareAliasesPromise)return middlewareAliasesPromise;middlewareAliasesPromise=(async()=>{try{return(await import(p.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(resolveDefaultsPath("app/Middleware.ts"))).default||{}}catch{return{}}}})();return middlewareAliasesPromise}const PASCAL_SPLIT_REGEX=/[-_\s]+/,pascalCaseCache=new Map;function toPascalCase(input){if(!input)return input;const cached=pascalCaseCache.get(input);if(cached!==void 0)return cached;const out=input.split(PASCAL_SPLIT_REGEX).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join("");pascalCaseCache.set(input,out);return out}async function resolveMiddlewareName(name){const resolved=(await getMiddlewareAliases())[name]||toPascalCase(name);log.debug(`[middleware] Resolved: ${name} \u2192 ${resolved}`);return resolved}async function loadMiddleware(name){if(middlewareCache.has(name))return middlewareCache.get(name)??null;const className=await resolveMiddlewareName(name);let userPathError;try{const userPath=p.appPath(`Middleware/${className}.ts`),handler=(await import(userPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${userPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){userPathError=err}try{const defaultPath=resolveDefaultsPath(`app/Middleware/${className}.ts`),handler=(await import(defaultPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${defaultPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){const userMsg=userPathError instanceof Error?userPathError.message:String(userPathError);log.error(`[Router] Failed to load middleware '${name}' (resolved to '${className}'). app/Middleware: ${userMsg}; defaults:`,err);return null}}export function clearMiddlewareCache(){middlewareCache.clear();middlewareAliasesPromise=null;actionSkipsCsrfCache.clear();routeHandlerKeyRegistry.clear();routeActionRegistry.clear();clearCsrfModuleCache()}export function installMiddlewareHotReload(){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")return()=>{};let fsWatchers=[];(async()=>{try{const fs=await import("node:fs"),targets=[p.appPath("Middleware"),p.appPath("Middleware.ts")];for(const target of targets)try{if(!fs.existsSync(target))continue;const w=fs.watch(target,{recursive:!0},()=>{log.debug("[middleware] hot-reload: clearing cache");clearMiddlewareCache()});fsWatchers.push(w)}catch{}}catch{}})();return()=>{for(const w of fsWatchers)try{w.close()}catch{}fsWatchers=[]}}const routeMiddlewareRegistry=new Map;export function clearRouteMiddlewareRegistry(){routeMiddlewareRegistry.clear()}const routeApiResponseRegistry=new Set;function parseMiddlewareName(middleware){const colonIndex=middleware.indexOf(":");if(colonIndex===-1)return{name:middleware};return{name:middleware.substring(0,colonIndex),params:middleware.substring(colonIndex+1)}}export async function findUnresolvableRouteMiddleware(){const usage=new Map;for(const[routeKey,entries]of routeMiddlewareRegistry)for(const entry of entries){const{name}=parseMiddlewareName(entry),routes=usage.get(name)??[];routes.push(routeKey);usage.set(name,routes)}if(!usage.has("csrf"))usage.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);const unresolvable=[];for(const[alias,routes]of usage){const handler=await loadMiddleware(alias);if(!handler||typeof handler.handle!=="function")unresolvable.push({alias,routes})}return unresolvable}export async function assertRouteMiddlewareResolvable(){const unresolvable=await findUnresolvableRouteMiddleware();if(unresolvable.length===0)return;const detail=unresolvable.map((u)=>`"${u.alias}" (used by ${u.routes.join(", ")})`).join("; ");throw Error(`[Router] Unresolvable middleware alias(es): ${detail}. Check the alias map in app/Middleware.ts or add app/Middleware/<Class>.ts.`)}function createMiddlewareHandler(routeKey,handler){const wrappedBase=wrapHandler(handler,!0,routeKey),routeMethod=routeKey.slice(0,routeKey.indexOf(":")).toUpperCase(),routeAcceptsCsrf=CSRF_PROTECTED_METHODS.has(routeMethod),forcesJsonByGroup=routeApiResponseRegistry.has(routeKey),handlerKey=typeof handler==="string"?handler:isRouterAction(handler)?routeKey:void 0;let actionPrefetch=null;if(typeof handler==="string"&&routeAcceptsCsrf)actionPrefetch=resolveStringHandler(handler).then(()=>{return}).catch(()=>{return});return async(req)=>{try{await parseRequestBody(req)}catch(err){const error=err instanceof Error?err:Error(String(err));return createMiddlewareErrorResponse(error,req)}const enhancedReq=enhanceRequest(req),renderTokenSeeding=seedCsrfTokenForRender(enhancedReq);if(renderTokenSeeding)await renderTokenSeeding;if(actionPrefetch)await actionPrefetch;if(forcesJsonByGroup)req._forceJson=!0;return runWithRequest(enhancedReq,async()=>{const rl=routeRateLimitRegistry.get(routeKey);if(rl)try{await enforceRateLimit(routeKey,rl.max).over(rl.windowSeconds)}catch(err){return createMiddlewareErrorResponse(err,req)}const userMiddleware=routeMiddlewareRegistry.get(routeKey)||[];let shouldInjectCsrf=!1;if(routeAcceptsCsrf){const alreadyHasCsrf=userMiddleware.some((m)=>m==="csrf"||m.startsWith("csrf:")),routeSkipped=csrfSkipRegistry.has(routeKey),routeRequired=csrfRequireRegistry.has(routeKey),actionSkipped=handlerKey?actionSkipsCsrfCache.get(handlerKey)===!0:!1;shouldInjectCsrf=!alreadyHasCsrf&&(routeRequired||!routeSkipped&&!actionSkipped)}const middlewareEntries=shouldInjectCsrf?["csrf",...userMiddleware]:userMiddleware;if(middlewareEntries.length>0&&isDebugLogging()){const schemeEnd=req.url.indexOf("://"),pathStart=schemeEnd===-1?0:req.url.indexOf("/",schemeEnd+3),q=req.url.indexOf("?",pathStart<0?0:pathStart),urlPath=pathStart<0?"/":req.url.slice(pathStart,q===-1?void 0:q);log.debug(`[middleware] Executing chain: [${middlewareEntries.join(", ")}] for ${routeMethod} ${urlPath}`)}const resolved=[];for(const middlewareEntry of middlewareEntries){const{name:middlewareName,params}=parseMiddlewareName(middlewareEntry);if(params){enhancedReq._middlewareParams=enhancedReq._middlewareParams||{};enhancedReq._middlewareParams[middlewareName]=params}const middleware=await loadMiddleware(middlewareName);if(!middleware||typeof middleware.handle!=="function"){log.error(`[Router] Middleware '${middlewareName}' on ${routeKey} could not be resolved - failing closed`);const failClosedError=Error(`Middleware '${middlewareName}' could not be resolved`),failClosedResponse=await createErrorResponse(failClosedError,enhancedReq,{status:500});return await applyCorsIfConfigured(enhancedReq,failClosedResponse)}const rawPriority=middleware.priority;let priority=DEFAULT_MIDDLEWARE_PRIORITY;if(typeof rawPriority==="number"&&Number.isFinite(rawPriority)&&rawPriority>=0)priority=rawPriority;else if(rawPriority!==void 0)warnInvalidMiddlewarePriority(middlewareName,rawPriority);resolved.push({name:middlewareName,handler:middleware,priority})}resolved.sort((a,b)=>a.priority-b.priority);const middlewareTimings=[];let chainTimer,chainBudget,runningMiddleware="";const armChainBudget=()=>{if(!chainBudget){chainBudget=new Promise((_,reject)=>{chainTimer=setTimeout(()=>reject(Error(`Middleware '${runningMiddleware}' exceeded ${MIDDLEWARE_TIMEOUT_MS}ms`)),MIDDLEWARE_TIMEOUT_MS)});chainBudget.catch(()=>{})}return chainBudget};try{for(const{name:middlewareName,handler:middleware}of resolved){const mwStart=process.hrtime.bigint();runningMiddleware=middlewareName;try{const outcome=middleware.handle(enhancedReq);if(outcome&&typeof outcome.then==="function")await Promise.race([outcome,armChainBudget()]);const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs})}catch(error){const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs});log.debug(`[middleware] Blocked by: ${middlewareName}`);if(error instanceof Response){try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)error.headers.set("Server-Timing",parts.join(", "));if(reqId)error.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,error)}const err=error instanceof Error?error:Error(String(error)),errorResponse="statusCode"in err||"status"in err?await createMiddlewareErrorResponse(err,enhancedReq):await(()=>{log.error(`[Router] Middleware '${middlewareName}' threw an unexpected error:`,err);return createErrorResponse(err,enhancedReq,{status:500})})();try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)errorResponse.headers.set("Server-Timing",parts.join(", "));if(reqId)errorResponse.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,errorResponse)}}}finally{clearTimeout(chainTimer)}let response=await wrappedBase(enhancedReq);clearTrackedQueries();if(response){if(req.method==="GET"||req.method==="HEAD"||req.method==="OPTIONS")try{const mod=loadCsrfModule(),csrf=mod instanceof Promise?await mod:mod;if(csrf)response=csrf.seedCsrfCookieIfMissing(enhancedReq,response,enhancedReq._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed",{error:err})}}if(response)response=await applyCorsIfConfigured(enhancedReq,response);const{_requestId:reqId,_startNs:startNs}=enhancedReq,durMs=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,setHeaders=(h)=>{const after=enhancedReq._afterResponse;if(Array.isArray(after))for(const callback of after)try{if(typeof callback==="function")callback({status:response?.status??0,durationMs:durMs??0})}catch{}const requested=enhancedReq._responseHeaders;if(requested&&typeof requested==="object"){for(const[name,value]of Object.entries(requested))if(typeof value==="string")h.set(name,value)}if(reqId)h.set("X-Request-ID",reqId);if(durMs!=null){const parts=[`total;dur=${durMs.toFixed(1)}`];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}h.set("Server-Timing",parts.join(", "))}applySecurityHeaders(h)};if(response&&typeof response.headers?.set==="function"){if(response.status>=400&&(response.headers.get("content-type")||"").includes("json")&&reqId)try{const text=await response.clone().text(),parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"){const newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(JSON.stringify({...parsed,request_id:reqId}),{status:response.status,statusText:response.statusText,headers:newHeaders})}}catch{}try{setHeaders(response.headers)}catch{try{const cloned=response.clone(),newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(cloned.body,{status:response.status,statusText:response.statusText,headers:newHeaders})}catch{}}}if(enhancedReq._compress===!0&&response)try{const{applyCompression}=await import(resolveDefaultsPath("app/Middleware/Compress.ts"));return await applyCompression(enhancedReq,response)}catch(err){log.warn(`[router] Compression failed; sending uncompressed response: ${err instanceof Error?err.message:String(err)}`)}return response})}}function createInertRoute(){const inert={middleware:()=>inert,name:()=>inert,skipCsrf:()=>inert,requireCsrf:()=>inert,rateLimit:()=>inert};return inert}function createChainableRoute(routeKey,shadowed=!1){if(shadowed)return createInertRoute();if(!routeMiddlewareRegistry.has(routeKey))routeMiddlewareRegistry.set(routeKey,[]);const routePath=routeKey.includes(":")?routeKey.substring(routeKey.indexOf(":")+1):routeKey,chain={middleware(name){const middlewareList=routeMiddlewareRegistry.get(routeKey);if(!middlewareList)return chain;for(const entry of Array.isArray(name)?name:[name]){if(typeof entry!=="string")throw TypeError(`[Router] middleware() on ${routeKey} was given a ${typeof entry}; it takes an alias or an array of aliases`);middlewareList.push(entry)}return chain},name(routeName){namedRouteRegistry.set(routeName,compileNamedRoute(routePath));return chain},skipCsrf(){csrfSkipRegistry.add(routeKey);csrfRequireRegistry.delete(routeKey);return chain},requireCsrf(){csrfRequireRegistry.add(routeKey);csrfSkipRegistry.delete(routeKey);return chain},rateLimit(max,window){if(!Number.isFinite(max)||max<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(max)}`);const windowSeconds=rateLimitWindowToSeconds(window);routeRateLimitRegistry.set(routeKey,{max:Math.floor(max),windowSeconds});return chain}};return chain}async function fileExists(path){try{return await Bun.file(path).exists()}catch{return!1}}function assertSafeHandlerPath(handlerPath){if(typeof handlerPath!=="string"||handlerPath.length===0)throw Error(`[Router] Refusing to resolve handler '${String(handlerPath)}': empty or non-string`);if(handlerPath.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if(handlerPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(handlerPath))throw Error(`[Router] Refusing to resolve absolute handler path '${handlerPath}'`);if(handlerPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[Router] Refusing to resolve handler path '${handlerPath}' (contains '..' segment)`)}const _moduleImportCache=new Map;function cachedImport(fullPath){let p=_moduleImportCache.get(fullPath);if(!p){p=import(fullPath);_moduleImportCache.set(fullPath,p)}return p}const _resolvedHandlerCache=new Map;function resolveStringHandler(handlerPath){let resolved=_resolvedHandlerCache.get(handlerPath);if(!resolved){resolved=resolveStringHandlerUncached(handlerPath);_resolvedHandlerCache.set(handlerPath,resolved);resolved.catch(()=>_resolvedHandlerCache.delete(handlerPath))}return resolved}function validationFailureResponse(errors){return response.validationError(errors)}export function precognitionRequest(req){const header=req.headers?.get?.("Precognition"),viaHeader=typeof header==="string"&&header.toLowerCase()==="true";let viaQuery=!1;try{viaQuery=new URL(req.url).searchParams.get("_validate")==="1"}catch{viaQuery=!1}if(!viaHeader&&!viaQuery)return null;return{only:(req.headers?.get?.("Precognition-Validate-Only")??"").split(",").map((field)=>field.trim()).filter(Boolean)}}export function precognitionSuccess(){return new Response(null,{status:204,headers:{Precognition:"true","Precognition-Success":"true",Vary:"Precognition, Precognition-Validate-Only"}})}async function resolveStringHandlerUncached(handlerPath){assertSafeHandlerPath(handlerPath);let modulePath=handlerPath;modulePath=modulePath.endsWith(".ts")?modulePath.slice(0,-3):modulePath;if(modulePath.includes("Controller")){const[controllerPath,methodName="index"]=modulePath.split("@"),userPath=p.appPath(`${controllerPath}.ts`),defaultPath=resolveDefaultsPath(`app/${controllerPath}.ts`),fullPath=await fileExists(userPath)?userPath:defaultPath;try{const controller=await cachedImport(fullPath);if(!controller.default||typeof controller.default!=="function")throw Error(`Controller ${controllerPath} does not export a default class`);const instance=new controller.default;if(typeof instance[methodName]!=="function")throw Error(`Method ${methodName} not found in controller ${controllerPath}`);return async(req)=>{const result=await instance[methodName](req);return formatResult(result,req)}}catch(error){log.error(`[Router] Failed to load controller '${fullPath}':`,error);throw error}}let fullPath;if(modulePath.includes("storage/framework/orm"))fullPath=modulePath;else if(modulePath.includes("OrmAction"))fullPath=p.storagePath(`framework/actions/src/${modulePath}.ts`);else if(modulePath.includes("Actions")){const userPath=p.projectPath(`app/${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}else{const userPath=p.appPath(`${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}try{const action=(await cachedImport(fullPath)).default;if(!action)throw Error(`Action '${handlerPath}' has no default export`);if(typeof action.handle!=="function"){log.error(`[Router] Action '${handlerPath}' structure:`,Object.keys(action));throw Error(`Action '${handlerPath}' has no handle() method. Got: ${typeof action.handle}`)}return wrapAction(action,handlerPath)}catch(importError){log.error(`[Router] Failed to import action '${fullPath}':`,importError);throw importError}}export function isRouterAction(handler){return typeof handler==="object"&&handler!==null&&typeof handler.handle==="function"}export function wrapAction(action,handlerKey){const actionSkipsCsrf=action.skipCsrf===!0||action.csrf===!1;actionSkipsCsrfCache.set(handlerKey,actionSkipsCsrf);const actionForcesJson=action.apiResponse===!0,requestValidationRules=action.validations??modelValidationRules(action.modelDefinition??action.model);return async(req)=>{if(actionSkipsCsrf)req._skipCsrf=!0;if(actionForcesJson)req._forceJson=!0;req._requestValidationRules=requestValidationRules;try{const precognition=precognitionRequest(req);if(precognition){if(!action.validations)return precognitionSuccess();const rules=precognition.only.length>0?Object.fromEntries(Object.entries(action.validations).filter(([field])=>precognition.only.includes(field))):action.validations,precognitionResult=await validateActionInput(req,rules);return precognitionResult.valid?precognitionSuccess():validationFailureResponse(precognitionResult.errors)}if(action.validations){const validationResult=await validateActionInput(req,action.validations);if(!validationResult.valid)return validationFailureResponse(validationResult.errors)}if(typeof action.authorize==="function"){const auth=await action.authorize(req);if(auth instanceof Response)return auth;if(auth===!1)return Response.json({error:"Forbidden"},{status:403})}if(typeof action.before==="function"){const pre=await action.before(req);if(pre instanceof Response)return pre}const result=await action.handle(req);return formatResult(result,req)}catch(handleError){report(handleError,{label:`[Router] action.handle() for '${handlerKey}'`});throw handleError}}}export async function validateActionInput(req,validations){const errors={},input=await getRequestInput(req,validations);for(const[field,validation]of Object.entries(validations)){const value=input[field];let result;try{result=validation.rule.validate(value)}catch{result={valid:!1,errors:[{message:`${field} validation failed`}]}}if(!result.valid){const fieldErrors=[],label=field.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(c)=>c.toUpperCase()),decorate=(msg)=>msg.toLowerCase().startsWith(field.toLowerCase())||msg.includes(label)?msg:`${label} ${msg}`;if(result.errors&&result.errors.length>0)if(validation.message){const firstMessage=result.errors[0]?.message??"";fieldErrors.push(typeof validation.message==="string"?validation.message:validation.message[field]||decorate(firstMessage))}else result.errors.forEach((err)=>fieldErrors.push(decorate(err.message)));else fieldErrors.push(validation.message?typeof validation.message==="string"?validation.message:`${label} is invalid`:`${label} is invalid`);errors[field]=fieldErrors}}const valid=Object.keys(errors).length===0;if(valid){const validated={};for(const field of Object.keys(validations))if(input[field]!==void 0)validated[field]=input[field];req._validatedInput=validated}return{valid,errors}}function modelValidationRules(model){if(!model?.attributes||typeof model.attributes!=="object")return;const rules={};for(const[field,attribute]of Object.entries(model.attributes)){const validation=attribute?.validation;if(validation?.rule)rules[field]=validation}return Object.keys(rules).length>0?rules:void 0}async function getRequestInput(req,validations){const input={},q=req.query;if(q)for(const key in q)input[key]=q[key];else new URL(req.url).searchParams.forEach((value,key)=>{input[key]=value});if(req.params)Object.assign(input,req.params);if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);else if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(typeof req.allFiles==="function")try{const files=req.allFiles();for(const key of Object.keys(files??{}))if(!(key in input))input[key]=files[key]}catch{}if(!validations)return input;for(const[field,validation]of Object.entries(validations)){const value=input[field];if(typeof value!=="string")continue;const validatorName=validation.rule?.name;if(validatorName==="number"){const n=Number(value);if(Number.isFinite(n))input[field]=n}else if(validatorName==="boolean"){if(value==="true"||value==="1")input[field]=!0;else if(value==="false"||value==="0")input[field]=!1}}return input}function formatResult(result,req){if(result instanceof Response)return result;if(result instanceof ReadableStream)return new Response(result,{headers:{"Content-Type":"application/octet-stream"}});const apiShaped=req._forceJson===!0||isApiRequest(req);if(result===null||result===void 0)return apiShaped?new Response(null,{status:204}):new Response("",{status:200});if(typeof result==="object"){const linkHeader=buildPaginatorLinkHeader(result);if(linkHeader)return Response.json(result,{headers:{Link:linkHeader}});return Response.json(result)}if(apiShaped)return Response.json(result);return new Response(String(result),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function buildPaginatorLinkHeader(value){if(!isPaginator(value)&&!isSimplePaginator(value)&&!isCursorPaginator(value))return null;const v=value,parts=[];if(v.prev_page_url)parts.push(`<${v.prev_page_url}>; rel="prev"`);if(v.next_page_url)parts.push(`<${v.next_page_url}>; rel="next"`);if(v.first_page_url)parts.push(`<${v.first_page_url}>; rel="first"`);if(v.last_page_url)parts.push(`<${v.last_page_url}>; rel="last"`);return parts.length>0?parts.join(", "):null}export function stream(source,options={}){const baseHeaders={};if(options.type==="sse"){baseHeaders["Content-Type"]="text/event-stream; charset=utf-8";baseHeaders["Cache-Control"]="no-cache";baseHeaders.Connection="keep-alive"}else if(options.type==="ndjson")baseHeaders["Content-Type"]="application/x-ndjson; charset=utf-8";else baseHeaders["Content-Type"]=options.contentType??"application/octet-stream";const body=source instanceof ReadableStream?source:new ReadableStream({async start(controller){try{for await(const chunk of source)controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):chunk);controller.close()}catch(err){controller.error(err)}}}),merged=new Headers(baseHeaders);if(options.headers)new Headers(options.headers).forEach((value,key)=>merged.set(key,value));return new Response(body,{status:options.status??200,headers:merged})}function getAllInputFor(req){const cached=req._allInputCache;if(cached)return cached;const input={},query=req.query;if(query)for(const key in query)input[key]=query[key];if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(req.params&&typeof req.params==="object")Object.assign(input,req.params);req._allInputCache=input;return input}function flashInputFor(req,keys){const input=getAllInputFor(req);req._oldInput=keys?Object.fromEntries(keys.filter((key)=>(key in input)).map((key)=>[key,input[key]])):{...input}}const REQUEST_METHODS={get(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},input(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},all(){return getAllInputFor(this)},only(keys){const input=getAllInputFor(this),result={};for(const key of keys)if(key in input)result[key]=input[key];return result},except(keys){const result={...getAllInputFor(this)};for(const key of keys)delete result[key];return result},has(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>(k in input)&&input[k]!==void 0);return key in input&&input[key]!==void 0},hasAny(keys){const input=getAllInputFor(this);return keys.some((k)=>(k in input)&&input[k]!==void 0)},filled(key){const input=getAllInputFor(this),isFilled=(k)=>{const value=input[k];return value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0)};if(Array.isArray(key))return key.every(isFilled);return isFilled(key)},missing(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>!(k in input)||input[k]===void 0);return!(key in input)||input[key]===void 0},merge(data){Object.assign(getAllInputFor(this),data)},keys(){return Object.keys(getAllInputFor(this))},string(key,defaultValue=""){const value=getAllInputFor(this)[key];return value!==void 0&&value!==null?String(value):defaultValue},integer(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?Math.trunc(value):defaultValue;const str=String(value).trim();if(!/^-?\d+$/.test(str))return defaultValue;const parsed=Number.parseInt(str,10);return Number.isFinite(parsed)?parsed:defaultValue},float(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?value:defaultValue;const str=String(value).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(str))return defaultValue;const parsed=Number.parseFloat(str);return Number.isFinite(parsed)?parsed:defaultValue},boolean(key,defaultValue=!1){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return defaultValue;if(typeof value==="boolean")return value;if(value==="true"||value==="1"||value===1)return!0;if(value==="false"||value==="0"||value===0)return!1;return defaultValue},array(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return value;return value!==void 0&&value!==null?[value]:[]},date(key){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return null;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?null:parsed},enum(key,enumType){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return null;if(Object.values(enumType).includes(value))return value;const enumKey=String(value);return enumKey in enumType?enumType[enumKey]:null},collect(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return collect(value);return collect(value===void 0||value===null?[]:[value])},whenHas(key,callback,defaultCallback){const input=getAllInputFor(this);if(key in input&&input[key]!==void 0)callback(input[key]);else defaultCallback?.()},whenFilled(key,callback,defaultCallback){const value=getAllInputFor(this)[key];if(value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0))callback(value);else defaultCallback?.()},isValue(key,value){return getAllInputFor(this)[key]===value},async validate(rules,messages={}){const selectedRules=rules??this._requestValidationRules;if(!selectedRules||Object.keys(selectedRules).length===0){const input=getAllInputFor(this);this._validatedInput=input;return input}const normalized={};for(const[field,definition]of Object.entries(selectedRules)){if(typeof definition==="string")throw TypeError(`String validation rules are not supported for "${field}". Use schema validators.`);if(definition&&typeof definition==="object"&&"rule"in definition){const message=messages[field];normalized[field]=message?{...definition,message}:definition}else normalized[field]=definition}const{validate}=await import("@stacksjs/validation"),validated=await validate(this,normalized);this._validatedInput=validated;return validated},getValidated(){return this._validatedInput??{}},safe(){const data=this._validatedInput??{};return{all:()=>({...data}),get:(key,defaultValue)=>(key in data)?data[key]:defaultValue,only:(keys)=>Object.fromEntries(keys.filter((key)=>(key in data)).map((key)=>[key,data[key]])),except:(keys)=>Object.fromEntries(Object.entries(data).filter(([key])=>!keys.includes(key)))}},old(key,defaultValue){return this._oldInput?.[key]??defaultValue},flashInput(keys){flashInputFor(this,keys)},flashInputOnly(keys){flashInputFor(this,keys)},flashInputExcept(keys){const input=getAllInputFor(this);this._oldInput=Object.fromEntries(Object.entries(input).filter(([key])=>!keys.includes(key)))},file(key){const file=(this.files||{})[key];if(!file)return null;const rawFile=Array.isArray(file)?file[0]:file;return rawFile?new UploadedFile(rawFile):null},getFiles(key){const file=(this.files||{})[key];if(!file)return[];return(Array.isArray(file)?file:[file]).map((f)=>new UploadedFile(f))},hasFile(key){const files=this.files||{};return key in files&&files[key]!==void 0},allFiles(){const files=this.files||{},result={};for(const[key,value]of Object.entries(files))if(Array.isArray(value))result[key]=value.map((f)=>new UploadedFile(f));else result[key]=new UploadedFile(value);return result},getParams(){return{...this.params}},isEmpty(){return Object.keys(getAllInputFor(this)).length===0},browser(){return this.headers.get("sec-ch-ua")||this.headers.get("user-agent")},ipForRateLimit(){const ip=this.ip;if(typeof ip==="function")return ip.call(this)||null;return typeof ip==="string"&&ip?ip:null},getMethod(){return this.method.toUpperCase()},async user(){return this._authenticatedUser},async userToken(){return this._currentAccessToken},async tokenCan(ability){if(typeof ability!=="string"||ability.length===0)return!1;const token=this._currentAccessToken;if(!token||typeof token!=="object")return!1;if(!Array.isArray(token.abilities))return!1;if(token.abilities.includes("*"))return!0;return token.abilities.includes(ability)},async tokenCant(ability){return!await this.tokenCan(ability)},async can(ability,...args){if(typeof ability!=="string"||ability.length===0)return!1;const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;return Gate.allows(ability,user,...args)},async cannot(ability,...args){return!await this.can(ability,...args)},async authorize(ability,...args){const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;await Gate.authorize(ability,user,...args)}};let csrfModule,csrfModuleLoad;function loadCsrfModule(){if(csrfModule!==void 0)return csrfModule;csrfModuleLoad??=import(resolveDefaultsPath("app/Middleware/Csrf.ts")).then((mod)=>{csrfModule=mod;return csrfModule}).catch(()=>{csrfModule=null;return null});return csrfModuleLoad}export function clearCsrfModuleCache(){csrfModule=void 0;csrfModuleLoad=void 0}function applyCsrfRenderToken(req,cookieHeader,mod){const token=mod.generateCsrfToken();req._csrfToken=token;try{const merged=cookieHeader?`${cookieHeader}; ${mod.CSRF_COOKIE_NAME}=${token}`:`${mod.CSRF_COOKIE_NAME}=${token}`;req.headers.set("cookie",merged)}catch{}}function seedCsrfTokenForRender(req){const method=req.method?.toUpperCase?.()??"GET";if(method!=="GET"&&method!=="HEAD")return;const cookieHeader=req.headers?.get?.("cookie")??"";if(cookieHeader.includes("X-CSRF-Token=")||cookieHeader.includes("csrf-token="))return;const mod=loadCsrfModule();if(mod===null)return;if(mod instanceof Promise)return mod.then((resolved)=>{if(resolved)applyCsrfRenderToken(req,cookieHeader,resolved)});applyCsrfRenderToken(req,cookieHeader,mod)}export function enhanceRequest(req){const routeParams=req.params??{};req.params=routeParams;applyRequestEnhancements(req,routeParams);if(!req._requestId)req._requestId=incomingRequestId(req)??crypto.randomUUID();Object.assign(req,REQUEST_METHODS);return req}function incomingRequestId(req){try{const supplied=req.headers?.get?.("x-request-id")?.trim();if(supplied&&/^[\w.:-]{8,200}$/.test(supplied))return supplied}catch{}return}function wrapHandler(handler,skipParsing=!1,handlerKey=""){if(isRouterAction(handler))return wrapAction(handler,handlerKey);if(typeof handler==="string"){const handlerPath=handler;return async(req)=>{try{if(!skipParsing){await parseRequestBody(req);req=enhanceRequest(req)}return await(await resolveStringHandler(handlerPath))(req)}catch(error){report(error,{label:`[Router] ${handlerPath}`});const rawStatus=error?.statusCode??error?.status,status=typeof rawStatus==="number"&&Number.isInteger(rawStatus)&&rawStatus>=400&&rawStatus<600?rawStatus:void 0;return await createErrorResponse(error instanceof Error?error:Error(String(error)),req,{handlerPath,status})}}}const fn=handler;return async(req)=>{const result=await fn(req);return formatResult(result,req)}}async function readJsonBodyOnce(req,contentType){const raw=await req.text();req._rawBody=raw;const target=req;target.text=()=>Promise.resolve(raw);target.json=()=>{try{return Promise.resolve(raw.length===0?null:JSON.parse(raw))}catch(err){return Promise.reject(err)}};target.bytes=()=>Promise.resolve(new TextEncoder().encode(raw));target.arrayBuffer=()=>{const bytes=new TextEncoder().encode(raw);return Promise.resolve(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength))};target.blob=()=>Promise.resolve(new Blob([raw],{type:contentType}));target.clone=()=>new Request(req.url,{method:req.method,headers:req.headers,body:raw});return raw}async function parseRequestBody(req){if(req._bodyParsed)return;req._bodyParsed=!0;const contentType=req.headers.get("content-type")||"";try{if(JSON_CONTENT_TYPE.test(contentType)){const raw=await readJsonBodyOnce(req,contentType);if(raw.length===0)req.jsonBody={};else try{const body=JSON.parse(raw);req.jsonBody=body&&typeof body==="object"?body:{}}catch(parseErr){const message=parseErr instanceof Error?parseErr.message:"Invalid JSON",{HttpError}=await import("@stacksjs/error-handling");throw new HttpError(400,`Invalid JSON body: ${message}`)}}else if(contentType.includes("application/x-www-form-urlencoded")){const text=await req.clone().text(),params=new URLSearchParams(text),formBody={};params.forEach((value,key)=>{formBody[key]=value});req.formBody=formBody}else if(contentType.includes("multipart/form-data")){const formData=await req.clone().formData(),formBody={},files={};formData.forEach((value,key)=>{if(value instanceof File)if(files[key])if(Array.isArray(files[key]))files[key].push(value);else files[key]=[files[key],value];else files[key]=value;else formBody[key]=value});Reflect.set(req,"formBody",formBody);Reflect.set(req,"files",files)}}catch(e){if(typeof(e?.status??e?.statusCode)==="number")throw e;log.debug("[stacks-router] Body parsing failed:",e)}}export function createStacksRouter(config={}){const bunRouter=new Router({verbose:config.verbose??!1});let currentPrefix="",currentGroupMiddleware=[],currentGroupApiResponse=!1;const registeredRouteKeys=new Set;function registerRoute(method,path,_handler){const fullPath=currentPrefix+path,routeKey=`${method}:${fullPath}`;log.debug(`[router] ${method} ${fullPath} \u2192 ${typeof _handler==="string"?_handler:"function"}`);const shadowed=registeredRouteKeys.has(routeKey);if(!shadowed)registeredRouteKeys.add(routeKey);if(!shadowed&&currentGroupMiddleware.length>0)routeMiddlewareRegistry.set(routeKey,[...currentGroupMiddleware]);if(!shadowed&&currentGroupApiResponse)routeApiResponseRegistry.add(routeKey);if(!shadowed&&typeof _handler==="string")routeHandlerKeyRegistry.set(routeKey,_handler);if(!shadowed&&isRouterAction(_handler))routeActionRegistry.set(routeKey,_handler);return{fullPath,routeKey,shadowed}}const stacksRouter={bunRouter,get routes(){return bunRouter.routes},get(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("GET",path,handler);bunRouter.get(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},post(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("POST",path,handler);bunRouter.post(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},put(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("PUT",path,handler);bunRouter.put(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},patch(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("PATCH",path,handler);bunRouter.patch(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},delete(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("DELETE",path,handler);bunRouter.delete(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},options(path,handler){const{fullPath,routeKey,shadowed}=registerRoute("OPTIONS",path,handler);bunRouter.options(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey,shadowed)},group(options,callback){const previousPrefix=currentPrefix,previousMiddleware=[...currentGroupMiddleware],previousApiResponse=currentGroupApiResponse;if(options.prefix)currentPrefix=previousPrefix+options.prefix;const middlewareList=options.middleware?Array.isArray(options.middleware)?options.middleware:[options.middleware]:void 0;if(middlewareList)currentGroupMiddleware=[...currentGroupMiddleware,...middlewareList];if(options.apiResponse===!0)currentGroupApiResponse=!0;log.debug(`[router] Entering group: prefix=${options.prefix||"/"} middleware=[${middlewareList?.join(", ")||""}]${currentGroupApiResponse?" apiResponse=true":""}`);const result=callback();if(result instanceof Promise)return result.then(()=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter}).catch((err)=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;throw err});currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter},resource(name,handler,options){const actions=["index","store","show","update","destroy"],activeActions=options?.only?actions.filter((a)=>options.only.includes(a)):options?.except?actions.filter((a)=>!options.except.includes(a)):actions,stripped=handler.replace(/Action$/,""),handlerBase=stripped.startsWith("Actions/")?stripped:`Actions/${stripped}`;log.debug(`[router] Resource: /${name} \u2192 ${handlerBase}*Action [${activeActions.join(", ")}]`);const sibling=(suffix)=>`${handlerBase}${suffix}`,registerResourceRoutes=()=>{for(const action of activeActions)switch(action){case"index":stacksRouter.get(`/${name}`,sibling("IndexAction"));break;case"store":stacksRouter.post(`/${name}`,sibling("StoreAction"));break;case"show":stacksRouter.get(`/${name}/:id`,sibling("ShowAction"));break;case"update":stacksRouter.put(`/${name}/:id`,sibling("UpdateAction"));break;case"destroy":stacksRouter.delete(`/${name}/:id`,sibling("DestroyAction"));break}};if(options?.middleware)stacksRouter.group({middleware:options.middleware},registerResourceRoutes);else registerResourceRoutes();return stacksRouter},match(methods,path,handler){log.debug(`[router] Match: [${methods.join(", ")}] ${path} \u2192 ${typeof handler==="string"?handler:"function"}`);let firstShadowed=!1;for(const[index,method]of methods.entries()){const m=method.toUpperCase(),{fullPath,routeKey,shadowed}=registerRoute(m,path,handler);if(index===0)firstShadowed=shadowed;const wrappedHandler=createMiddlewareHandler(routeKey,handler);switch(m){case"GET":bunRouter.get(fullPath,wrappedHandler);break;case"POST":bunRouter.post(fullPath,wrappedHandler);break;case"PUT":bunRouter.put(fullPath,wrappedHandler);break;case"PATCH":bunRouter.patch(fullPath,wrappedHandler);break;case"DELETE":bunRouter.delete(fullPath,wrappedHandler);break;case"OPTIONS":bunRouter.options(fullPath,wrappedHandler);break}}return createChainableRoute(`${methods[0]}:${currentPrefix}${path}`,firstShadowed)},health(){bunRouter.get("/api/health",async()=>{const health=await checkApplicationHealth();return Response.json(health,{status:health.status==="healthy"?200:503})});bunRouter.get("/__routes",(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});return Response.json(listRegisteredRoutes())});bunRouter.get("/__storage/:path",async(req)=>{const url=new URL(req.url),token=url.searchParams.get("token"),params=req.params,rawPath=params?.path?decodeURIComponent(params.path):decodeURIComponent(url.pathname.replace(/^\/__storage\//,""));if(!token||typeof rawPath!=="string"||rawPath.length===0)return new Response("Forbidden",{status:403});const{verifySignedStorageToken,Storage}=await import("@stacksjs/storage");if(!verifySignedStorageToken(token,rawPath).valid)return new Response("Forbidden",{status:403});try{const adapter=Storage.disk();if(!await adapter.fileExists(rawPath))return new Response("Not Found",{status:404});const buf=await adapter.readToBuffer(rawPath),mime=await adapter.mimeType(rawPath).catch(()=>"application/octet-stream");return new Response(buf,{status:200,headers:{"Content-Type":mime,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(err){log.error("[storage] signed-url fetch failed:",err);return new Response("Internal Error",{status:500})}});bunRouter.get("/__openapi.json",async(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});try{const{generateOpenApi}=await import("@stacksjs/api"),spec=await generateOpenApi({write:!1,portable:!1});return Response.json(spec)}catch(err){return Response.json({error:"OpenAPI generation failed",message:err instanceof Error?err.message:String(err)},{status:500})}});return stacksRouter},use(middleware){const adapted=adaptMiddlewareForBunRouter(middleware);bunRouter.globalMiddleware.push(adapted);return stacksRouter},booting(name,run){bootHooks.push({name,run});return stacksRouter},async serve(options={}){warnOnMultipleRouterInstances();configureViewDirectories(bunRouter);wrapHandleRequestForCsrf(bunRouter);await runBootHooks();return bunRouter.serve(options)},async handleRequest(req){return bunRouter.handleRequest(req)},getAllowedMethods(pathname,domain){return bunRouter.getAllowedMethods(pathname,domain)},async register(routePath,options){log.debug(`[router] Register: ${routePath} prefix=${options?.prefix||"none"}`);const callback=async()=>{await import(routePath)};if(options?.prefix||options?.middleware)await stacksRouter.group({prefix:options.prefix,middleware:options.middleware},callback);else await callback();return stacksRouter},async importRoutes(){log.debug("[router] Loading user routes from registry...");try{const{loadRoutes}=await import("./route-loader"),{appPath}=await import("@stacksjs/path"),routeRegistry=(await import(appPath("Routes.ts"))).default;await loadRoutes(routeRegistry)}catch(error){log.error("Failed to load route registry:",error);throw error}log.debug("[router] Loading ORM routes...");const ormRoutesCandidates=[p.frameworkPath("orm/routes.ts"),p.frameworkPath("core/orm/routes.ts")];let ormRoutesLoaded=!1;for(const candidate of ormRoutesCandidates)try{if(await Bun.file(candidate).exists()){await import(candidate);ormRoutesLoaded=!0;break}}catch(error){log.warn(`[router] ORM routes candidate failed to load, falling back to next: ${candidate}
5
5
  `,error)}if(!ormRoutesLoaded)try{await import("@stacksjs/orm/routes");ormRoutesLoaded=!0}catch(error){log.warn(`[router] ORM routes could not be loaded from @stacksjs/orm either
6
- `,error)}if(!ormRoutesLoaded)log.warn("[router] No ORM routes candidate loaded - model useApi endpoints are unavailable.");log.debug("[router] Loading discovered package routes...");try{await stacksRouter.loadDiscoveredRoutes()}catch(error){log.debug("Package route discovery skipped:",error)}await assertRouteMiddlewareResolvable()},async loadDiscoveredRoutes(){try{const manifestPath=p.storagePath("framework/discovered-packages.json"),file=Bun.file(manifestPath);if(!await file.exists())return;const packages=(await file.json())?.packages;if(!packages)return;const pantryDir=p.projectPath("pantry");for(const[pkgName,meta]of Object.entries(packages)){const routes=meta?.routes;if(!routes)continue;const routeList=Array.isArray(routes)?routes:[routes],pkgDir=`${pantryDir}/${pkgName}`;for(const routeFile of routeList){log.debug(`[router] Discovered route: ${pkgName} \u2192 ${routeFile}`);const fullPath=routeFile.startsWith("/")?routeFile:`${pkgDir}/${routeFile}`,prefix=meta?.routePrefix,middleware=meta?.routeMiddleware;try{await stacksRouter.register(fullPath,{prefix,middleware})}catch(err){log.warn(`Failed to load routes from package '${pkgName}': ${err}`)}}}}catch{}}};return stacksRouter}function wrapHandleRequestForCsrf(bunRouter){const router=bunRouter;if(router._csrfSeedingWrapped)return;const original=router.handleRequest.bind(router);router.handleRequest=async(request)=>{const method=request.method?.toUpperCase?.()??"GET",safe=method==="GET"||method==="HEAD"||method==="OPTIONS";if(safe)await seedCsrfTokenForRender(request);const response=await original(request);if(!safe||!response)return response;try{const{seedCsrfCookieIfMissing}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts"));return seedCsrfCookieIfMissing(request,response,request._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed on the view path",{error:err});return response}};router._csrfSeedingWrapped=!0}export function configureViewDirectories(bunRouter){const router=bunRouter;if(typeof router.views!=="function")return;const existing=router._fileRoutingConfig;if(existing&&Object.keys(existing).length>0)return;if(!existsSync(p.projectPath("resources/views")))return;const layouts=[p.projectPath("resources/views/layouts"),p.projectPath("resources/layouts")].find(existsSync),partials=[p.projectPath("resources/views/partials"),p.projectPath("resources/partials")].find(existsSync),components=[p.projectPath("resources/components"),p.projectPath("resources/views/components")].find(existsSync);router.views({...components?{componentsDir:components}:{},...layouts?{layoutsDir:layouts}:{},...partials?{partialsDir:partials}:{}})}export function disableViewRouting(bunRouter){const router=bunRouter;if(typeof router.disableFileRouting!=="function")return!1;const existing=router._fileRoutingConfig;if(existing&&Object.keys(existing).length>0)return!1;router.disableFileRouting();return!0}const ROUTE_SINGLETON_KEY=Symbol.for("@stacksjs/router:route-singleton");export const route=globalThis[ROUTE_SINGLETON_KEY]??=createStacksRouter();let routesLoadPromise=null,routingContextRunner=null;async function getRoutingContextRunner(){if(!routingContextRunner)try{const{withRoutingContext}=await import("@stacksjs/database");routingContextRunner=typeof withRoutingContext==="function"?withRoutingContext:(fn)=>fn()}catch{routingContextRunner=(fn)=>fn()}return routingContextRunner}export async function serverResponse(request,_body){return(await getRoutingContextRunner())(()=>handleServerRequest(request))}async function handleServerRequest(request){if(!routesLoadPromise){log.debug("[router] Loading routes for first time...");routesLoadPromise=route.importRoutes().catch((err)=>{routesLoadPromise=null;throw err})}await routesLoadPromise;const response=await route.handleRequest(request);if(response.status===404&&response.headers.get("content-type")?.includes("json"))try{const body=await response.clone().json();if(body?.message==="Not Found"||body?.error==="Not Found"){const url=new URL(request.url),enriched={...body,path:url.pathname,method:request.method};return new Response(JSON.stringify(enriched),{status:404,headers:response.headers})}}catch{}return response}export async function serve(options={}){return route.serve(options)}
6
+ `,error)}if(!ormRoutesLoaded)log.warn("[router] No ORM routes candidate loaded - model useApi endpoints are unavailable.");log.debug("[router] Loading discovered package routes...");try{await stacksRouter.loadDiscoveredRoutes()}catch(error){log.debug("Package route discovery skipped:",error)}await assertRouteMiddlewareResolvable()},async loadDiscoveredRoutes(){try{const manifestPath=p.storagePath("framework/discovered-packages.json"),file=Bun.file(manifestPath);if(!await file.exists())return;const packages=(await file.json())?.packages;if(!packages)return;const pantryDir=p.projectPath("pantry");for(const[pkgName,meta]of Object.entries(packages)){const routes=meta?.routes;if(!routes)continue;const routeList=Array.isArray(routes)?routes:[routes],pkgDir=`${pantryDir}/${pkgName}`;for(const routeFile of routeList){log.debug(`[router] Discovered route: ${pkgName} \u2192 ${routeFile}`);const fullPath=routeFile.startsWith("/")?routeFile:`${pkgDir}/${routeFile}`,prefix=meta?.routePrefix,middleware=meta?.routeMiddleware;try{await stacksRouter.register(fullPath,{prefix,middleware})}catch(err){log.warn(`Failed to load routes from package '${pkgName}': ${err}`)}}}}catch{}}};return stacksRouter}function wrapHandleRequestForCsrf(bunRouter){const router=bunRouter;if(router._csrfSeedingWrapped)return;const original=router.handleRequest.bind(router);router.handleRequest=async(request)=>{const method=request.method?.toUpperCase?.()??"GET",safe=method==="GET"||method==="HEAD"||method==="OPTIONS";if(safe){const seeding=seedCsrfTokenForRender(request);if(seeding)await seeding}const response=await original(request);if(!safe||!response)return response;try{const mod=loadCsrfModule(),csrf=mod instanceof Promise?await mod:mod;if(!csrf)return response;return csrf.seedCsrfCookieIfMissing(request,response,request._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed on the view path",{error:err});return response}};router._csrfSeedingWrapped=!0}export function configureViewDirectories(bunRouter){const router=bunRouter;if(typeof router.views!=="function")return;const existing=router._fileRoutingConfig;if(existing&&Object.keys(existing).length>0)return;if(!existsSync(p.projectPath("resources/views")))return;const layouts=[p.projectPath("resources/views/layouts"),p.projectPath("resources/layouts")].find(existsSync),partials=[p.projectPath("resources/views/partials"),p.projectPath("resources/partials")].find(existsSync),components=[p.projectPath("resources/components"),p.projectPath("resources/views/components")].find(existsSync);router.views({...components?{componentsDir:components}:{},...layouts?{layoutsDir:layouts}:{},...partials?{partialsDir:partials}:{}})}export function disableViewRouting(bunRouter){const router=bunRouter;if(typeof router.disableFileRouting!=="function")return!1;const existing=router._fileRoutingConfig;if(existing&&Object.keys(existing).length>0)return!1;router.disableFileRouting();return!0}const ROUTE_SINGLETON_KEY=Symbol.for("@stacksjs/router:route-singleton");export const route=globalThis[ROUTE_SINGLETON_KEY]??=createStacksRouter();let routesLoadPromise=null,routingContextRunner=null;async function getRoutingContextRunner(){if(!routingContextRunner)try{const{withRoutingContext}=await import("@stacksjs/database");routingContextRunner=typeof withRoutingContext==="function"?withRoutingContext:(fn)=>fn()}catch{routingContextRunner=(fn)=>fn()}return routingContextRunner}export async function serverResponse(request,_body){return(await getRoutingContextRunner())(()=>handleServerRequest(request))}async function handleServerRequest(request){if(!routesLoadPromise){log.debug("[router] Loading routes for first time...");routesLoadPromise=route.importRoutes().catch((err)=>{routesLoadPromise=null;throw err})}await routesLoadPromise;const response=await route.handleRequest(request);if(response.status===404&&response.headers.get("content-type")?.includes("json"))try{const body=await response.clone().json();if(body?.message==="Not Found"||body?.error==="Not Found"){const url=new URL(request.url),enriched={...body,path:url.pathname,method:request.method};return new Response(JSON.stringify(enriched),{status:404,headers:response.headers})}}catch{}return response}export async function serve(options={}){return route.serve(options)}
@@ -0,0 +1,10 @@
1
+ import type { StacksRouterInstance } from './stacks-router';
2
+ import type { TypedRouter } from '@stacksjs/bun-router';
3
+ /**
4
+ * Build a typed route group on top of a Stacks router.
5
+ *
6
+ * Defaults to the shared `route` singleton, so a route file can use this and
7
+ * the string form side by side and both land in the same table. Pass a router
8
+ * explicitly when you are assembling one yourself (tests do this).
9
+ */
10
+ export declare function createTypedRouter(router?: StacksRouterInstance): TypedRouter;
@@ -0,0 +1 @@
1
+ import{createTypedRouter as createBunTypedRouter}from"@stacksjs/bun-router";import{route as defaultRoute}from"./stacks-router";export function createTypedRouter(router=defaultRoute){return createBunTypedRouter(router)}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/router",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.72.56",
5
+ "version": "0.72.60",
6
6
  "description": "The Stacks framework router.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -56,23 +56,24 @@
56
56
  "build": "bun build.ts",
57
57
  "build:user": "bun build2.ts",
58
58
  "typecheck": "bun tsc --noEmit",
59
+ "typecheck:types": "bun tsc --noEmit -p tsconfig.type-tests.json --pretty false",
59
60
  "prepublishOnly": "bun run build"
60
61
  },
61
62
  "dependencies": {
62
- "@stacksjs/bun-router": "^0.1.0",
63
- "@stacksjs/collections": "0.72.56",
63
+ "@stacksjs/bun-router": "^0.1.7",
64
+ "@stacksjs/collections": "0.72.60",
64
65
  "ts-rate-limiter": "^0.4.2"
65
66
  },
66
67
  "devDependencies": {
67
- "@stacksjs/actions": "0.72.56",
68
- "@stacksjs/config": "0.72.56",
68
+ "@stacksjs/actions": "0.72.60",
69
+ "@stacksjs/config": "0.72.60",
69
70
  "better-dx": "^0.2.24",
70
- "@stacksjs/error-handling": "0.72.56",
71
- "@stacksjs/logging": "0.72.56",
72
- "@stacksjs/orm": "0.72.56",
73
- "@stacksjs/path": "0.72.56",
74
- "@stacksjs/storage": "0.72.56",
75
- "@stacksjs/types": "0.72.56",
76
- "@stacksjs/validation": "0.72.56"
71
+ "@stacksjs/error-handling": "0.72.60",
72
+ "@stacksjs/logging": "0.72.60",
73
+ "@stacksjs/orm": "0.72.60",
74
+ "@stacksjs/path": "0.72.60",
75
+ "@stacksjs/storage": "0.72.60",
76
+ "@stacksjs/types": "0.72.60",
77
+ "@stacksjs/validation": "0.72.60"
77
78
  }
78
79
  }
@@ -1,7 +0,0 @@
1
- /**
2
- * Action path types for the Stacks router.
3
- * This file is auto-generated or manually maintained to provide
4
- * type-safe string paths for routing to actions and controllers.
5
- */
6
- // Base type for all action paths - will be narrowed as actions are added
7
- export type StacksActionPath = string;
File without changes