@stacksjs/router 0.75.529 → 0.75.535

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.
@@ -23,4 +23,4 @@ export declare function isApiRequest(req: Request | { headers: Headers }): boole
23
23
  * a valid header), and the subtype stops at the parameters - `.+` used to run
24
24
  * on into them, so `application/x; a=b+json` counted as JSON.
25
25
  */
26
- export declare const JSON_CONTENT_TYPE: unknown;
26
+ export declare const JSON_CONTENT_TYPE: RegExp;
package/dist/body.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { JsonParseOptions } from './json';
2
- export declare function readJsonBody(request: Request, maxBytes?: unknown, options?: JsonParseOptions): Promise<unknown>;
2
+ export declare function readJsonBody(request: Request, maxBytes?: number, options?: JsonParseOptions): Promise<unknown>;
3
3
  /** Bounded UTF-8 for form and text protocols, counted from actual streamed bytes. */
4
- export declare function readTextBody(request: Request, maxBytes?: unknown): Promise<string>;
4
+ export declare function readTextBody(request: Request, maxBytes?: number): Promise<string>;
5
5
  /** Bounded body reads for protocol handlers that need the original wire body. */
6
6
  export declare class RequestBodyError extends Error {
7
7
  readonly status: 400 | 413 | 415;
@@ -1,5 +1,5 @@
1
- import './query-tracking';
2
1
  import type { EnhancedRequest } from '@stacksjs/bun-router';
2
+ import './query-tracking';
3
3
  /**
4
4
  * Create an Ignition-style error response for development
5
5
  */
@@ -1,5 +1,5 @@
1
- import type { Collection } from '@stacksjs/types';
2
1
  import type { FileInfo } from '@stacksjs/bun-router';
2
+ import type { Collection } from '@stacksjs/types';
3
3
  /**
4
4
  * Stacks-specific marker fields attached to the request by the
5
5
  * router itself and the framework's default middleware.
@@ -1,15 +1,6 @@
1
1
  import type { EnhancedRequest } from '@stacksjs/bun-router';
2
2
  import type { RequestInstance } from '@stacksjs/types';
3
3
  import type { StacksRequestMarkers } from './request-augmentation';
4
- /**
5
- * Read the active trace id, or `undefined` outside any traced scope.
6
- *
7
- * Falls back to the request's `_requestId` if no explicit trace was
8
- * set so the helper is always useful from an HTTP handler — the router
9
- * sets `_requestId` per request, and that value is the implicit trace
10
- * for downstream calls until something more specific is configured.
11
- */
12
- export declare function getTraceId(): string | undefined;
13
4
  /**
14
5
  * Run `fn` under a fresh trace scope. Used by queue workers and cron
15
6
  * triggers to associate background work with the originating request
@@ -135,7 +135,7 @@ export declare const DEFAULT_ROUTE_REGISTRY: RouteRegistry;
135
135
  * cookie and the `/locale/{code}` redirect, and bootstrap registers it
136
136
  * unconditionally.
137
137
  */
138
- export declare const DEFAULT_ROUTE_BUNDLES: readonly ['auth', 'dashboard', 'delivery', 'email', 'forms', 'payments'];
138
+ export declare const DEFAULT_ROUTE_BUNDLES: readonly ['auth', 'dashboard', 'delivery', 'email', 'forms', 'payments', 'storefront'];
139
139
  /**
140
140
  * Bundles an app must ask for. Excluded from the implicit default AND from
141
141
  * `all`, because both are what an app that said nothing gets: `social` mounts
@@ -154,18 +154,8 @@ export declare const DEFAULT_ROUTE_BUNDLES_KEY: '__stacksDefaultRouteBundles';
154
154
  * `defaults/bootstrap.ts` gives: `config/auth.ts` ships enabled in every app,
155
155
  * so gating on it would widen existing apps' public surface on upgrade.
156
156
  */
157
- export declare const DEFAULT_ROUTE_BUNDLE_FEATURES: Record<typeof DEFAULT_ROUTE_BUNDLES[number], string>;
158
- export declare interface RootMountedAppRoute {
159
- method: string
160
- path: string
161
- file: string
162
- }
163
- /** What {@link loadFrameworkRoutes} publishes for bootstrap.ts. */
164
- export declare interface DefaultRouteBundleSelection {
165
- bundles: ReadonlySet<string>
166
- explicit: boolean
167
- }
168
- export type DefaultRouteBundle = typeof DEFAULT_ROUTE_BUNDLES[number] | typeof OPT_IN_ROUTE_BUNDLES[number];
157
+ export declare const DEFAULT_ROUTE_BUNDLE_FEATURES: Record<typeof DEFAULT_ROUTE_BUNDLES[number], string>
158
+
169
159
  /**
170
160
  * The feature names the router asks about, and nothing wider.
171
161
  *
@@ -177,3 +167,14 @@ export type DefaultRouteBundle = typeof DEFAULT_ROUTE_BUNDLES[number] | typeof O
177
167
  * the router knew (stacksjs/stacks#2867).
178
168
  */
179
169
  export type DefaultRouteBundleFeature = typeof DEFAULT_ROUTE_BUNDLE_FEATURES[keyof typeof DEFAULT_ROUTE_BUNDLE_FEATURES];
170
+ export declare interface RootMountedAppRoute {
171
+ method: string
172
+ path: string
173
+ file: string
174
+ }
175
+ /** What {@link loadFrameworkRoutes} publishes for bootstrap.ts. */
176
+ export declare interface DefaultRouteBundleSelection {
177
+ bundles: ReadonlySet<string>
178
+ explicit: boolean
179
+ }
180
+ export type DefaultRouteBundle = typeof DEFAULT_ROUTE_BUNDLES[number] | typeof OPT_IN_ROUTE_BUNDLES[number];
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{log}from"@stacksjs/logging/runtime";import{route,withFallbackRouteNames}from"./stacks-router";let rootMountedAppRoutes;export function listRootMountedAppRoutes(){return rootMountedAppRoutes??=[]}export const DEFAULT_ROUTE_REGISTRY={api:"api"};export async function appRouteRegistry(){const{projectPath}=await import("@stacksjs/path");const file=projectPath("app/Routes.ts");if(!existsSync(file))return DEFAULT_ROUTE_REGISTRY;const registry=(await import(file)).default;if(!registry||typeof registry!=="object"||Object.keys(registry).length===0){log.debug("[route-loader] app/Routes.ts exports no registry; using the default");return DEFAULT_ROUTE_REGISTRY}return registry}export async function loadRoutes(registry){for(const[key,definition]of Object.entries(registry)){const config=normalizeDefinition(definition);const prefix=config.prefix!==undefined?config.prefix?config.prefix.startsWith("/")?config.prefix:`/${config.prefix}`:undefined:key==="web"?undefined:`/${key}`;const middleware=normalizeMiddleware(config.middleware);log.debug(`[route-loader] Loading: ${config.path} prefix=${prefix||"/"} middleware=[${middleware.join(", ")}]`);try{if(prefix||middleware.length>0){await route.group({prefix,middleware:middleware.length>0?middleware:undefined},async()=>{await importRouteFile(config.path)})}else{const before=registeredRouteKeys();await importRouteFile(config.path);for(const entry of currentRouteTable()){const method=String(entry.method??"").toUpperCase();const path=String(entry.path??"");if(!method||!path||before.has(`${method} ${path}`))continue;const routes=rootMountedAppRoutes??=[];routes.push({method,path,file:`routes/${config.path}.ts`})}}}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[Routes] Failed to load route file '${config.path}': ${message}`);throw new Error(`Route loading failed for '${config.path}': ${message}`)}}await loadFrameworkRoutes()}export const DEFAULT_ROUTE_BUNDLES=["auth","dashboard","delivery","email","forms","payments"];export const OPT_IN_ROUTE_BUNDLES=["social"];export const DEFAULT_ROUTE_BUNDLES_KEY="__stacksDefaultRouteBundles";export function resolveDefaultRouteBundles(env=process.env){return resolveDefaultRouteBundlesWithDiagnostics(env).bundles}export function resolveDefaultRouteBundlesWithDiagnostics(env=process.env){const all=()=>new Set(DEFAULT_ROUTE_BUNDLES);const raw=env.STACKS_DEFAULT_ROUTES;if(raw!==undefined){const names=raw.split(",").map((name)=>name.trim().toLowerCase()).filter(Boolean);if(names.length===0||names.includes("none"))return{bundles:new Set,unknown:[],explicit:true};if(names.includes("all"))return{bundles:all(),unknown:[],explicit:true};const bundles=new Set;const unknown=[];for(const name of names){if(DEFAULT_ROUTE_BUNDLES.includes(name)||OPT_IN_ROUTE_BUNDLES.includes(name)){bundles.add(name)}else{unknown.push(name)}}return{bundles,unknown,explicit:true}}if(env.STACKS_SKIP_DEFAULT_ROUTES==="1")return{bundles:new Set,unknown:[],explicit:true};return{bundles:all(),unknown:[],explicit:false}}export const DEFAULT_ROUTE_BUNDLE_FEATURES={auth:"dashboard",dashboard:"dashboard",delivery:"commerce",email:"email",forms:"forms",payments:"commerce"};export function bundleMounts(selection,bundle,featureEnabled){if(selection&&!selection.bundles.has(bundle))return false;return selection?.explicit?true:featureEnabled}export function mountedDefaultRouteBundles(featureEnabled,env=process.env){const selection=resolveDefaultRouteBundlesWithDiagnostics(env);const mounted=new Set;for(const bundle of DEFAULT_ROUTE_BUNDLES){if(bundleMounts(selection,bundle,featureEnabled(DEFAULT_ROUTE_BUNDLE_FEATURES[bundle])))mounted.add(bundle)}return mounted}async function loadFrameworkRoutes(){const{bundles,unknown,explicit}=resolveDefaultRouteBundlesWithDiagnostics();for(const name of unknown)log.warn(`[Routes] STACKS_DEFAULT_ROUTES lists unknown bundle "${name}" - known bundles are ${DEFAULT_ROUTE_BUNDLES.join(", ")}.`);if(bundles.size===0)return;globalThis[DEFAULT_ROUTE_BUNDLES_KEY]={bundles,explicit};try{try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch{}const{frameworkPath}=await import("@stacksjs/path");const bootstrapPath=frameworkPath("defaults/bootstrap.ts");if(await Bun.file(bootstrapPath).exists()){await withFallbackRouteNames(()=>import(bootstrapPath))}}catch(error){const message=error instanceof Error?error.message:String(error);if(!message.includes("Cannot find module")&&!message.includes("MODULE_NOT_FOUND")){console.error(`[Routes] Failed to load framework bootstrap: ${message}`)}}}function assertSafeRouteName(routeName){if(typeof routeName!=="string"||routeName.length===0)throw new Error(`[route-loader] Invalid route path: empty or non-string`);if(routeName.includes("\x00"))throw new Error(`[route-loader] Invalid route path: null byte`);let decoded;try{decoded=decodeURIComponent(routeName)}catch{throw new Error(`[route-loader] Invalid route path: malformed URL encoding`)}const cleanPath=decoded.replace(/\.ts$/,"");if(cleanPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(cleanPath))throw new Error(`[route-loader] Invalid route path: absolute paths not allowed (${cleanPath})`);const segments=cleanPath.split(/[/\\]/);if(segments.some((s)=>s===".."))throw new Error(`[route-loader] Invalid route path: '..' segment not allowed (${cleanPath})`);return cleanPath}async function importRouteFile(routeName){const cleanPath=assertSafeRouteName(routeName);const{isCompiledBinary,projectPath}=await import("@stacksjs/path");if(isCompiledBinary()){throw new Error(`[route-loader] Cannot load routes/${cleanPath} from a compiled binary: route files are read from disk at runtime, and a disk file cannot resolve the framework packages it imports from inside the bundle. Import the route file statically (\`import '../routes/${cleanPath}'\`) so it is bundled, or run the app with \`bun\` instead of compiling it.`)}await import(projectPath(`routes/${cleanPath}`))}function normalizeDefinition(def){if(typeof def==="string"){return{path:def}}return def}function normalizeMiddleware(middleware){if(!middleware)return[];if(typeof middleware==="string")return[middleware];return middleware}function currentRouteTable(){return route.routes??[]}function registeredRouteKeys(){const keys=new Set;for(const entry of currentRouteTable())keys.add(`${String(entry.method??"").toUpperCase()} ${String(entry.path??"")}`);return keys}
1
+ import{existsSync}from"node:fs";import{log}from"@stacksjs/logging/runtime";import{route,withFallbackRouteNames}from"./stacks-router";let rootMountedAppRoutes;export function listRootMountedAppRoutes(){return rootMountedAppRoutes??=[]}export const DEFAULT_ROUTE_REGISTRY={api:"api"};export async function appRouteRegistry(){const{projectPath}=await import("@stacksjs/path");const file=projectPath("app/Routes.ts");if(!existsSync(file))return DEFAULT_ROUTE_REGISTRY;const registry=(await import(file)).default;if(!registry||typeof registry!=="object"||Object.keys(registry).length===0){log.debug("[route-loader] app/Routes.ts exports no registry; using the default");return DEFAULT_ROUTE_REGISTRY}return registry}export async function loadRoutes(registry){for(const[key,definition]of Object.entries(registry)){const config=normalizeDefinition(definition);const prefix=config.prefix!==undefined?config.prefix?config.prefix.startsWith("/")?config.prefix:`/${config.prefix}`:undefined:key==="web"?undefined:`/${key}`;const middleware=normalizeMiddleware(config.middleware);log.debug(`[route-loader] Loading: ${config.path} prefix=${prefix||"/"} middleware=[${middleware.join(", ")}]`);try{if(prefix||middleware.length>0){await route.group({prefix,middleware:middleware.length>0?middleware:undefined},async()=>{await importRouteFile(config.path)})}else{const before=registeredRouteKeys();await importRouteFile(config.path);for(const entry of currentRouteTable()){const method=String(entry.method??"").toUpperCase();const path=String(entry.path??"");if(!method||!path||before.has(`${method} ${path}`))continue;const routes=rootMountedAppRoutes??=[];routes.push({method,path,file:`routes/${config.path}.ts`})}}}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[Routes] Failed to load route file '${config.path}': ${message}`);throw new Error(`Route loading failed for '${config.path}': ${message}`)}}await loadFrameworkRoutes()}export const DEFAULT_ROUTE_BUNDLES=["auth","dashboard","delivery","email","forms","payments","storefront"];export const OPT_IN_ROUTE_BUNDLES=["social"];export const DEFAULT_ROUTE_BUNDLES_KEY="__stacksDefaultRouteBundles";export function resolveDefaultRouteBundles(env=process.env){return resolveDefaultRouteBundlesWithDiagnostics(env).bundles}export function resolveDefaultRouteBundlesWithDiagnostics(env=process.env){const all=()=>new Set(DEFAULT_ROUTE_BUNDLES);const raw=env.STACKS_DEFAULT_ROUTES;if(raw!==undefined){const names=raw.split(",").map((name)=>name.trim().toLowerCase()).filter(Boolean);if(names.length===0||names.includes("none"))return{bundles:new Set,unknown:[],explicit:true};if(names.includes("all"))return{bundles:all(),unknown:[],explicit:true};const bundles=new Set;const unknown=[];for(const name of names){if(DEFAULT_ROUTE_BUNDLES.includes(name)||OPT_IN_ROUTE_BUNDLES.includes(name)){bundles.add(name)}else{unknown.push(name)}}return{bundles,unknown,explicit:true}}if(env.STACKS_SKIP_DEFAULT_ROUTES==="1")return{bundles:new Set,unknown:[],explicit:true};return{bundles:all(),unknown:[],explicit:false}}export const DEFAULT_ROUTE_BUNDLE_FEATURES={auth:"dashboard",dashboard:"dashboard",delivery:"commerce",email:"email",forms:"forms",payments:"commerce",storefront:"commerce"};export function bundleMounts(selection,bundle,featureEnabled){if(selection&&!selection.bundles.has(bundle))return false;return selection?.explicit?true:featureEnabled}export function mountedDefaultRouteBundles(featureEnabled,env=process.env){const selection=resolveDefaultRouteBundlesWithDiagnostics(env);const mounted=new Set;for(const bundle of DEFAULT_ROUTE_BUNDLES){if(bundleMounts(selection,bundle,featureEnabled(DEFAULT_ROUTE_BUNDLE_FEATURES[bundle])))mounted.add(bundle)}return mounted}async function loadFrameworkRoutes(){const{bundles,unknown,explicit}=resolveDefaultRouteBundlesWithDiagnostics();for(const name of unknown)log.warn(`[Routes] STACKS_DEFAULT_ROUTES lists unknown bundle "${name}" - known bundles are ${DEFAULT_ROUTE_BUNDLES.join(", ")}.`);if(bundles.size===0)return;globalThis[DEFAULT_ROUTE_BUNDLES_KEY]={bundles,explicit};try{try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch{}const{frameworkPath}=await import("@stacksjs/path");const bootstrapPath=frameworkPath("defaults/bootstrap.ts");if(await Bun.file(bootstrapPath).exists()){await withFallbackRouteNames(()=>import(bootstrapPath))}}catch(error){const message=error instanceof Error?error.message:String(error);if(!message.includes("Cannot find module")&&!message.includes("MODULE_NOT_FOUND")){console.error(`[Routes] Failed to load framework bootstrap: ${message}`)}}}function assertSafeRouteName(routeName){if(typeof routeName!=="string"||routeName.length===0)throw new Error(`[route-loader] Invalid route path: empty or non-string`);if(routeName.includes("\x00"))throw new Error(`[route-loader] Invalid route path: null byte`);let decoded;try{decoded=decodeURIComponent(routeName)}catch{throw new Error(`[route-loader] Invalid route path: malformed URL encoding`)}const cleanPath=decoded.replace(/\.ts$/,"");if(cleanPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(cleanPath))throw new Error(`[route-loader] Invalid route path: absolute paths not allowed (${cleanPath})`);const segments=cleanPath.split(/[/\\]/);if(segments.some((s)=>s===".."))throw new Error(`[route-loader] Invalid route path: '..' segment not allowed (${cleanPath})`);return cleanPath}async function importRouteFile(routeName){const cleanPath=assertSafeRouteName(routeName);const{isCompiledBinary,projectPath}=await import("@stacksjs/path");if(isCompiledBinary()){throw new Error(`[route-loader] Cannot load routes/${cleanPath} from a compiled binary: route files are read from disk at runtime, and a disk file cannot resolve the framework packages it imports from inside the bundle. Import the route file statically (\`import '../routes/${cleanPath}'\`) so it is bundled, or run the app with \`bun\` instead of compiling it.`)}await import(projectPath(`routes/${cleanPath}`))}function normalizeDefinition(def){if(typeof def==="string"){return{path:def}}return def}function normalizeMiddleware(middleware){if(!middleware)return[];if(typeof middleware==="string")return[middleware];return middleware}function currentRouteTable(){return route.routes??[]}function registeredRouteKeys(){const keys=new Set;for(const entry of currentRouteTable())keys.add(`${String(entry.method??"").toUpperCase()} ${String(entry.path??"")}`);return keys}
@@ -1,8 +1,6 @@
1
- import type { Server } from 'bun';
1
+ import type { ActionPath, EnhancedRequest, MiddlewareReference, RequestFor, Route } from '@stacksjs/bun-router/runtime';
2
2
  import './request-augmentation';
3
- import { response, Router } from '@stacksjs/bun-router/runtime';
4
- import type { ActionHandler, ActionPath, EnhancedRequest, ExtractRouteParams, KnownRouteName, MiddlewareHandler as BunMiddlewareHandler, MiddlewareReference, PathForRouteName, RequestFor, Route, ServerOptions } from '@stacksjs/bun-router/runtime';
5
- import type { ActionResult, ActionValidations, ValidationResult } from '@stacksjs/actions';
3
+ import type { ActionResult } from '@stacksjs/actions';
6
4
  /**
7
5
  * Run every registered boot hook, once per process.
8
6
  *
@@ -34,246 +32,9 @@ export declare function warnOnMultipleRouterInstances(): boolean;
34
32
  * overlapping constrained, domain-scoped, or mixed-parameter route expected.
35
33
  */
36
34
  export declare function shouldUseNativeRoutesByDefault(routes: readonly Route[]): boolean;
37
- /**
38
- * Register routes with an admission check in force, and report what it withheld.
39
- *
40
- * For the framework's default route bundles, whose actions can depend on
41
- * framework models an app has excluded from its schema. Registering one of
42
- * those routes served an endpoint that could only answer 500 over a table that
43
- * will never exist (stacksjs/stacks#2943). A withheld route is never handed to
44
- * bun-router, so it answers 404 like any route that does not exist, and the
45
- * chain API on it is inert.
46
- *
47
- * Applies to every router instance while `register` runs, and to nothing after.
48
- */
49
- export declare function withRouteAdmission(admit: RouteAdmission | undefined, register: () => Promise<void>): Promise<WithheldRoute[]>;
50
- /**
51
- * Merge framework bootstrap names beneath the app's existing named routes.
52
- * The loader registers app files first and awaits this boot phase before
53
- * serving. Merging definitions also retains their compiled parameter shapes;
54
- * no ambient registration mode changes ordinary app name() semantics.
55
- */
56
- export declare function withFallbackRouteNames(register: () => Promise<unknown>): Promise<void>;
57
- // False positive: this is an overload signature, which has no body for its
58
- // parameters to be used in. The implementation below uses them.
59
- // eslint-disable-next-line unused-imports/no-unused-vars
60
- export declare function url<TName extends KnownRouteName>(routeName: TName, ...params: RequiresUrlParams<TName> extends true ? [params: UrlParams<TName>] : [params?: UrlParams<TName>]): string;
61
- /**
62
- * List the placeholder names a named route expects — handy for
63
- * codegen/test cases and for detecting typos before runtime.
64
- */
65
- export declare function routeParams(routeName: string): string[];
66
- /**
67
- * Every named route, as `name → path`.
68
- *
69
- * `listRegisteredRoutes()` reports a name by searching the named registry for a
70
- * matching path, which answers "what is this route called" and cannot answer
71
- * "what routes are there names for" - two routes on one path give the first
72
- * name found, and a name whose route was never registered is invisible.
73
- *
74
- * The type generator needs the second question: it writes this map into the
75
- * router's type registry so `url('users.shwo')` stops compiling. Reading the
76
- * registry directly is the only way to get every name.
77
- */
78
- export declare function listNamedRoutes(): Record<string, string>;
79
- /**
80
- * Every `route.redirect()` and `route.permanentRedirect()`, in registration
81
- * order, with group prefixes applied. Read by the type generator, which writes
82
- * the page-path ones for the views server.
83
- */
84
- export declare function listRedirectRoutes(): RedirectRoute[];
85
- /**
86
- * Snapshot of the registered routes — `{ method, path, name?, handler? }` per
87
- * route. Used by `buddy route:list`, the dev-server startup banner, and the
88
- * OpenAPI generator.
89
- *
90
- * `handler` is the string a route was registered with (`'Actions/…'`), and it
91
- * is absent for an inline function, which has no file to read anything out of.
92
- * The OpenAPI generator needs it to find the action's `validations`: it used to
93
- * guess the path by title-casing the route *name* (`posts.store` →
94
- * `Actions/PostsStoreAction`), which found a schema for the handful of routes
95
- * following that convention and silently described every other endpoint as
96
- * taking no input at all. The registry has known the real answer the whole
97
- * time; it was simply not being reported.
98
- */
99
- export declare function listRegisteredRoutes(): Array<{ method: string, path: string, name?: string, handler?: string, action?: RouterAction, middleware?: string[] }>;
100
- /**
101
- * The merged middleware alias map: the framework defaults, with the
102
- * application's own map on top.
103
- *
104
- * Exported for diagnostics and tests. A copy, so a caller cannot edit the
105
- * cached map out from under the router.
106
- */
107
- export declare function middlewareAliases(): Promise<Record<string, string>>;
108
- /*.ts` as the single middleware registry instead of asking
109
- * the application to define a second set of anonymous page-only functions.
110
- */
111
- export declare function loadMiddlewareHandlers(): Promise<Record<string, MiddlewareHandler>>;
112
- /**
113
- * Clear the middleware cache (useful for hot-reload in development).
114
- *
115
- * `installMiddlewareHotReload()` will wire this up automatically when
116
- * called from the dev server — production should never invoke it.
117
- */
118
- export declare function clearMiddlewareCache(): void;
119
- /**
120
- * Watch `app/Middleware/` and `app/Middleware.ts` and invalidate the
121
- * cached middleware modules whenever a file changes. Intended for the
122
- * dev server only — calling this in production is a no-op (the
123
- * watcher handle is created but never fires anything user code cares
124
- * about). Returns a `disposer()` to stop watching.
125
- *
126
- * Without this hook, editing a middleware file in dev requires a
127
- * full server restart to see the change — the import map caches the
128
- * old version forever.
129
- */
130
- export declare function installMiddlewareHotReload(): () => void;
131
- /**
132
- * Drop every registered route-state mapping.
133
- *
134
- * The registry is module-scoped and lives for the life of the process, which
135
- * is what `listRegisteredRoutes()` and the boot-time validators read. That is
136
- * correct at runtime — routes are registered once at boot — but it means a
137
- * test that registers a route keeps it visible to every later caller in the
138
- * same process, including `assertRouteMiddlewareResolvable()`. A suite that
139
- * deliberately registers an unresolvable alias therefore made an unrelated
140
- * file's `serverResponse()` throw on routes it never declared.
141
- *
142
- * `clearMiddlewareCache()` deliberately does NOT do this: it flushes resolved
143
- * middleware so a hot-reloaded file is re-read, while the routes themselves
144
- * must survive. Clearing the route table is a separate, coarser action.
145
- */
146
- export declare function clearRouteMiddlewareRegistry(): void;
147
- /**
148
- * Resolve every middleware alias referenced by a registered route and
149
- * report the ones that don't load. `csrf` is always checked too — it's
150
- * auto-injected on unsafe methods even when no route lists it.
151
- *
152
- * Resolution is inherently lazy (`.middleware(name)` is a sync chainable
153
- * that just records a string; the alias map and middleware modules load
154
- * via async dynamic import), so a throw at literal registration time is
155
- * impossible. Calling this after all routes are registered — the end of
156
- * `importRoutes()` and the compiled-binary boot in core/server — IS
157
- * effectively registration-time validation. See stacksjs/stacks#1957.
158
- */
159
- export declare function findUnresolvableRouteMiddleware(): Promise<Array<{ alias: string, routes: string[] }>>;
160
- /**
161
- * Throw when any registered route references a middleware alias that
162
- * cannot be resolved. Fail-closed boot validation: a typo'd `auth` alias
163
- * must abort startup loudly, not serve the route unprotected (the
164
- * request-time guard in createMiddlewareHandler 500s as a backstop).
165
- */
166
- export declare function assertRouteMiddlewareResolvable(): Promise<void>;
167
- /**
168
- * Whether this request is asking "would this be accepted?" rather than
169
- * "do this" (stacksjs/stacks#2226).
170
- *
171
- * An Action's `validations:` block was a server-only artifact: nothing could
172
- * read it from a template or a client script, so every form in every app
173
- * retyped the rules in the browser and the two copies drifted. The framework's
174
- * own defaults demonstrated it — the browser refused a 7-character password
175
- * that `POST /register` would have accepted.
176
- *
177
- * Rather than serialise the rules (a `schema.*` chain is a live object with
178
- * no faithful JSON projection), the client asks the real endpoint to run the
179
- * real rules and stops short of the side effect. Same shape as Laravel
180
- * Precognition, and deliberately header-compatible with it.
181
- *
182
- * `?_validate=1` is accepted too: a header cannot be set on a plain form
183
- * submission or a `<script client>` block using a bare fetch shorthand, and
184
- * requiring one would have put this out of reach of the simplest caller.
185
- */
186
- export declare function precognitionRequest(req: EnhancedRequest, knownHeader?: string | null): { only: string[] } | null;
187
- /**
188
- * The "nothing to report" answer to a precognition request. 204 rather than an
189
- * empty 200 so a client cannot mistake it for the action's real result.
190
- *
191
- * `Vary` because the same URL and method now has two different answers
192
- * depending on a request header — without it a shared cache is entitled to
193
- * serve this 204 to a caller that meant to submit.
194
- */
195
- export declare function precognitionSuccess(): Response;
196
- export declare function provideActions(loaders: Record<string, () => Promise<{ default?: unknown }>>): void;
197
- /** Whether a route handler is an action rather than a plain function. */
198
- export declare function isRouterAction(handler: unknown): handler is RouterAction;
199
- /**
200
- * Turn a resolved action into the function the route actually runs.
201
- *
202
- * Split out of the string-resolution path so registering an action by import
203
- * (`createTypedRouter().get('/x', ShowAction)`) and registering it by name
204
- * (`route.get('/x', 'Actions/ShowAction')`) share one runtime path. The two
205
- * forms differ only in when the module is loaded and in what the compiler can
206
- * see; everything below - validation, precognition, `authorize`, `before`,
207
- * result formatting, error reporting - is the same code for both.
208
- *
209
- * `handlerKey` identifies the action for the CSRF skip cache and for error
210
- * labels. It is the handler string when there is one, and the route key
211
- * otherwise.
212
- */
213
- export declare function wrapAction(action: RouterAction, handlerKey: string): RouteHandlerFn;
214
- declare function createValidationFieldLabel(field: string): { label: string, decorate: (message: string) => string };
215
- export declare function validateActionInput(req: EnhancedRequest, validations: ActionValidations): Promise<ValidationResult>;
216
- export declare function stream(source: ReadableStream | AsyncIterable<string | Uint8Array>, options?: StreamOptions): Response;
217
- /** Test / hot-reload seam: forget the resolved module. */
218
- export declare function clearCsrfModuleCache(): void;
219
- export declare function enhanceRequest(req: EnhancedRequest, initializeRequestId?: boolean): EnhancedRequest;
220
- /**
221
- * Create a Stacks-enhanced router
222
- */
223
- export declare function createStacksRouter(config?: StacksRouterConfig): StacksRouterInstance;
224
- /**
225
- * Tell the file-based view renderer where this application keeps its templates.
226
- *
227
- * Two different programs render `.stx` in a Stacks app and they were not
228
- * agreeing. `buddy dev` and the production server go through
229
- * `bun-plugin-stx`'s own `serve()`, which is handed the components, layouts and
230
- * partials directories explicitly. `route.serve()` goes through bun-router's
231
- * file routing, which was handed nothing - so its components directory fell
232
- * back to `<viewsDir>/components`, and `resources/components`, where every
233
- * Stacks app actually keeps them, was never looked in.
234
- *
235
- * The failure is silent in the direction that hides bugs. The page still
236
- * answers 200; the component is replaced inline with
237
- * `[Error loading component: ENOENT ...]`. So a test that boots the router and
238
- * asserts on rendered HTML cannot see any component at all, and reads as though
239
- * the feature under test were missing rather than the harness.
240
- *
241
- * Only fills in what has not been set: an application that called
242
- * `route.bunRouter.views(...)` itself has said something more specific, and
243
- * this must not overwrite it.
244
- *
245
- * **It deliberately does not set `viewsPath`.** Naming one switches on
246
- * file-based route discovery, which walks the whole views tree - so an
247
- * application that never asked for file routing would start doing it because a
248
- * directory happened to exist. Where the views are is already decided
249
- * elsewhere; the only thing missing was where the *components* are.
250
- */
251
- export declare function configureViewDirectories(bunRouter: Router): void;
252
- /*.ts` works.
253
- *
254
- * The two functions are coupled and the coupling is bun-router's, not ours:
255
- * `serve()` calls {@link configureViewDirectories} after this, and that only
256
- * backs off because `disableFileRouting()` happens to leave a non-empty
257
- * `_fileRoutingConfig` behind. Were that flag ever to move to a field of its
258
- * own, `configureViewDirectories` would overwrite the config and re-mount every
259
- * template. `api-view-routing.test.ts` drives both, in that order, so the
260
- * upgrade that changes it fails a test rather than quietly restoring the site
261
- * to the API port.
262
- *
263
- * @returns whether file routing was switched off by this call.
264
- */
265
- export declare function disableViewRouting(bunRouter: Router): boolean;
266
- /**
267
- * Handle a server request through the router
268
- * This is the main entry point for the Stacks server
269
- */
270
- export declare function serverResponse(request: Request, _body?: string): Promise<Response>;
271
- // Export serve function that uses the default router
272
- export declare function serve(options?: ServerOptions): Promise<Server<unknown>>;
273
35
  declare const CSRF_DEFAULT: 0;
274
36
  declare const CSRF_SKIPPED: 1;
275
37
  declare const CSRF_REQUIRED: 2;
276
- export declare const route: StacksRouterInstance;
277
38
  /**
278
39
  * Warn (once per process) when more than one @stacksjs/router module has loaded
279
40
  * (stacksjs/stacks#1975 / #1982). Routing still works — the route table and
@@ -332,11 +93,6 @@ export declare interface StacksRouterConfig {
332
93
  csrf?: boolean
333
94
  requestContext?: boolean
334
95
  }
335
- declare interface GroupOptions {
336
- prefix?: string
337
- middleware?: MiddlewareReference | MiddlewareReference[]
338
- apiResponse?: boolean
339
- }
340
96
  /** The file-name half each CRUD action is composed from. */
341
97
  declare interface ResourceKindOf {
342
98
  index: 'Index'
@@ -356,139 +112,6 @@ export declare interface ChainableRoute {
356
112
  requireCsrf: () => ChainableRoute
357
113
  rateLimit: (max: number, window: 'second' | 'minute' | 'hour' | 'day' | number) => ChainableRoute
358
114
  }
359
- /** A route {@link withRouteAdmission} declined to register, and why. */
360
- export declare interface WithheldRoute {
361
- method: string
362
- path: string
363
- handler: string
364
- reason: string
365
- }
366
- /** One `route.redirect()` / `route.permanentRedirect()` declaration, by its full path. */
367
- export declare interface RedirectRoute {
368
- path: string
369
- to: string
370
- status: RedirectStatus
371
- }
372
- /** Represents a middleware module with a handle method */
373
- declare interface MiddlewareHandler {
374
- handle: (req: EnhancedRequest) => Promise<void> | void
375
- priority?: number
376
- }
377
- /**
378
- * Anything the router is willing to treat as an action.
379
- *
380
- * Structural rather than `instanceof Action`, because an action can also be a
381
- * plain object with a `handle()` - the framework's own defaults include both
382
- * shapes - and because a duplicated install would make an `instanceof` check
383
- * reject a perfectly good action from the other copy of the package.
384
- */
385
- export declare interface RouterAction {
386
- handle: (req: any) => unknown
387
- validations?: ActionValidations
388
- authorize?: (req: any) => unknown
389
- before?: (req: any) => unknown
390
- skipCsrf?: boolean
391
- csrf?: boolean
392
- apiResponse?: boolean
393
- model?: unknown
394
- modelDefinition?: unknown
395
- name?: string
396
- responses?: unknown
397
- responseHeaders?: unknown
398
- requestHeaders?: unknown
399
- }
400
- /**
401
- * Helper for streaming responses — wraps a `ReadableStream` or async
402
- * generator with the right headers for the chosen content type.
403
- *
404
- * Common shapes:
405
- *
406
- * ```ts
407
- * // Server-Sent Events
408
- * return stream(async function* () {
409
- * for await (const evt of source) yield `data: ${JSON.stringify(evt)}\n\n`
410
- * }, { type: 'sse' })
411
- *
412
- * // Chunked JSON (NDJSON) — one JSON object per line
413
- * return stream(async function* () {
414
- * for await (const row of rows) yield `${JSON.stringify(row)}\n`
415
- * }, { type: 'ndjson' })
416
- *
417
- * // Raw bytes — caller supplies a ReadableStream of Uint8Array chunks
418
- * return stream(myReadable, { contentType: 'application/octet-stream' })
419
- * ```
420
- *
421
- * The wrapper sets `Cache-Control: no-cache` and `Connection: keep-alive`
422
- * for SSE — the two headers a sane proxy / browser pair won't ignore — and
423
- * leaves backpressure / cancellation to the underlying stream.
424
- *
425
- * See stacksjs/stacks#1870 R-4.
426
- */
427
- export declare interface StreamOptions {
428
- type?: 'sse' | 'ndjson'
429
- contentType?: string
430
- headers?: HeadersInit
431
- status?: number
432
- }
433
- export declare interface StacksRouterInstance {
434
- bunRouter: Router
435
- routes: Route[]
436
- staticResponse: (
437
- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS',
438
- path: string,
439
- response: Response,
440
- ) => StacksRouterInstance
441
- get: {
442
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
443
- (path: string, handler: StacksHandler): ChainableRoute
444
- }
445
- post: {
446
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
447
- (path: string, handler: StacksHandler): ChainableRoute
448
- }
449
- put: {
450
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
451
- (path: string, handler: StacksHandler): ChainableRoute
452
- }
453
- patch: {
454
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
455
- (path: string, handler: StacksHandler): ChainableRoute
456
- }
457
- delete: {
458
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
459
- (path: string, handler: StacksHandler): ChainableRoute
460
- }
461
- options: {
462
- <TPath extends string>(path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
463
- (path: string, handler: StacksHandler): ChainableRoute
464
- }
465
- redirect: (from: string, to: string, status?: RedirectStatus) => ChainableRoute
466
- permanentRedirect: (from: string, to: string) => ChainableRoute
467
- group: (options: GroupOptions, callback: () => void | Promise<void>) => StacksRouterInstance | Promise<StacksRouterInstance>
468
- resource: <TBase extends string, TOnly extends ResourceAction = never, TExcept extends ResourceAction = never>(
469
- name: string,
470
- handler: TBase & ResourceBaseCheck<TBase, ActiveResourceActions<TOnly, TExcept>>,
471
- options?: {
472
- only?: readonly TOnly[]
473
- except?: readonly TExcept[]
474
- middleware?: MiddlewareReference | MiddlewareReference[]
475
- },
476
- ) => StacksRouterInstance
477
- match: {
478
- <TPath extends string>(methods: string[], path: TPath, handler: TypedInlineRouteHandler<TPath>): ChainableRoute
479
- (methods: string[], path: string, handler: StacksHandler): ChainableRoute
480
- }
481
- health: () => StacksRouterInstance
482
- use: (middleware: ActionHandler | BunMiddlewareHandler) => StacksRouterInstance
483
- register: (routePath: string, options?: { prefix?: string, middleware?: MiddlewareReference | MiddlewareReference[] }) => Promise<StacksRouterInstance>
484
- booting: (name: string, run: () => void | Promise<void>) => StacksRouterInstance
485
- stopping: (name: string, run: () => void | Promise<void>) => StacksRouterInstance
486
- serve: (options?: ServerOptions) => Promise<Server<unknown>>
487
- handleRequest: (req: Request) => Promise<Response>
488
- getAllowedMethods: (pathname: string, domain?: string) => string[]
489
- importRoutes: () => Promise<void>
490
- loadDiscoveredRoutes: () => Promise<void>
491
- }
492
115
  declare type QueryTracker = typeof import('./query-tracking').trackQuery;
493
116
  declare type ErrorHandlerModule = typeof import('./error-handler');
494
117
  declare type RouteHandlerFn = (_req: EnhancedRequest) => Response | Promise<Response>;
@@ -559,110 +182,4 @@ declare type ResourceBaseCheck<TBase extends string, TActive extends ResourceAct
559
182
  ? unknown
560
183
  : { 'these actions do not exist': MissingResourceActions<TBase, TActive> }
561
184
  declare type RouteCsrfMode = typeof CSRF_DEFAULT | typeof CSRF_SKIPPED | typeof CSRF_REQUIRED;
562
- /**
563
- * Decides whether a route bound to a string handler (`'Actions/…'`) may be
564
- * registered. Returns the reason to withhold it, or undefined to register it.
565
- */
566
- export type RouteAdmission = (handler: string) => string | undefined;
567
- declare type CorsHeaderApplier = (req: Request, res: Response, cfg?: unknown) => Response;
568
- declare type CompressionApplier = (req: Request, res: Response, bodySizeUpperBound?: number) => Promise<Response>;
569
- /** The statuses `route.redirect()` answers with, as Laravel's `Route::redirect` takes them. */
570
- export type RedirectStatus = 301 | 302 | 303 | 307 | 308;
571
- /**
572
- * Generate a full URL for a named route, like Laravel's route() helper.
573
- *
574
- * Validates path parameters at call time so a typo'd argument
575
- * (`url('user.post', { userId: 1 })` against `/users/{id}`) throws
576
- * immediately with a list of expected names instead of silently
577
- * producing a URL with `{id}` left literal in the path.
578
- *
579
- * @example
580
- * ```typescript
581
- * // Define a named route
582
- * route.get('/api/email/unsubscribe', 'Actions/UnsubscribeAction').name('email.unsubscribe')
583
- *
584
- * // Generate URL
585
- * url('email.unsubscribe', { token: 'abc-123' })
586
- * // → https://stacksjs.com/api/email/unsubscribe?token=abc-123
587
- *
588
- * // With path parameters
589
- * route.get('/users/{id}/posts/{postId}', handler).name('user.post')
590
- * url('user.post', { id: 42, postId: 7 })
591
- * // → https://stacksjs.com/users/42/posts/7
592
- * ```
593
- */
594
- /**
595
- * The params a named route needs, plus anything else that becomes query string.
596
- *
597
- * The required half comes from the path the name resolves to, so
598
- * `url('user.post', { id: 42 })` against `/users/{id}/posts/{postId}` stops
599
- * compiling instead of throwing at call time. Extra keys stay allowed: the
600
- * implementation appends whatever it did not consume as a query string, which
601
- * is what `url('email.unsubscribe', { token })` relies on.
602
- */
603
- export type UrlParams<TName extends string> = { [K in keyof ExtractRouteParams<PathForRouteName<TName>>]: string | number }
604
- & Record<string, string | number>;
605
- /** The keys of `T` that are not optional. */
606
- declare type RequiredParamKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? never : K }[keyof T];
607
- /**
608
- * Whether `url()` must be given a second argument.
609
- *
610
- * Keyed on REQUIRED params: a path whose only placeholder is optional is
611
- * reachable with nothing at all, and demanding an empty object for it would be
612
- * the type getting in the way of the truth.
613
- */
614
- declare type RequiresUrlParams<TName extends string> = [RequiredParamKeys<ExtractRouteParams<PathForRouteName<TName>>>] extends [never] ? false : true;
615
- /**
616
- * Run an action's declarative `validations:` against the request.
617
- *
618
- * The action path uses this synchronous core because input collection and the
619
- * validator contract are synchronous. The exported wrapper below stays
620
- * Promise-based for compatibility with callers that chain or await it.
621
- */
622
- declare type ActionValidationEntry = [string, ActionValidations[string], ReturnType<typeof createValidationFieldLabel>?];
623
- /**
624
- * Per-request read-routing context.
625
- *
626
- * The database package tracks writes per async context so that a request
627
- * which reads back what it just wrote is never served from a read replica
628
- * (replication is asynchronous, so the row may not be there yet). That
629
- * tracking only works if something establishes the context at the request
630
- * boundary — without this, `contextHasWritten()` has no store to consult,
631
- * always reports false, and every read routes to a replica including the
632
- * one immediately following a write. The safety rule would be dead code.
633
- *
634
- * Loaded lazily rather than imported: `@stacksjs/database` already depends
635
- * on `@stacksjs/router`, so a static import here would close a package
636
- * cycle. The dynamic import is resolved once and cached, and the fallback
637
- * is a plain pass-through so a build without the database package (or an
638
- * older one) still serves requests.
639
- */
640
- declare type ContextDispatcher = <T, A>(fn: (arg: A) => T, arg: A) => T;
641
- declare type ContextRunner = <T>(fn: () => T) => T;
642
- declare type NativeRouteHandler = (request: Request) => Response | Promise<Response>;
643
- declare type NativeRouteTable = Record<string, Record<string, NativeRouteHandler>>;
644
- declare type NativeResponseFinalizer = (response: Response, request: Request) => Response | Promise<Response>;
645
- /**
646
- * FIFO-bounded Map. Wraps `Map` with a hard size cap; on overflow,
647
- * the oldest entry (Map insertion order) is evicted. Used for the
648
- * router's small framework-internal caches whose size is normally
649
- * bounded by action count, but which had no upper limit before —
650
- * tests that instantiate many short-lived routers would leak entries
651
- * across `createStacksRouter()` calls (stacksjs/stacks#1863 T-8).
652
- *
653
- * Insertion-order LRU is appropriate here because the access pattern
654
- * is "set once at action-load time, then many reads" — refreshing on
655
- * get would buy nothing since reads dominate.
656
- */
657
- declare class BoundedMap<K, V> {
658
- private map;
659
- private max;
660
- constructor(max: number);
661
- get(key: K): V | undefined;
662
- has(key: K): boolean;
663
- set(key: K, value: V): this;
664
- delete(key: K): boolean;
665
- clear(): void;
666
- get size(): number;
667
- }
668
185
  export {};
@@ -1,5 +1,5 @@
1
- import type { StacksRouterInstance } from './stacks-router';
2
1
  import type { TypedRouter } from '@stacksjs/bun-router';
2
+ import type { StacksRouterInstance } from './stacks-router';
3
3
  /**
4
4
  * Build a typed route group on top of a Stacks router.
5
5
  *
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/router",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.529",
5
+ "version": "0.75.535",
6
6
  "description": "The Stacks framework router.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -68,27 +68,27 @@
68
68
  },
69
69
  "dependencies": {
70
70
  "@stacksjs/bun-router": "^0.1.24",
71
- "@stacksjs/cache": "0.75.529",
72
- "@stacksjs/collections": "0.75.529",
73
- "@stacksjs/config": "0.75.529",
74
- "@stacksjs/error-handling": "0.75.529",
75
- "@stacksjs/logging": "0.75.529",
76
- "@stacksjs/pagination": "0.75.529",
77
- "@stacksjs/path": "0.75.529",
78
- "@stacksjs/security": "0.75.529",
79
- "@stacksjs/storage": "0.75.529",
71
+ "@stacksjs/cache": "0.75.535",
72
+ "@stacksjs/collections": "0.75.535",
73
+ "@stacksjs/config": "0.75.535",
74
+ "@stacksjs/error-handling": "0.75.535",
75
+ "@stacksjs/logging": "0.75.535",
76
+ "@stacksjs/pagination": "0.75.535",
77
+ "@stacksjs/path": "0.75.535",
78
+ "@stacksjs/security": "0.75.535",
79
+ "@stacksjs/storage": "0.75.535",
80
80
  "ts-rate-limiter": "^0.4.10"
81
81
  },
82
82
  "devDependencies": {
83
- "@stacksjs/actions": "0.75.529",
84
- "@stacksjs/types": "0.75.529",
83
+ "@stacksjs/actions": "0.75.535",
84
+ "@stacksjs/types": "0.75.535",
85
85
  "better-dx": "^0.2.24"
86
86
  },
87
87
  "peerDependencies": {
88
- "@stacksjs/api": "0.75.529",
89
- "@stacksjs/auth": "0.75.529",
90
- "@stacksjs/database": "0.75.529",
91
- "@stacksjs/validation": "0.75.529"
88
+ "@stacksjs/api": "0.75.535",
89
+ "@stacksjs/auth": "0.75.535",
90
+ "@stacksjs/database": "0.75.535",
91
+ "@stacksjs/validation": "0.75.535"
92
92
  },
93
93
  "peerDependenciesMeta": {
94
94
  "@stacksjs/api": {