rossa 0.0.6 → 0.1.1

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
@@ -1,4 +1,6 @@
1
1
  import { Server, SocketAddress, BunFile, ServerWebSocket, WebSocketHandler, SQL } from 'bun';
2
+ import { McpServer, McpRequestContext } from '@modelcontextprotocol/server';
3
+ export { McpRequestContext, McpServer } from '@modelcontextprotocol/server';
2
4
 
3
5
  declare class req {
4
6
  readonly request: Request;
@@ -315,7 +317,14 @@ declare class StaticFileServer {
315
317
  private readonly CACHE_TTL;
316
318
  constructor(resolvedAssetRootPath: string, additionalExtensions?: string[]);
317
319
  isFile(path: string): boolean;
318
- serve(req: req, res: res): Promise<Response>;
320
+ /**
321
+ * Serves the request from this server's root.
322
+ *
323
+ * @param lookupPath - Optional already-decoded path to resolve instead of the
324
+ * request pathname. Scoped mounts use it to serve a prefix-stripped path;
325
+ * when omitted the request URL is decoded exactly as before.
326
+ */
327
+ serve(req: req, res: res, lookupPath?: string): Promise<Response>;
319
328
  }
320
329
 
321
330
  type HeaderObject = Record<string, string>;
@@ -737,6 +746,7 @@ type GuardReturnType = {
737
746
  declare function createGuard<TOptions = void, ExtraCfg = Record<string, unknown>>(handler: GuardFactoryHandler<TOptions, ExtraCfg>, defaultConfig?: GuardConfig): (options?: TOptions, overrideConfig?: BaseConfig) => GuardReturnType;
738
747
 
739
748
  type Class = new (...args: any[]) => any;
749
+ type RouteHandler = (ctx: ctx) => Promise<Response> | Response;
740
750
  interface WssBaseController {
741
751
  open?(ws: any): void;
742
752
  message(ws: any, message: string | Uint8Array): void;
@@ -768,12 +778,23 @@ declare class RouterManager {
768
778
  wssRoutes: WssRouteConfig[];
769
779
  protected globalGuards: any[];
770
780
  private registeredSignatures;
781
+ private programmaticRoutes;
771
782
  constructor(globalBasePath?: string);
772
783
  use(...guards: GuardReturnType[]): void;
784
+ private fullRoutePath;
773
785
  private compiler;
774
786
  private checkSignature;
775
787
  registerWSS(...ControllerClass: (typeof Websocket<{}>)[]): void;
776
788
  register(...ControllerClass: (typeof Methods)[]): void;
789
+ /**
790
+ * Registers a programmatic HTTP route without a decorated controller class.
791
+ * Used by framework features such as MCP endpoints; a matching programmatic
792
+ * route can be replaced, while a decorated HTTP route at the same path is a
793
+ * collision.
794
+ */
795
+ protected registerHandlerRoute(path: string, handlers: Partial<Record<methodsKeys, RouteHandler>>, options?: {
796
+ replace?: boolean;
797
+ }): void;
777
798
  protected matchWSS(url: string): Partial<WssRouteConfig & {
778
799
  params: HttpRouteMatch["params"];
779
800
  }>;
@@ -783,6 +804,51 @@ declare class RouterManager {
783
804
  getPaths(): string[];
784
805
  }
785
806
 
807
+ /**
808
+ * Base class for decorator-driven MCP endpoints.
809
+ *
810
+ * The framework creates a fresh `McpServer` for each request (named after the
811
+ * controller class) and calls {@link McpController.build} before serving it.
812
+ * Combine it with the `@mcp("/path")` decorator and register it with
813
+ * `app.registerMCP(MyController)`.
814
+ */
815
+ declare abstract class McpController {
816
+ /**
817
+ * Builds the MCP server: register tools, resources, and prompts here.
818
+ * Runs once per request via the SDK factory, so async setup is supported.
819
+ */
820
+ abstract build(server: McpServer): void | Promise<void>;
821
+ }
822
+
823
+ /**
824
+ * Produces a fresh MCP server for one HTTP exchange. Under the SDK's v2
825
+ * handler the factory runs once per request, so per-request tools are possible.
826
+ * Zero-argument factories remain assignable.
827
+ */
828
+ type McpServerFactory = (context: McpRequestContext) => McpServer | Promise<McpServer>;
829
+ interface McpOptions {
830
+ /**
831
+ * Allowed browser `Origin` values. Entries may be full origins
832
+ * (`https://app.example.com`), hostnames (`app.example.com`), or the SDK's
833
+ * extension form (`moz-extension://*`). Full origins are matched exactly
834
+ * (scheme, host, and port); hostnames are matched port-agnostically.
835
+ *
836
+ * Requests without an `Origin` header always pass, as non-browser MCP
837
+ * clients do not send one. When omitted, Origin validation is disabled;
838
+ * production apps should set this or use the CORS and IP guards.
839
+ */
840
+ origin?: string | string[];
841
+ }
842
+
843
+ /**
844
+ * Marks an {@link McpController} subclass as an MCP endpoint.
845
+ *
846
+ * @param path - MCP endpoint path, resolved under the app's `basePath`.
847
+ * @param options - Optional MCP endpoint settings such as allowed origins.
848
+ * @returns A class decorator, used as `@mcp("/mcp")`.
849
+ */
850
+ declare function mcp(path?: string, options?: McpOptions): <TTarget extends abstract new (...args: any[]) => McpController>(target: TTarget, context: ClassDecoratorContext<any>) => void | TTarget;
851
+
786
852
  interface dev {
787
853
  path?: string;
788
854
  hostname?: string;
@@ -813,6 +879,39 @@ declare class Rossa extends RouterManager {
813
879
  fileServer: StaticFileServer;
814
880
  private clientRoot;
815
881
  constructor(options?: RossaOptions);
882
+ /**
883
+ * Mounts an MCP server over Streamable HTTP.
884
+ *
885
+ * Use the decorator idiom for controllers:
886
+ * ```ts
887
+ * @mcp("/mcp")
888
+ * class MyMcp extends McpController {
889
+ * build(server: McpServer) { ... }
890
+ * }
891
+ * app.registerMCP(MyMcp);
892
+ * ```
893
+ *
894
+ * A raw per-request factory remains available when an explicit path is
895
+ * supplied: `app.registerMCP("/mcp", () => new McpServer(...))`.
896
+ *
897
+ * Decorator-provided options are merged with per-call options; a per-call
898
+ * `origin` wins. Global guards added with `use(...)` run before the MCP
899
+ * handler. Registering the same path again replaces the previous MCP route.
900
+ *
901
+ * @param controller - A decorated `McpController` class or instance.
902
+ * @param options - Optional per-call MCP settings.
903
+ */
904
+ registerMCP(controller: McpController, options?: McpOptions): void;
905
+ registerMCP(controller: new () => McpController, options?: McpOptions): void;
906
+ /**
907
+ * Mounts a raw MCP factory at an explicit path.
908
+ *
909
+ * @param path - MCP endpoint path, for example `/mcp`.
910
+ * @param factory - Produces the `McpServer` served for each request.
911
+ * @param options - Optional allowed browser origins.
912
+ */
913
+ registerMCP(path: string, factory: McpServerFactory, options?: McpOptions): void;
914
+ private mountMcp;
816
915
  private get getClientRoot();
817
916
  private pipeline;
818
917
  private processRouter;
@@ -878,28 +977,28 @@ interface DbDialectAdapter {
878
977
  buildColumnType(column: Column): string;
879
978
  normalizeOperator(operator: string): string;
880
979
  version(db: SQL): Promise<string>;
881
- createTable(db: SQL, schema: Schema<any>): Promise<void>;
882
- getColumns(db: SQL, schema: Schema<any>): Promise<string[]>;
883
- addColumn(db: SQL, schema: Schema<any>, name: string, type: string): Promise<void>;
884
- dropColumn(db: SQL, schema: Schema<any>, name: string): Promise<void>;
885
- upsert<T extends Record<string, any>>(db: SQL, schema: Schema<T>, data: T, conflictColumn: keyof T): Promise<T | undefined>;
980
+ createTable(db: SQL, schema: DbSchema<any>): Promise<void>;
981
+ getColumns(db: SQL, schema: DbSchema<any>): Promise<string[]>;
982
+ addColumn(db: SQL, schema: DbSchema<any>, name: string, type: string): Promise<void>;
983
+ dropColumn(db: SQL, schema: DbSchema<any>, name: string): Promise<void>;
984
+ upsert<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>, data: T, conflictColumn: keyof T): Promise<T | undefined>;
886
985
  listTables(db: SQL): Promise<string[]>;
887
- dropTable(db: SQL, schema: Schema<any>): Promise<void>;
888
- truncateTable(db: SQL, schema: Schema<any>): Promise<void>;
889
- getTableStats(db: SQL, schema: Schema<any>): Promise<TableStats>;
890
- getTableIndices(db: SQL, schema: Schema<any>): Promise<any[]>;
891
- getTableSchema(db: SQL, schema: Schema<any>): Promise<any[]>;
892
- getTableData(db: SQL, schema: Schema<any>, limit: number, offset: number): Promise<any[]>;
893
- optimize(db: SQL, schema: Schema<any>): Promise<void>;
986
+ dropTable(db: SQL, schema: DbSchema<any>): Promise<void>;
987
+ truncateTable(db: SQL, schema: DbSchema<any>): Promise<void>;
988
+ getTableStats(db: SQL, schema: DbSchema<any>): Promise<TableStats>;
989
+ getTableIndices(db: SQL, schema: DbSchema<any>): Promise<any[]>;
990
+ getTableSchema(db: SQL, schema: DbSchema<any>): Promise<any[]>;
991
+ getTableData(db: SQL, schema: DbSchema<any>, limit: number, offset: number): Promise<any[]>;
992
+ optimize(db: SQL, schema: DbSchema<any>): Promise<void>;
894
993
  }
895
994
 
896
- declare class Schema<T extends Record<string, any>> {
995
+ declare class DbSchema<T extends Record<string, any>> {
897
996
  readonly table: string;
898
997
  private readonly definitions;
899
998
  readonly dialect: DbDialectAdapter;
900
999
  constructor(table: string, definitions: Record<keyof T, Column>, dialect: DbDialectAdapter);
901
1000
  entries(): Array<[string, Column]>;
902
- withDialect(dialect: DbDialectAdapter): Schema<T>;
1001
+ withDialect(dialect: DbDialectAdapter): DbSchema<T>;
903
1002
  createSQL(adapter?: DbDialectAdapter): string;
904
1003
  columnDefinitions(adapter?: DbDialectAdapter): Record<string, string>;
905
1004
  get columns(): {
@@ -910,8 +1009,8 @@ declare class Schema<T extends Record<string, any>> {
910
1009
  /** Shared inspection API; SQL-specific operations live in the dialect adapter. */
911
1010
  declare class DbInspector<T extends Record<string, any>> {
912
1011
  private readonly db;
913
- readonly schema: Schema<T>;
914
- constructor(db: SQL, schema: Schema<T>);
1012
+ readonly schema: DbSchema<T>;
1013
+ constructor(db: SQL, schema: DbSchema<T>);
915
1014
  listTables(): Promise<string[]>;
916
1015
  dropTable(): Promise<void>;
917
1016
  truncateTable(): Promise<void>;
@@ -920,8 +1019,8 @@ declare class DbInspector<T extends Record<string, any>> {
920
1019
  getTableSchema(): Promise<any[]>;
921
1020
  getTableData(limit?: number, offset?: number): Promise<any[]>;
922
1021
  optimize(): Promise<void>;
923
- static sqlite<T extends Record<string, any>>(db: SQL, schema: Schema<T>): DbInspector<T>;
924
- static postgres<T extends Record<string, any>>(db: SQL, schema: Schema<T>): DbInspector<T>;
1022
+ static sqlite<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
1023
+ static postgres<T extends Record<string, any>>(db: SQL, schema: DbSchema<T>): DbInspector<T>;
925
1024
  }
926
1025
 
927
1026
  type Where<T> = {
@@ -933,8 +1032,8 @@ type Where<T> = {
933
1032
  /** Shared CRUD repository. Dialect-specific statements are delegated to its adapter. */
934
1033
  declare class DbRepository<T extends Record<string, any>> {
935
1034
  private readonly db;
936
- readonly schema: Schema<T>;
937
- constructor(db: SQL, schema: Schema<T>);
1035
+ readonly schema: DbSchema<T>;
1036
+ constructor(db: SQL, schema: DbSchema<T>);
938
1037
  private get dialect();
939
1038
  get inspect(): DbInspector<T>;
940
1039
  withContext(context: SQL): DbRepository<T>;
@@ -1087,6 +1186,28 @@ interface CsrfOptions {
1087
1186
  */
1088
1187
  declare const csrf: (options?: CsrfOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1089
1188
 
1189
+ type DenyConfig = ErrorConfig & {
1190
+ /** When provided, the guard denies only requests where the predicate returns true; otherwise it continues. */
1191
+ when?: (ctx: ctx) => boolean | Promise<boolean>;
1192
+ };
1193
+ /**
1194
+ * Rejects requests with an HTTP error, optionally only when a predicate matches.
1195
+ *
1196
+ * Without `when` every request is denied, which is useful for maintenance
1197
+ * windows or permanently closing a route. With `when`, non-matching requests
1198
+ * continue through the remaining guards and the handler.
1199
+ *
1200
+ * ```ts
1201
+ * @use(deny()) // always 403
1202
+ * @use(deny({ code: 503, message: "Under maintenance" })) // custom status
1203
+ * @use(deny({ when: (ctx) => ctx.req.method === "TRACE" })) // conditional
1204
+ * ```
1205
+ *
1206
+ * @param options - Optional status, message, headers, redirect, and predicate.
1207
+ * @returns A guard factory that denies matching requests and continues otherwise.
1208
+ */
1209
+ declare const deny: (options?: DenyConfig | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1210
+
1090
1211
  interface ErrorGuardOptions {
1091
1212
  /** Log caught errors. Defaults to false. */
1092
1213
  logErrors?: boolean;
@@ -1127,26 +1248,384 @@ type IpOptions = {
1127
1248
  */
1128
1249
  declare const ipFilter: (options?: IpOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1129
1250
 
1130
- declare class SchemaBuilder<T extends Record<string, any>> {
1131
- private schema;
1132
- private rules;
1133
- private defaults;
1134
- string(key: keyof T, defaultValue?: T[keyof T]): this;
1135
- number(key: keyof T, defaultValue?: T[keyof T]): this;
1136
- boolean(key: keyof T, defaultValue?: T[keyof T]): this;
1137
- min(key: keyof T, val: number): this;
1138
- max(key: keyof T, val: number): this;
1139
- email(key: keyof T): this;
1140
- private addRule;
1141
- private noBool;
1142
- private noKey;
1143
- validate(data: any): {
1144
- errors: string[];
1145
- processedData: any;
1146
- };
1147
- private validateObject;
1251
+ /**
1252
+ * TypeScript types for the
1253
+ * {@link https://standardschema.dev/ | Standard Schema} and
1254
+ * Standard JSON Schema interfaces.
1255
+ *
1256
+ * They mirror the vendor-neutral contracts consumed by the MCP SDK. Keeping
1257
+ * local copies avoids a runtime dependency on the SDK from the schema library.
1258
+ */
1259
+ /** A single property key or named path segment in an issue path. */
1260
+ type StandardPathSegment = PropertyKey | {
1261
+ readonly key: PropertyKey;
1262
+ };
1263
+ /** One validation problem in the Standard Schema shape. */
1264
+ interface StandardIssue {
1265
+ /** Human-readable explanation of the failure. */
1266
+ readonly message: string;
1267
+ /** Location of the failing value inside nested data. */
1268
+ readonly path?: ReadonlyArray<StandardPathSegment> | undefined;
1269
+ }
1270
+ /** Successful validation result. */
1271
+ interface StandardSuccessResult<Output> {
1272
+ /** Parsed and normalized output value. */
1273
+ readonly value: Output;
1274
+ readonly issues?: undefined;
1275
+ }
1276
+ /** Failed validation result. */
1277
+ interface StandardFailureResult {
1278
+ /** Every problem found while validating the input. */
1279
+ readonly issues: ReadonlyArray<StandardIssue>;
1280
+ }
1281
+ /** Discriminated union returned by `~standard.validate`. */
1282
+ type StandardValidateResult<Output> = StandardSuccessResult<Output> | StandardFailureResult;
1283
+ /** Options passed to `~standard.validate`. */
1284
+ interface StandardValidateOptions {
1285
+ /** Extra options for the producing library; unused by Rossa schemas. */
1286
+ readonly libraryOptions?: Record<string, unknown> | undefined;
1287
+ }
1288
+ /** JSON Schema dialect requested by a consumer. */
1289
+ type StandardJSONSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | (object & string);
1290
+ /** Options passed to the `~standard.jsonSchema` converters. */
1291
+ interface StandardJSONSchemaOptions {
1292
+ /** Target dialect. Rossa emits the same subset for every target. */
1293
+ readonly target?: StandardJSONSchemaTarget | undefined;
1294
+ /** Extra options for the producing library; unused by Rossa schemas. */
1295
+ readonly libraryOptions?: Record<string, unknown> | undefined;
1296
+ }
1297
+ /** Converters that advertise a schema's wire shape as JSON Schema. */
1298
+ interface StandardJSONSchemaConverter {
1299
+ /** JSON Schema describing accepted input values. */
1300
+ readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
1301
+ /** JSON Schema describing produced output values. */
1302
+ readonly output: (options: StandardJSONSchemaOptions) => Record<string, unknown>;
1303
+ }
1304
+ /** Phantom input/output type pair exposed through `~standard.types`. */
1305
+ interface StandardTypes<Input = unknown, Output = Input> {
1306
+ readonly input: Input;
1307
+ readonly output: Output;
1308
+ }
1309
+ /** Properties attached to every schema under the `~standard` key. */
1310
+ interface StandardSchemaProps<Input = unknown, Output = Input> {
1311
+ readonly version: 1;
1312
+ readonly vendor: string;
1313
+ readonly types?: StandardTypes<Input, Output> | undefined;
1314
+ readonly validate: (value: unknown, options?: StandardValidateOptions | undefined) => StandardValidateResult<Output>;
1315
+ readonly jsonSchema: StandardJSONSchemaConverter;
1316
+ }
1317
+ /** Any value implementing the Standard Schema contract. */
1318
+ interface StandardSchema<Input = unknown, Output = Input> {
1319
+ readonly "~standard": StandardSchemaProps<Input, Output>;
1320
+ }
1321
+
1322
+ /**
1323
+ * A single validation problem found while parsing a value.
1324
+ *
1325
+ * `path` identifies the failing location in nested data (for example
1326
+ * `["address", "city"]` or `["tags", 0]`), while `message` is a human-friendly
1327
+ * explanation written for API consumers.
1328
+ */
1329
+ type Issue = {
1330
+ path: (string | number)[];
1331
+ message: string;
1332
+ };
1333
+ /** Result of a successful {@link Schema.safeParse} call. */
1334
+ type SafeParseSuccess<T> = {
1335
+ success: true;
1336
+ data: T;
1337
+ };
1338
+ /** Result of a failed {@link Schema.safeParse} call. */
1339
+ type SafeParseFailure = {
1340
+ success: false;
1341
+ error: SchemaError;
1342
+ };
1343
+ /** Discriminated union returned by {@link Schema.safeParse}. */
1344
+ type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseFailure;
1345
+ /**
1346
+ * Error thrown by {@link Schema.parse} when validation fails.
1347
+ *
1348
+ * Inspect `issues` for structured, path-aware details, or read `message` for a
1349
+ * short joined summary.
1350
+ */
1351
+ declare class SchemaError extends Error {
1352
+ /** Structured validation problems, in the order they were discovered. */
1353
+ readonly issues: Issue[];
1354
+ constructor(issues: Issue[]);
1355
+ }
1356
+ /**
1357
+ * Any schema, regardless of its output type. Useful for guard options and for
1358
+ * accepting schemas whose exact output is not important.
1359
+ */
1360
+ type AnySchema = Schema<unknown>;
1361
+ /** Resolve the output type carried by a schema. */
1362
+ type InferSchema<S> = S extends Schema<infer Output> ? Output : never;
1363
+ /** Internal, cloneable flags shared by every schema. */
1364
+ interface SchemaState {
1365
+ optional: boolean;
1366
+ nullable: boolean;
1367
+ hasDefault: boolean;
1368
+ defaultValue: unknown;
1369
+ }
1370
+ /**
1371
+ * Base class for every schema.
1372
+ *
1373
+ * It owns the shared modifier flags (`.optional()`, `.nullable()`, `.default()`)
1374
+ * and the parse/safeParse entry points. Concrete schemas implement `_clone` and
1375
+ * `_validate`. All modifier methods return fresh instances, so a schema value
1376
+ * can be safely reused in multiple chains.
1377
+ */
1378
+ declare abstract class Schema<Output> {
1379
+ /** Phantom output type used by `z.infer`. */
1380
+ readonly _output: Output;
1381
+ /**
1382
+ * Standard Schema and Standard JSON Schema interface.
1383
+ *
1384
+ * This is the vendor-neutral contract used by the MCP SDK's `registerTool`
1385
+ * and `registerPrompt`. `validate` runs the same pipeline as
1386
+ * {@link Schema.safeParse}; `jsonSchema` advertises the wire shape.
1387
+ */
1388
+ readonly "~standard": StandardSchemaProps<unknown, Output>;
1389
+ protected readonly _state: SchemaState;
1390
+ constructor(state?: SchemaState);
1391
+ /** Create a fresh copy of this schema, including its modifier flags. */
1392
+ protected abstract _clone(): this;
1393
+ /** Validate a defined, non-null value and return the parsed output. */
1394
+ protected abstract _validate(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
1395
+ /**
1396
+ * Render this schema as JSON Schema.
1397
+ *
1398
+ * The result uses a subset that is valid for draft-07 and draft-2020-12.
1399
+ * Unknown top-level input keys are described with
1400
+ * `additionalProperties: false`; the requested target is ignored.
1401
+ */
1402
+ toJSONSchema(options?: StandardJSONSchemaOptions): Record<string, unknown>;
1403
+ /**
1404
+ * Implement each concrete schema's JSON Schema mapping.
1405
+ *
1406
+ * @internal
1407
+ */
1408
+ protected abstract _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1409
+ /**
1410
+ * Whether the field must appear in an object's `required` list.
1411
+ *
1412
+ * Fields with `.optional()` or `.default(...)` are not required.
1413
+ *
1414
+ * @internal
1415
+ */
1416
+ _isRequired(): boolean;
1417
+ /** Return a copy that also accepts `undefined` (a missing key is allowed). */
1418
+ optional(): Schema<Output | undefined>;
1419
+ /** Return a copy that also accepts `null`, but still rejects `undefined`. */
1420
+ nullable(): Schema<Output | null>;
1421
+ /**
1422
+ * Return a copy that substitutes `value` when the input is `undefined`.
1423
+ * The same default reference is used for every parse.
1424
+ */
1425
+ default(value: Exclude<Output, undefined>): Schema<Exclude<Output, undefined>>;
1426
+ /**
1427
+ * Shared handling for `undefined`, `null`, and defaults before a concrete
1428
+ * schema runs its own type checks.
1429
+ *
1430
+ * @internal
1431
+ */
1432
+ _run(value: unknown, path: (string | number)[], issues: Issue[]): Output | undefined;
1433
+ /**
1434
+ * Validate a value without throwing.
1435
+ *
1436
+ * Unknown object keys are stripped from the returned data. On failure the
1437
+ * result contains a {@link SchemaError} with every collected issue.
1438
+ */
1439
+ safeParse(data: unknown): SafeParseResult<Output>;
1440
+ /**
1441
+ * Validate a value and return the parsed output.
1442
+ *
1443
+ * @throws {SchemaError} When the input does not satisfy this schema.
1444
+ */
1445
+ parse(data: unknown): Output;
1446
+ }
1447
+
1448
+ type StringRule = {
1449
+ kind: "min";
1450
+ value: number;
1451
+ } | {
1452
+ kind: "max";
1453
+ value: number;
1454
+ } | {
1455
+ kind: "email";
1456
+ } | {
1457
+ kind: "trim";
1458
+ };
1459
+ type NumberRule = {
1460
+ kind: "min";
1461
+ value: number;
1462
+ } | {
1463
+ kind: "max";
1464
+ value: number;
1465
+ } | {
1466
+ kind: "int";
1467
+ };
1468
+ interface StringOptions {
1469
+ coerce?: boolean;
1470
+ rules?: StringRule[];
1471
+ state?: SchemaState;
1472
+ }
1473
+ interface NumberOptions {
1474
+ coerce?: boolean;
1475
+ rules?: NumberRule[];
1476
+ state?: SchemaState;
1477
+ }
1478
+ interface BooleanOptions {
1479
+ coerce?: boolean;
1480
+ state?: SchemaState;
1481
+ }
1482
+ /** Schema for text values, with `.min`, `.max`, and `.email` rules. */
1483
+ declare class StringSchema extends Schema<string> {
1484
+ private readonly _rules;
1485
+ private readonly _coerce;
1486
+ constructor(options?: StringOptions);
1487
+ protected _clone(): this;
1488
+ /** Require at least `length` characters. */
1489
+ min(length: number): this;
1490
+ /** Require at most `length` characters. */
1491
+ max(length: number): this;
1492
+ /** Require a conventional email address (`local@domain.tld`). */
1493
+ email(): this;
1494
+ /**
1495
+ * Trim leading and trailing whitespace before validation.
1496
+ *
1497
+ * `.min`, `.max`, and `.email` see the trimmed value, and the parsed output
1498
+ * is trimmed.
1499
+ */
1500
+ trim(): this;
1501
+ private _withRule;
1502
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1503
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): string | undefined;
1504
+ }
1505
+ /** Schema for numeric values, with `.min`, `.max`, and `.int` rules. */
1506
+ declare class NumberSchema extends Schema<number> {
1507
+ private readonly _rules;
1508
+ private readonly _coerce;
1509
+ constructor(options?: NumberOptions);
1510
+ protected _clone(): this;
1511
+ /** Require a value greater than or equal to `minimum`. */
1512
+ min(minimum: number): this;
1513
+ /** Require a value less than or equal to `maximum`. */
1514
+ max(maximum: number): this;
1515
+ /** Require a whole number. */
1516
+ int(): this;
1517
+ private _withRule;
1518
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1519
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): number | undefined;
1520
+ }
1521
+ /** Schema for boolean values. */
1522
+ declare class BooleanSchema extends Schema<boolean> {
1523
+ private readonly _coerce;
1524
+ constructor(options?: BooleanOptions);
1525
+ protected _clone(): this;
1526
+ protected _jsonSchema(_options: StandardJSONSchemaOptions): Record<string, unknown>;
1527
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): boolean | undefined;
1528
+ }
1529
+
1530
+ /** A map of field names to schemas. */
1531
+ type Shape = Record<string, AnySchema>;
1532
+ type OptionalShapeKeys<TShape extends Shape> = {
1533
+ [K in keyof TShape]: undefined extends InferSchema<TShape[K]> ? K : never;
1534
+ }[keyof TShape];
1535
+ /** Output type produced by an object schema, with optional fields preserved. */
1536
+ type InferShape<TShape extends Shape> = {
1537
+ [K in Exclude<keyof TShape, OptionalShapeKeys<TShape>>]: InferSchema<TShape[K]>;
1538
+ } & {
1539
+ [K in OptionalShapeKeys<TShape>]?: Exclude<InferSchema<TShape[K]>, undefined>;
1540
+ };
1541
+ type ArrayRule = {
1542
+ kind: "min";
1543
+ value: number;
1544
+ } | {
1545
+ kind: "max";
1546
+ value: number;
1547
+ };
1548
+ interface ArrayOptions {
1549
+ rules?: ArrayRule[];
1550
+ state?: SchemaState;
1551
+ }
1552
+ /** Schema for arrays whose items share a single item schema. */
1553
+ declare class ArraySchema<Item extends AnySchema> extends Schema<InferSchema<Item>[]> {
1554
+ private readonly _item;
1555
+ private readonly _rules;
1556
+ constructor(item: Item, options?: ArrayOptions);
1557
+ protected _clone(): this;
1558
+ /** Require at least `length` items. */
1559
+ min(length: number): this;
1560
+ /** Require at most `length` items. */
1561
+ max(length: number): this;
1562
+ private _withRule;
1563
+ protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1564
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferSchema<Item>[] | undefined;
1565
+ }
1566
+ interface ObjectOptions {
1567
+ state?: SchemaState;
1568
+ }
1569
+ /**
1570
+ * Schema for objects with a fixed shape.
1571
+ *
1572
+ * Unknown input keys are stripped from the parsed output (zod `.strip()`
1573
+ * behavior).
1574
+ */
1575
+ declare class ObjectSchema<TShape extends Shape> extends Schema<InferShape<TShape>> {
1576
+ /** Field schemas keyed by output property name. */
1577
+ readonly shape: TShape;
1578
+ constructor(shape: TShape, options?: ObjectOptions);
1579
+ protected _clone(): this;
1580
+ protected _jsonSchema(options: StandardJSONSchemaOptions): Record<string, unknown>;
1581
+ protected _validate(value: unknown, path: (string | number)[], issues: Issue[]): InferShape<TShape> | undefined;
1582
+ }
1583
+
1584
+ /** Create a text schema. */
1585
+ declare const string: () => StringSchema;
1586
+ /** Create a numeric schema. */
1587
+ declare const number: () => NumberSchema;
1588
+ /** Create a boolean schema. */
1589
+ declare const boolean: () => BooleanSchema;
1590
+ /** Create an array schema for the given item schema. */
1591
+ declare const array: <Item extends AnySchema>(item: Item) => ArraySchema<Item>;
1592
+ /** Create an object schema with a fixed shape. */
1593
+ declare const object: <TShape extends Shape>(shape: TShape) => ObjectSchema<TShape>;
1594
+ /**
1595
+ * Coercing variants that convert raw query/form strings before validation.
1596
+ * Non-string inputs pass through to the underlying type checks.
1597
+ */
1598
+ declare const coerce: {
1599
+ /** Create a text schema that stringifies numbers and booleans. */
1600
+ string: () => StringSchema;
1601
+ /** Create a numeric schema that converts numeric strings with `Number()`. */
1602
+ number: () => NumberSchema;
1603
+ /**
1604
+ * Create a boolean schema that accepts `"true"`/`"1"` and
1605
+ * `"false"`/`"0"` case-insensitively.
1606
+ */
1607
+ boolean: () => BooleanSchema;
1608
+ };
1609
+ /**
1610
+ * Resolve the output type of a schema.
1611
+ *
1612
+ * ```ts
1613
+ * const User = z.object({ name: z.string() });
1614
+ * type User = z.infer<typeof User>; // { name: string }
1615
+ * ```
1616
+ */
1617
+ type Infer<S extends AnySchema> = InferSchema<S>;
1618
+
1619
+ declare const z_d_array: typeof array;
1620
+ declare const z_d_boolean: typeof boolean;
1621
+ declare const z_d_coerce: typeof coerce;
1622
+ declare const z_d_number: typeof number;
1623
+ declare const z_d_object: typeof object;
1624
+ declare const z_d_string: typeof string;
1625
+ declare namespace z_d {
1626
+ export { z_d_array as array, z_d_boolean as boolean, z_d_coerce as coerce, z_d_number as number, z_d_object as object, z_d_string as string };
1627
+ export type { Infer as infer };
1148
1628
  }
1149
- declare function z<T extends Record<string, any>>(): SchemaBuilder<T>;
1150
1629
 
1151
1630
  declare const DEFAULT_MAX_SIZE: number;
1152
1631
  /**
@@ -1156,7 +1635,7 @@ declare const DEFAULT_MAX_SIZE: number;
1156
1635
  * @param schema - Schema used to validate the parsed JSON object.
1157
1636
  * @returns A guard factory that accepts a schema and optional error config.
1158
1637
  */
1159
- declare const json: (options?: SchemaBuilder<any> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1638
+ declare const json: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1160
1639
  interface RequireKeysOptions {
1161
1640
  keys: string[];
1162
1641
  }
@@ -1172,6 +1651,12 @@ declare const keys: (options?: string[] | undefined, overrideConfig?: BaseConfig
1172
1651
  type JwtPayload<T> = T & {
1173
1652
  iat: number;
1174
1653
  exp: number;
1654
+ /**
1655
+ * Unique token identifier assigned on every signature.
1656
+ *
1657
+ * Optional only so tokens issued before this claim existed remain readable.
1658
+ */
1659
+ jti?: string;
1175
1660
  };
1176
1661
 
1177
1662
  /**
@@ -1248,7 +1733,7 @@ declare const jwtRefresh: (options?: JWTAuthService<any> | undefined, overrideCo
1248
1733
  * @param label - Optional text included in the log entry.
1249
1734
  * @returns A guard factory that accepts a label and optional error config.
1250
1735
  */
1251
- declare const logger: (options?: void | string | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1736
+ declare const logger: (options?: string | void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1252
1737
  type logFN = {
1253
1738
  ctx: ctx;
1254
1739
  res: Response;
@@ -1273,11 +1758,15 @@ declare const loggerFN: (options?: ((ff: logFN) => any) | undefined, overrideCon
1273
1758
  */
1274
1759
  declare const multipart: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1275
1760
 
1276
- interface QueryValidationOptions<T extends Record<string, any>> {
1277
- schema: SchemaBuilder<T>;
1761
+ /** Options accepted by {@link validateQuery}. */
1762
+ interface QueryValidationOptions {
1763
+ /** Schema used to validate and coerce query parameters. */
1764
+ schema: AnySchema;
1278
1765
  }
1279
- interface FormValidationOptions<T extends Record<string, any>> {
1280
- schema: SchemaBuilder<T>;
1766
+ /** Options accepted by {@link validateForm}. */
1767
+ interface FormValidationOptions {
1768
+ /** Schema used to validate and coerce form fields. */
1769
+ schema: AnySchema;
1281
1770
  }
1282
1771
  /**
1283
1772
  * Validates and coerces URL query parameters against a schema, then stores the
@@ -1286,7 +1775,7 @@ interface FormValidationOptions<T extends Record<string, any>> {
1286
1775
  * @param schema - Schema used to validate and coerce query values.
1287
1776
  * @returns A guard factory that accepts the schema and optional error config.
1288
1777
  */
1289
- declare const validateQuery: (options?: SchemaBuilder<{}> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1778
+ declare const validateQuery: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1290
1779
  /**
1291
1780
  * Validates multipart or URL-encoded form fields against a schema and stores
1292
1781
  * the processed result in `ctx.form`.
@@ -1294,7 +1783,7 @@ declare const validateQuery: (options?: SchemaBuilder<{}> | undefined, overrideC
1294
1783
  * @param schema - Schema used to validate and coerce form values.
1295
1784
  * @returns A guard factory that accepts the schema and optional error config.
1296
1785
  */
1297
- declare const validateForm: (options?: SchemaBuilder<{}> | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1786
+ declare const validateForm: (options?: AnySchema | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1298
1787
 
1299
1788
  interface RateLimitOptions {
1300
1789
  /** Maximum number of connections/requests allowed within the window. @default 100 */
@@ -1453,14 +1942,76 @@ interface SessionConfig {
1453
1942
  * @returns A guard factory that accepts a session service and optional error config.
1454
1943
  */
1455
1944
  declare const session: (options?: SessionAuthInterface | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1945
+ /** Optional extra check applied to a session that `session()` already resolved. */
1946
+ type SessionValidator = (session: ServerSide) => boolean | Promise<boolean>;
1947
+ /**
1948
+ * Rejects requests that do not carry a valid, stored session.
1949
+ *
1950
+ * A session counts as authenticated only when the cookie signature is valid,
1951
+ * the row still exists in the store, it has not expired, and it is not a
1952
+ * freshly created anonymous session. Compose this guard after
1953
+ * `session(service)` — it reads `ctx.session` and never loads the cookie
1954
+ * itself:
1955
+ *
1956
+ * ```ts
1957
+ * @use(session(service), requireSession())
1958
+ * ```
1959
+ *
1960
+ * Pass a validator to add an application-level check, for example an identity
1961
+ * field written during login. Session data keys are not part of the
1962
+ * `ServerSide` type, so cast to your session shape:
1963
+ *
1964
+ * ```ts
1965
+ * @use(session(service), requireSession((s) => typeof (s as AccountSession).userId === "number"))
1966
+ * ```
1967
+ *
1968
+ * @param validator - Optional additional check for the resolved session.
1969
+ * @returns A guard factory that returns 401 and continues otherwise.
1970
+ */
1971
+ declare const requireSession: (options?: SessionValidator | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1456
1972
 
1973
+ /** Configuration for a {@link staticFiles} mount. */
1974
+ interface StaticFilesOptions {
1975
+ /**
1976
+ * Restricts this mount to request paths under the given prefix. The decoded
1977
+ * pathname is compared at a path-segment boundary, so `/assets` matches
1978
+ * `/assets` and `/assets/app.js` but not `/assetsfoo.png`. Requests outside
1979
+ * the prefix fall through to the remaining guards and routes, which keeps
1980
+ * authentication and route handling reachable. Omit it to intercept every
1981
+ * file-like path, as a global static mount does.
1982
+ */
1983
+ prefix?: string;
1984
+ /**
1985
+ * Directory this mount serves from. Relative paths resolve against
1986
+ * `process.cwd()`; absolute paths are used as-is. When set, the mount uses a
1987
+ * dedicated static file server instead of the app-wide `clientPath` server.
1988
+ * With a `prefix`, the prefix is stripped before the lookup, so
1989
+ * `/files/logo.png` maps to `<root>/logo.png`. Without a prefix the full
1990
+ * request path is used.
1991
+ */
1992
+ root?: string;
1993
+ /**
1994
+ * Additional file extensions recognized by this mount, with or without a
1995
+ * leading dot. They extend the built-in extension list but do not replace
1996
+ * the app-wide `fileExtensions` configuration.
1997
+ */
1998
+ extensions?: string[];
1999
+ }
1457
2000
  /**
1458
- * Serves requests for file-like paths through the configured static file server.
1459
- * Only GET and HEAD requests are intercepted.
2001
+ * Serves requests for file-like paths through a static file server.
2002
+ * Only GET and HEAD requests are intercepted; HEAD responses keep the file
2003
+ * headers but drop the body.
2004
+ *
2005
+ * Without options it behaves like a global mount: every recognized file-like
2006
+ * path is served from the app-wide `clientPath` server before route guards run.
2007
+ * Pass `prefix` and/or `root` to scope a mount, for example
2008
+ * `staticFiles({ prefix: "/files", root: "./private-files" })` registered
2009
+ * behind an authentication guard.
1460
2010
  *
2011
+ * @param options - Optional prefix, root, and extension configuration.
1461
2012
  * @returns A guard factory that serves static assets before route handling.
1462
2013
  */
1463
- declare const staticFiles: (options?: void | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2014
+ declare const staticFiles: (options?: StaticFilesOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1464
2015
 
1465
2016
  /**
1466
2017
  * Stops waiting for downstream work after the configured number of milliseconds.
@@ -1488,7 +2039,7 @@ interface UrlValidationOptions {
1488
2039
  * @param options - URL size, query, and path validation rules.
1489
2040
  * @returns A guard factory that accepts validation rules and optional error config.
1490
2041
  */
1491
- declare const validateUrl: (options?: void | number | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
2042
+ declare const validateUrl: (options?: number | void | UrlValidationOptions | undefined, overrideConfig?: BaseConfig) => GuardReturnType;
1492
2043
 
1493
2044
  /**
1494
2045
  * Parses an URL-encoded form request and stores its fields in `ctx.form`.
@@ -1536,5 +2087,5 @@ interface ScopeStatic {
1536
2087
  type Scope = _Scope;
1537
2088
  declare const Scope: ScopeStatic;
1538
2089
 
1539
- export { Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, Field, ForeignKeyError, JWTAuthService, Methods, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaBuilder, Scope, ServerSide, SessionAuthInterface, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, keys, logger, loggerFN, mariadbDialect, multipart, mysqlDialect, postgresDialect, rateLimit, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z };
1540
- export type { AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, JWTConfig, JwtPayload, JwtRefreshTokenStore, QueryValidationOptions, RateLimitOptions, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SanitizeOptions, SecurityHeadersOptions, SessionConfig, TableStats, TopicPublishResult, TopicPublishStatus, UrlValidationOptions, Where, WssBaseController, WssConfig, WssMessageRateLimit, WssRouteConfig, dev, methodsKeys, serverOptions, wssMessage };
2090
+ export { ArraySchema, BooleanSchema, Column, DEFAULT_MAX_SIZE, DatabaseError, DbInspector, DbRepository, DbSchema, Field, ForeignKeyError, JWTAuthService, McpController, Methods, NumberSchema, ObjectSchema, req as Req, res as Res, Rossa, RouterManager, Schema, SchemaError, Scope, ServerSide, SessionAuthInterface, StringSchema, UniqueConstraintError, WSSMAN, Websocket, WssManager, apiKey, auth, authBearer, authorize, contentType, cookies, cors, createGuard, csrf, ctx, deny, errorHandler, getDialect, header, ipFilter, json, jwtAuth, jwtRefresh, keys, logger, loggerFN, mariadbDialect, mcp, multipart, mysqlDialect, postgresDialect, rateLimit, requireSession, route, sanitize, security, sendError, session, smartCache, sqliteDialect, staticFiles, subManager, t, timeout, urlencoded, use, validateForm, validateQuery, validateUrl, wss, z_d as z };
2091
+ export type { AnySchema, AuthConfig, BaseConfig, CacheOptions, ColumnType, ContentEncodingType, ContentTypeRules, CorsOptions, CsrfOptions, DbDialectAdapter, DbDialectName, DenyConfig, ErrorConfig, ErrorGuardOptions, FormValidationOptions, GlobalGuard, GuardConfig, GuardFactoryHandler, GuardReturnType, HeaderValidationRules, HttpRouteConfig, HttpRouteMatch, InferSchema, InferShape, Issue, JWTConfig, JwtPayload, JwtRefreshTokenStore, McpOptions, McpServerFactory, QueryValidationOptions, RateLimitOptions, RequireKeysOptions, RossaOptions, RossaWebSocketOptions, SafeParseFailure, SafeParseResult, SafeParseSuccess, SanitizeOptions, SchemaState, SecurityHeadersOptions, SessionConfig, SessionValidator, Shape, StandardIssue, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardPathSegment, StandardSchema, StandardSchemaProps, StandardTypes, StandardValidateOptions, StandardValidateResult, StaticFilesOptions, TableStats, TopicPublishResult, TopicPublishStatus, UrlValidationOptions, Where, WssBaseController, WssConfig, WssMessageRateLimit, WssRouteConfig, dev, methodsKeys, serverOptions, wssMessage };