ovr 6.2.4 → 7.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -1,10 +1,24 @@
1
+ import { type Field, Form as FormSchema, forms, query } from "../form/index.js";
1
2
  import { type JSX, jsx } from "../jsx/index.js";
2
3
  import type { Middleware } from "../middleware/index.js";
3
- import { Form as FormSchema } from "../schema/index.js";
4
+ import { Schema as ValueSchema } from "../schema/index.js";
4
5
  import type { Trie } from "../trie/index.js";
5
6
  import { Checksum, Method, Mime } from "../util/index.js";
6
7
  import type { Util } from "../util/index.js";
7
8
 
9
+ /** Finishes a route's configuration, `app.use(route)` calls it */
10
+ export const freeze = Symbol("freeze");
11
+
12
+ /**
13
+ * Matches a pattern's parameters, as the router reads them: `:name` up to the
14
+ * next slash, anywhere in a segment, and a final `*`, the wildcard, which
15
+ * has no name. Internal to ovr.
16
+ */
17
+ export const parameters = /:([^/]+?)(?=\/|\*?$)|\*$/g;
18
+
19
+ /** Internal protocol for the MCP endpoint, to read a route's parameter schemas. */
20
+ export const schemas = Symbol("schemas");
21
+
8
22
  /**
9
23
  * Helper type to extract the route params (`:slug`) into a record.
10
24
  *
@@ -19,6 +33,75 @@ export type ExtractParams<Pattern extends string = string> =
19
33
  ? { "*": string }
20
34
  : {};
21
35
 
36
+ /**
37
+ * The last segment of a pattern, the only one a wildcard can end.
38
+ *
39
+ * @template P Route pattern
40
+ */
41
+ type Last<P extends string> = P extends `${string}/${infer R}` ? Last<R> : P;
42
+
43
+ /**
44
+ * `P`, or a message when a parameter runs into the wildcard, as in `/:id*`,
45
+ * where nothing tells them apart.
46
+ *
47
+ * @template P Route pattern
48
+ */
49
+ type Checked<P extends string> = string extends P
50
+ ? P
51
+ : P extends `/${string}`
52
+ ? P extends `${string}${"?" | "#" | "\\" | " " | "\t" | "\n" | "//"}${string}`
53
+ ? "A route pattern is a path, such as /posts/:id, without a query or a fragment"
54
+ : Last<P> extends `${string}:${string}*`
55
+ ? "Separate the parameter from the wildcard, as in /:id/*"
56
+ : P
57
+ : "A route pattern starts with /, such as /posts/:id";
58
+
59
+ /**
60
+ * A character or sequence a path of the app's own cannot hold: a query,
61
+ * a fragment, a scheme, a pattern, whitespace, or a segment that resolves
62
+ * to another path
63
+ */
64
+ type Unsafe =
65
+ "\\" | "?" | "#" | ":" | "*" | " " | "\t" | "\n" | "//" | "/./" | "/../";
66
+
67
+ /** Whitespace `String.prototype.trim` removes */
68
+ type Space =
69
+ | " "
70
+ | "\t"
71
+ | "\n"
72
+ | "\v"
73
+ | "\f"
74
+ | "\r"
75
+ | "\u00a0"
76
+ | "\u1680"
77
+ | "\u2000"
78
+ | "\u2001"
79
+ | "\u2002"
80
+ | "\u2003"
81
+ | "\u2004"
82
+ | "\u2005"
83
+ | "\u2006"
84
+ | "\u2007"
85
+ | "\u2008"
86
+ | "\u2009"
87
+ | "\u200a"
88
+ | "\u2028"
89
+ | "\u2029"
90
+ | "\u202f"
91
+ | "\u205f"
92
+ | "\u3000"
93
+ | "\ufeff";
94
+
95
+ /**
96
+ * `S` without leading or trailing whitespace
97
+ *
98
+ * @template S String to trim
99
+ */
100
+ type Trim<S extends string> = S extends
101
+ `${Space}${infer R}` | `${infer R}${Space}`
102
+ ? Trim<R>
103
+ : S;
104
+
22
105
  /**
23
106
  * Helper type to insert a record of params into a resolved string.
24
107
  *
@@ -27,7 +110,7 @@ export type ExtractParams<Pattern extends string = string> =
27
110
  */
28
111
  export type InsertParams<
29
112
  Pattern extends string,
30
- Params extends Trie.Params,
113
+ Params extends Route.URLParams,
31
114
  > = Pattern extends `${infer Start}:${infer Param}/${infer Rest}`
32
115
  ? Param extends keyof Params
33
116
  ? `${Start}${Params[Param]}/${InsertParams<Rest, Params>}`
@@ -56,6 +139,35 @@ export namespace Route {
56
139
  | "PATCH"
57
140
  | (string & {});
58
141
 
142
+ /** How agents call a route, from `route.tool`. */
143
+ export type Tool = {
144
+ /** Tool name, for example `post_posts_id_delete` */
145
+ readonly name: string;
146
+ /** What the tool does */
147
+ readonly description: string;
148
+ /** Only reads, a GET; other tools may change data, so agents can confirm them */
149
+ readonly read: boolean;
150
+ };
151
+
152
+ /**
153
+ * Schemas for route pattern parameters, keyed by parameter name.
154
+ *
155
+ * @template Pattern Route pattern
156
+ */
157
+ export type ParamSchemas<Pattern extends string> = {
158
+ readonly [K in keyof ExtractParams<Pattern>]?: ValueSchema<unknown>;
159
+ };
160
+
161
+ /**
162
+ * Route parameters after their schemas convert them.
163
+ *
164
+ * @template Params Current parameters
165
+ * @template P Parameter schemas
166
+ */
167
+ export type Converted<Params, P> = Util.Prettify<
168
+ Omit<Params, keyof P> & { [K in keyof P]: ValueSchema.Infer<P[K]> }
169
+ >;
170
+
59
171
  // these types are needed for proper JSDoc on `get` and `post` return types
60
172
  /**
61
173
  * Helper type for a route with a `<Button>` component.
@@ -88,12 +200,20 @@ export namespace Route {
88
200
  };
89
201
 
90
202
  /**
91
- * Form method subset attached to route helper types.
203
+ * The components a route with fields renders them with.
92
204
  *
205
+ * @template S Form field shape
206
+ */
207
+ type Components<S extends Field.Shape> = Pick<
208
+ FormSchema<S>,
209
+ "Field" | "Fields" | "component"
210
+ >;
211
+
212
+ /**
93
213
  * Omits `component` so schema-specific `component` signatures are not widened when a
94
- * concrete `Form<S>` is intersected onto the route type.
214
+ * concrete shape is intersected onto the route type.
95
215
  */
96
- type FormMethods = Omit<Route.Schema<any>, "component">;
216
+ type FormMethods = Omit<Components<any>, "component">;
97
217
 
98
218
  /**
99
219
  * Optional form helper methods available when a route may have a schema.
@@ -108,34 +228,121 @@ export namespace Route {
108
228
  : FormMethods[K];
109
229
  };
110
230
 
231
+ /**
232
+ * Schema helpers once `route.fields()` sets a shape.
233
+ *
234
+ * @template Shape Form field shape
235
+ */
236
+ type WithSchema<Shape extends Field.Shape> = [Field.Shape] extends [Shape]
237
+ ? MaybeForm
238
+ : Components<Shape>;
239
+
111
240
  /**
112
241
  * GET route type with route components and optional schema helpers.
113
242
  *
114
243
  * @template Pattern Route pattern
244
+ * @template Params Parameters passed to middleware
245
+ * @template Shape Form field shape
115
246
  */
116
- export type Get<Pattern extends string = string> = Route<Pattern> &
247
+ export type Get<
248
+ Pattern extends string = string,
249
+ Params extends Route.ParamsBase = any,
250
+ Shape extends Field.Shape = any,
251
+ > = Route<Pattern, Params, Shape, "get"> &
117
252
  WithAnchor<Pattern> &
118
253
  WithButton<Pattern> &
119
254
  WithForm<Pattern> &
120
- MaybeForm;
255
+ WithSchema<Shape>;
121
256
 
122
257
  /**
123
258
  * POST route type with route components and optional schema helpers.
124
259
  *
125
260
  * @template Pattern Route pattern
261
+ * @template Params Parameters passed to middleware
262
+ * @template Shape Form field shape
126
263
  */
127
- export type Post<Pattern extends string = string> = Route<Pattern> &
264
+ export type Post<
265
+ Pattern extends string = string,
266
+ Params extends Route.ParamsBase = any,
267
+ Shape extends Field.Shape = any,
268
+ > = Route<Pattern, Params, Shape, "post"> &
128
269
  WithButton<Pattern> &
129
270
  WithForm<Pattern> &
130
- MaybeForm;
271
+ WithSchema<Shape>;
272
+
273
+ /** Components a route has: GET routes add an `<Anchor>` */
274
+ export type Kind = "get" | "post" | "plain";
131
275
 
132
276
  /**
133
- * Schema helper type attached to routes that have a form schema.
277
+ * A route of the given kind.
134
278
  *
135
- * @template S Form field shape
279
+ * @template K Route kind
280
+ * @template Pattern Route pattern
281
+ * @template Params Parameters passed to middleware
282
+ * @template Shape Form field shape
283
+ */
284
+ export type Of<
285
+ K extends Route.Kind,
286
+ Pattern extends string,
287
+ Params extends Route.ParamsBase,
288
+ Shape extends Field.Shape,
289
+ > = K extends "get"
290
+ ? Route.Get<Pattern, Params, Shape>
291
+ : K extends "post"
292
+ ? Route.Post<Pattern, Params, Shape>
293
+ : Route<Pattern, Params, Shape, K>;
294
+
295
+ /** Parameters passed to middleware, strings unless a schema converts them */
296
+ export type ParamsBase = Record<string, unknown>;
297
+
298
+ /**
299
+ * A fixed path of the app's own, such as `/login`, checked as it is
300
+ * written: without parameters, a query, or a trailing slash. A path that is
301
+ * not written out, such as one read from the environment, is taken as it is.
302
+ *
303
+ * @template P Path
136
304
  */
137
- export type Schema<S extends FormSchema.Shape = FormSchema.Shape> =
138
- FormSchema<S>;
305
+ export type Path<P extends string> = string extends P
306
+ ? P
307
+ : P extends `/${string}`
308
+ ? P extends `${string}${Unsafe}${string}` | `${string}/.` | `${string}/..`
309
+ ? Path.Invalid
310
+ : P extends "/"
311
+ ? P
312
+ : P extends `${string}/`
313
+ ? Path.Invalid
314
+ : P
315
+ : Path.Invalid;
316
+
317
+ export namespace Path {
318
+ /** Shown in place of a path that is not one of the app's own */
319
+ export type Invalid =
320
+ "A path of the app's own, such as /login, without parameters, a query, or a trailing slash";
321
+ }
322
+
323
+ /**
324
+ * A route after `use()`: its middleware is typed by the params and fields
325
+ * set before it, so they cannot change, and calling `params()` or
326
+ * `fields()` is a type error.
327
+ *
328
+ * @template R Route
329
+ */
330
+ export type Used<R> = R & {
331
+ /** Call `.params()` before `.use()` */
332
+ readonly params: never;
333
+
334
+ /** Call `.fields()` before `.use()` */
335
+ readonly fields: never;
336
+ };
337
+
338
+ /**
339
+ * A parameter's value in a URL: text, or a number a `params` schema may
340
+ * have converted it to, written as its digits.
341
+ */
342
+ export type URLParam = string | number | bigint;
343
+
344
+ /** Parameter values to write into a route's pattern */
345
+ export type URLParams = Record<string, URLParam>;
139
346
 
140
347
  /**
141
348
  * Options to construct a relative URL from the route.
@@ -168,10 +375,37 @@ export namespace Route {
168
375
  readonly params?: undefined;
169
376
  }
170
377
  : {
171
- /** Route pattern parameters */
172
- readonly params: Params;
378
+ /** Route pattern parameters, numbers too, as `params` schemas may give them */
379
+ readonly params: { readonly [K in keyof Params]: Route.URLParam };
173
380
  });
174
381
 
382
+ /**
383
+ * Type of `route.url(options)`: the exact path with the given `params`,
384
+ * or a `string` once `search` or `hash` is added.
385
+ *
386
+ * @template Pattern Route pattern
387
+ * @template O URL options
388
+ */
389
+ export type Href<Pattern extends string, O> = [
390
+ Present<O, "search">,
391
+ Present<O, "hash">,
392
+ ] extends [never, never]
393
+ ? InsertParams<
394
+ Pattern,
395
+ O extends { readonly params: infer P extends Route.URLParams } ? P : {}
396
+ >
397
+ : string;
398
+
399
+ /**
400
+ * A given option's value, `never` when it is missing or `undefined`.
401
+ *
402
+ * @template O Options
403
+ * @template K Option name
404
+ */
405
+ type Present<O, K extends string> = K extends keyof O
406
+ ? NonNullable<O[K]>
407
+ : never;
408
+
175
409
  /**
176
410
  * `<Anchor>` route component type
177
411
  *
@@ -197,7 +431,14 @@ export namespace Route {
197
431
  */
198
432
  export type Form<Pattern extends string> = (
199
433
  props: JSX.IntrinsicElements["form"] &
200
- URLOptions<ExtractParams<Pattern>> & { state?: URL | undefined },
434
+ URLOptions<ExtractParams<Pattern>> & {
435
+ /** Current page URL, restores the state of an invalid submission */
436
+ state?: URL | undefined;
437
+ /** Initial field values, for example the record being edited */
438
+ values?: Readonly<Record<string, unknown>> | undefined;
439
+ /** Label of the generated submit button, defaults to "Submit" */
440
+ submit?: JSX.Element | undefined;
441
+ },
201
442
  ) => JSX.Element;
202
443
 
203
444
  /**
@@ -215,91 +456,292 @@ export namespace Route {
215
456
  /**
216
457
  * Route to use in the application.
217
458
  *
459
+ * Each method adds to the route and returns it, so a route reads as a chain:
460
+ *
461
+ * ```ts
462
+ * const update = Route.post("/posts/:id")
463
+ * .describe("Change a post's title or body")
464
+ * .params({ id: Schema.string().uuid() })
465
+ * .fields({ title, body })
466
+ * .use(async (c) => {
467
+ * // ...
468
+ * });
469
+ * ```
470
+ *
218
471
  * @template Pattern Route pattern
472
+ * @template Params Parameters passed to middleware
473
+ * @template Shape Form field shape
474
+ * @template Kind Components the route has
219
475
  */
220
- export class Route<Pattern extends string = string> {
221
- /** Route pattern */
222
- readonly pattern: Pattern;
223
-
476
+ export class Route<
477
+ Pattern extends string = string,
478
+ // any by default so a `Route` type accepts every route
479
+ Params extends Route.ParamsBase = any,
480
+ Shape extends Field.Shape = any,
481
+ Kind extends Route.Kind = any,
482
+ > {
224
483
  /** HTTP method */
225
484
  readonly method: Route.Method;
226
485
 
227
- /** Route middleware stack, runs after global middleware */
228
- readonly middleware: Middleware<any, any>[]; // any so you can use other middleware
486
+ /** Description for agents */
487
+ #description?: string;
488
+
489
+ /** Schemas that check and convert pattern parameters */
490
+ #paramSchemas?: Readonly<Record<string, ValueSchema<unknown>>>;
491
+
492
+ /** Mounted, so its configuration is final */
493
+ #frozen = false;
229
494
 
230
- /** Pattern parts */
231
- #parts: string[];
495
+ /** Route pattern */
496
+ readonly #pattern: Pattern;
497
+
498
+ /** Middleware added with `use` */
499
+ readonly #stack: Middleware<any, any>[] = [];
232
500
 
233
501
  /**
234
502
  * Create a new route.
235
503
  *
236
504
  * @param method HTTP Method
237
505
  * @param pattern Route pattern
238
- * @param middleware Route middleware
239
506
  */
240
- constructor(
241
- method: Route.Method,
242
- pattern: Pattern,
243
- ...middleware: Middleware<ExtractParams<Pattern>, any>[]
244
- ) {
507
+ constructor(method: Route.Method, pattern: Checked<Pattern>) {
245
508
  this.method = method;
246
- this.pattern = pattern;
247
- this.middleware = middleware;
248
- this.#parts = pattern.split("/");
509
+ // the message type only reaches here from a pattern already rejected
510
+ this.#pattern = pattern as Pattern;
511
+ }
512
+
513
+ /** Description for agents, only described routes are served to them */
514
+ get description() {
515
+ return this.#description;
516
+ }
517
+
518
+ /** Schemas that check and convert pattern parameters */
519
+ get [schemas]() {
520
+ return this.#paramSchemas;
521
+ }
522
+
523
+ /** Route pattern */
524
+ get pattern(): Pattern {
525
+ return this.#pattern;
526
+ }
527
+
528
+ /** Route middleware stack, runs after global middleware */
529
+ get middleware(): Middleware<any, any>[] {
530
+ const params = this.#paramSchemas;
531
+ // a copy, so a mounted route's middleware cannot be changed through it
532
+ if (!params) return [...this.#stack];
533
+
534
+ return [
535
+ (c, next) => {
536
+ for (const name in params) {
537
+ const result = params[name]!.parse(c.params[name]);
538
+
539
+ // a parameter that does not match is a resource that does not exist
540
+ if (result.issues) return void (c.res.status = 404);
541
+
542
+ c.params[name] = result.data;
543
+ }
544
+
545
+ return next();
546
+ },
547
+ ...this.#stack,
548
+ ];
549
+ }
550
+
551
+ /**
552
+ * The tool agents call the route as, through MCP and the route's `Form`.
553
+ * Only described routes are tools, so mounting a route never lets agents
554
+ * call it; GET tools are read-only.
555
+ */
556
+ get tool(): Route.Tool | undefined {
557
+ const { description, method, pattern } = this;
558
+
559
+ if (!description || method === Method.head) return;
560
+
561
+ const read = method === Method.get;
562
+
563
+ const segments = pattern
564
+ .split("/")
565
+ .filter(Boolean)
566
+ .map((segment) =>
567
+ segment === "*" ? "wildcard" : segment.replace(/^:/, ""),
568
+ );
569
+
570
+ let name = `${method.toLowerCase()}_${segments.join("_") || "index"}`;
571
+
572
+ // `_` and other punctuation could make two patterns' names the same,
573
+ // such as `/a/b` and `/a_b`, so those names end with the pattern's hash
574
+ if (
575
+ !segments.every((segment) => /^[A-Za-z0-9-]+$/.test(segment)) ||
576
+ name.length > 64
577
+ )
578
+ name = `${name
579
+ .replace(/[^\w-]+/g, "_")
580
+ .replace(/_+/g, "_")
581
+ .slice(0, 56)}_${Checksum.djb2(`${method} ${pattern}`).slice(0, 7)}`;
582
+
583
+ return { name, description, read };
584
+ }
585
+
586
+ /**
587
+ * Describe the route for agents. Only described routes are served to
588
+ * them: as MCP tools, and GET routes as resources too.
589
+ *
590
+ * @template D Description, a string literal that is not blank
591
+ * @param description What the route does, written for an agent, not blank
592
+ * @returns The route
593
+ */
594
+ describe<D extends string>(
595
+ description: Trim<D> extends ""
596
+ ? never
597
+ : // `:wildcard` and `*` would both be the tool's `wildcard` argument
598
+ ["wildcard" | "*"] extends [keyof ExtractParams<Pattern>]
599
+ ? "Rename :wildcard, a tool's * argument is named wildcard"
600
+ : D,
601
+ ) {
602
+ this.#configure("describe");
603
+ this.#description = description;
604
+ return this;
605
+ }
606
+
607
+ /**
608
+ * Check and convert pattern parameters before the middleware runs.
609
+ * A parameter that fails its schema responds `404`.
610
+ *
611
+ * @template P Schemas keyed by parameter name
612
+ * @param schemas Schemas keyed by parameter name
613
+ * @returns The route, with converted `c.params` types
614
+ */
615
+ params<P extends Route.ParamSchemas<Pattern>>(
616
+ // a name the pattern does not have is a type error
617
+ schemas: P,
618
+ ): Route.Of<Kind, Pattern, Route.Converted<Params, P>, Shape> {
619
+ this.#configure("params");
620
+
621
+ this.#paramSchemas = { ...this.#paramSchemas, ...schemas } as Record<
622
+ string,
623
+ ValueSchema<unknown>
624
+ >;
625
+
626
+ return this as any;
627
+ }
628
+
629
+ /**
630
+ * Set the form fields that `c.data()` parses, and that the route's `Form`
631
+ * renders by default.
632
+ *
633
+ * @template S Field shape
634
+ * @param fields Field shape
635
+ * @returns The route with form helpers
636
+ */
637
+ fields<S extends Field.Shape>(fields: S): Route.Of<Kind, Pattern, Params, S> {
638
+ this.#configure("fields");
639
+ let form = new FormSchema(fields);
640
+ // a GET form's submission is the URL, so its fields read from it
641
+ if (this.method === Method.get) form = form[query]();
642
+ forms.set(this, form);
643
+ const { Field, Fields, component } = form;
644
+
645
+ return Object.assign(this, { Field, Fields, component }) as any;
646
+ }
647
+
648
+ /**
649
+ * A mounted route is final, so the app's tools and middleware stay as
650
+ * they were when it was mounted. Changing the types middleware is given
651
+ * after `use()` is a type error instead, see `Route.Used`.
652
+ *
653
+ * @param method Method that changes the route
654
+ */
655
+ #configure(method: string) {
656
+ if (this.#frozen)
657
+ throw new TypeError(
658
+ `Call .${method}() before app.use() on route "${this.pattern}".`,
659
+ );
660
+ }
661
+
662
+ /** Finish the configuration, when an app mounts the route. */
663
+ [freeze]() {
664
+ this.#frozen = true;
249
665
  }
250
666
 
251
667
  /**
252
- * Constructs a _relative_ URL for the route.
668
+ * Add middleware to the route. The last one usually responds.
253
669
  *
254
- * @param [options] Options with type safe pathname parameters
670
+ * @param middleware Route middleware
671
+ * @returns The route
672
+ */
673
+ use(
674
+ ...middleware: Middleware<Params, Shape>[]
675
+ ): Route.Used<Route.Of<Kind, Pattern, Params, Shape>> {
676
+ this.#configure("use");
677
+ this.#stack.push(...middleware);
678
+ // a named type, not `this`, so an app's own routes can be named in
679
+ // its declarations
680
+ return this as any;
681
+ }
682
+
683
+ /**
684
+ * Construct a _relative_ URL for the route. Parameter values are encoded,
685
+ * so each stays in its own segment, and a wildcard keeps its slashes.
686
+ *
687
+ * @template O Options, the exact path type when only `params` are given
688
+ * @param [options] Parameters, search, and hash
255
689
  * @returns `pathname` + `search` + `hash`
256
690
  */
257
- url(
691
+ url<O extends object = {}>(
258
692
  ...[options]: keyof ExtractParams<Pattern> extends never
259
- ? [Route.URLOptions<ExtractParams<Pattern>>] | []
260
- : [Route.URLOptions<ExtractParams<Pattern>>]
261
- ) {
262
- return (
263
- this.pathname(
264
- // @ts-expect-error - do not have to pass in {} if no params
265
- options?.params,
266
- ) +
267
- (options?.search
693
+ ? [(O & Route.URLOptions<ExtractParams<Pattern>>)?]
694
+ : [O & Route.URLOptions<ExtractParams<Pattern>>]
695
+ ): Route.Href<Pattern, O> {
696
+ const params = options?.params as Route.URLParams | undefined;
697
+ const path = params
698
+ ? this.pattern.replace(parameters, (_, name?: string) =>
699
+ name
700
+ ? Route.#segment(String(params[name]!))
701
+ : // the wildcard keeps its slashes, each of its segments is encoded
702
+ String(params["*"]!)
703
+ .split("/")
704
+ .map((segment) => (segment ? Route.#segment(segment) : segment))
705
+ .join("/"),
706
+ )
707
+ : this.pattern;
708
+ // a value starting with a slash, such as a wildcard of `/host/path`,
709
+ // would make a path that browsers read as another origin
710
+ if (path.startsWith("//"))
711
+ throw new TypeError(
712
+ `Route path "${path}" would start with "//", which is read as another host`,
713
+ );
714
+ const { search, hash } = options ?? {};
715
+
716
+ return (path +
717
+ (search
268
718
  ? // use the value as the init
269
- // @ts-expect-error - see type above
270
- "?" + new URLSearchParams(options.search)
719
+ "?" +
720
+ new URLSearchParams(
721
+ search as ConstructorParameters<typeof URLSearchParams>[0],
722
+ )
271
723
  : "") +
272
- (options?.hash
724
+ (hash
273
725
  ? // adding # prefix if not present matches the URL setter:
274
726
  // https://developer.mozilla.org/en-US/docs/Web/API/URL/hash
275
- options.hash[0] === "#"
276
- ? options.hash
277
- : "#" + options.hash
278
- : "")
279
- );
727
+ hash[0] === "#"
728
+ ? hash
729
+ : "#" + hash
730
+ : "")) as Route.Href<Pattern, O>;
280
731
  }
281
732
 
282
733
  /**
283
- * @template Params Parameters to create the pathname with
284
- * @param [params] Parameters to insert
285
- * @returns Resolved `pathname` with params
734
+ * @param value Parameter value
735
+ * @returns The value encoded as one segment
736
+ * @throws When it would not stay in its segment: empty, `.`, or `..`,
737
+ * which a URL resolves away
286
738
  */
287
- pathname<Params extends ExtractParams<Pattern>>(
288
- ...[params]: keyof Params extends never ? [] : [Params]
289
- ): InsertParams<Pattern, Params> {
290
- if (!params) return this.pattern as InsertParams<Pattern, Params>;
291
-
292
- return this.#parts
293
- .map((part) => {
294
- if (part.startsWith(":")) {
295
- return params[part.slice(1) as keyof typeof params];
296
- }
297
-
298
- if (part === "*") return params[part as keyof typeof params];
299
-
300
- return part;
301
- })
302
- .join("/") as InsertParams<Pattern, Params>;
739
+ static #segment(value: string) {
740
+ if (value === "" || value === "." || value === "..")
741
+ throw new TypeError(
742
+ `Route parameter "${value}" cannot be a path segment, it would change the path`,
743
+ );
744
+ return encodeURIComponent(value);
303
745
  }
304
746
 
305
747
  /**
@@ -320,7 +762,15 @@ export class Route<Pattern extends string = string> {
320
762
  formenctype: enctype,
321
763
  ...rest,
322
764
  })) as Route.Button<Pattern>,
323
- Form: (({ params, search, hash, state, ...rest }) => {
765
+ Form: (({
766
+ params,
767
+ search,
768
+ hash,
769
+ state,
770
+ values,
771
+ submit = "Submit",
772
+ ...rest
773
+ }) => {
324
774
  let query: URLSearchParams | undefined;
325
775
 
326
776
  if (route.method === Method.post && state) {
@@ -341,6 +791,9 @@ export class Route<Pattern extends string = string> {
341
791
  );
342
792
  }
343
793
 
794
+ const { Fields } = route as Route.Post<Pattern>;
795
+ const { tool } = route;
796
+
344
797
  return jsx("form", {
345
798
  action: route.url({
346
799
  params,
@@ -349,229 +802,57 @@ export class Route<Pattern extends string = string> {
349
802
  } as Route.URLOptions<ExtractParams<Pattern>>),
350
803
  method: route.method,
351
804
  enctype,
352
- ...rest,
353
- });
354
- }) as Route.Form<Pattern>,
355
- });
356
- }
357
-
358
- /**
359
- * @template Pattern Route pattern
360
- * @template R Route type with Form component
361
- * @param route Route to add schema behavior to
362
- * @param schema Form schema
363
- * @returns Route with schema behavior attached
364
- */
365
- static #withSchema<
366
- Pattern extends string,
367
- R extends { middleware: Middleware<any, any>[]; Form: Route.Form<Pattern> },
368
- >(route: R, schema?: Route.Schema): R | (R & Route.Schema) {
369
- if (!schema) return route;
370
-
371
- // original form shell from normal route
372
- const { Form } = route;
373
-
374
- return Object.assign(route, schema, {
375
- Form: (({ state, ...rest }) =>
376
- Form({
377
- // add in the default children (Fields) with state and submit button
805
+ // default to the fields, if any, and a submit button, so a form
806
+ // without fields, such as a delete, is still one to submit
378
807
  children: [
379
- schema.Fields({ state }),
380
- jsx("button", { children: "Submit" }),
808
+ Fields?.({ state, values }),
809
+ jsx("button", { children: submit }),
381
810
  ],
382
- state,
811
+ // WebMCP, browser agents call the form as the route's tool. A form
812
+ // bound to a parameter, like a delete form in each row, would repeat
813
+ // the name, so those set the attributes themselves when they are unique
814
+ ...(tool &&
815
+ !/[:*]/.test(route.pattern) && {
816
+ toolname: tool.name,
817
+ tooldescription: tool.description,
818
+ // a form that may change data waits for the user to submit it
819
+ toolautosubmit: tool.read,
820
+ }),
383
821
  ...rest,
384
- } as Parameters<typeof Form>[0])) as Route.Form<Pattern>,
822
+ });
823
+ }) as Route.Form<Pattern>,
385
824
  });
386
825
  }
387
826
 
388
827
  /**
389
828
  * @template Pattern Route pattern
390
829
  * @param pattern Route pattern
391
- * @param middleware GET middleware
392
830
  * @returns GET `Route` with added components
393
831
  */
394
- static get<Pattern extends string>(
395
- pattern: Pattern,
396
- ...middleware: Middleware<ExtractParams<Pattern>>[]
397
- ): Route.Get<Pattern>;
398
- /**
399
- * @template Pattern Route pattern
400
- * @template S Form field shape
401
- * @param pattern Route pattern
402
- * @param fields Form field shape
403
- * @param middleware GET middleware
404
- * @returns GET `Route` with added components
405
- */
406
- static get<Pattern extends string, S extends FormSchema.Shape>(
407
- pattern: Pattern,
408
- fields: S,
409
- ...middleware: Middleware<ExtractParams<Pattern>, S>[]
410
- ): Route.Get<Pattern> & Route.Schema<S>;
411
- /**
412
- * @template Pattern Route pattern
413
- * @template S Form field shape
414
- * @param pattern Route pattern
415
- * @param form Form schema
416
- * @param middleware GET middleware
417
- * @returns GET `Route` with added components
418
- */
419
- static get<Pattern extends string, S extends FormSchema.Shape>(
420
- pattern: Pattern,
421
- form: Route.Schema<S>,
422
- ...middleware: Middleware<ExtractParams<Pattern>, S>[]
423
- ): Route.Get<Pattern> & Route.Schema<S>;
424
- static get<Pattern extends string>(
425
- pattern: Pattern,
426
- schemaOrMiddleware?:
427
- | Route.Schema
428
- | FormSchema.Shape
429
- | Middleware<ExtractParams<Pattern>>
430
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>,
431
- ...middleware: (
432
- | Middleware<ExtractParams<Pattern>>
433
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>
434
- )[]
435
- ) {
436
- let schema: Route.Schema | undefined;
832
+ static get<Pattern extends string>(pattern: Checked<Pattern>) {
833
+ const route = Route.#withComponents(new Route(Method.get, pattern));
437
834
 
438
- if (schemaOrMiddleware) {
439
- if (typeof schemaOrMiddleware === "function") {
440
- middleware.unshift(schemaOrMiddleware);
441
- } else {
442
- schema = FormSchema.from(schemaOrMiddleware);
443
- }
444
- }
445
-
446
- const route = Route.#withComponents(
447
- new Route(Method.get, pattern, ...middleware),
448
- );
449
-
450
- return Route.#withSchema(
451
- Object.assign(route, {
452
- Anchor: (({ params, search, hash, ...rest }) =>
453
- jsx("a", {
454
- href: route.url({ params, search, hash } as Route.URLOptions<
455
- ExtractParams<Pattern>
456
- >),
457
- ...rest,
458
- })) as Route.Anchor<Pattern>,
459
- }),
460
- schema,
461
- );
835
+ return Object.assign(route, {
836
+ Anchor: (({ params, search, hash, ...rest }) =>
837
+ jsx("a", {
838
+ href: route.url({ params, search, hash } as Route.URLOptions<
839
+ ExtractParams<Pattern>
840
+ >),
841
+ ...rest,
842
+ })) as Route.Anchor<Pattern>,
843
+ }) as Route.Get<Pattern, ExtractParams<Pattern>, Field.Shape>;
462
844
  }
463
845
 
464
- /**
465
- * @param middleware POST middleware
466
- * @returns POST `Route` with added components
467
- */
468
- static post(...middleware: Middleware<{}>[]): Route.Post;
469
- /**
470
- * @template S Form field shape
471
- * @param fields Form field shape
472
- * @param middleware POST middleware
473
- * @returns POST `Route` with added components
474
- */
475
- static post<S extends FormSchema.Shape>(
476
- fields: S,
477
- ...middleware: Middleware<{}, S>[]
478
- ): Route.Post & Route.Schema<S>;
479
- /**
480
- * @template S Form field shape
481
- * @param form Form schema
482
- * @param middleware POST middleware
483
- * @returns POST `Route` with added components
484
- */
485
- static post<S extends FormSchema.Shape>(
486
- form: Route.Schema<S>,
487
- ...middleware: Middleware<{}, S>[]
488
- ): Route.Post & Route.Schema<S>;
489
- /**
490
- * @template Pattern Route pattern
491
- * @param pattern Route pattern
492
- * @param middleware POST middleware
493
- * @returns POST `Route` with added components
494
- */
495
- static post<Pattern extends string>(
496
- pattern: Pattern,
497
- ...middleware: Middleware<ExtractParams<Pattern>>[]
498
- ): Route.Post<Pattern>;
499
- /**
500
- * @template Pattern Route pattern
501
- * @template S Form field shape
502
- * @param pattern Route pattern
503
- * @param fields Form field shape
504
- * @param middleware POST middleware
505
- * @returns POST `Route` with added components
506
- */
507
- static post<Pattern extends string, S extends FormSchema.Shape>(
508
- pattern: Pattern,
509
- fields: S,
510
- ...middleware: Middleware<ExtractParams<Pattern>, S>[]
511
- ): Route.Post<Pattern> & Route.Schema<S>;
512
846
  /**
513
847
  * @template Pattern Route pattern
514
- * @template S Form field shape
515
848
  * @param pattern Route pattern
516
- * @param form Form schema
517
- * @param middleware POST middleware
518
849
  * @returns POST `Route` with added components
519
850
  */
520
- static post<Pattern extends string, S extends FormSchema.Shape>(
521
- pattern: Pattern,
522
- form: Route.Schema<S>,
523
- ...middleware: Middleware<ExtractParams<Pattern>, S>[]
524
- ): Route.Post<Pattern> & Route.Schema<S>;
525
- static post<Pattern extends string>(
526
- patternOrSchemaOrMiddleware:
527
- | Pattern
528
- | Route.Schema
529
- | FormSchema.Shape
530
- | Middleware<ExtractParams<Pattern>>
531
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>,
532
- schemaOrMiddleware?:
533
- | Route.Schema
534
- | FormSchema.Shape
535
- | Middleware<ExtractParams<Pattern>>
536
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>,
537
- ...middleware: (
538
- | Middleware<ExtractParams<Pattern>>
539
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>
540
- )[]
541
- ) {
542
- let pattern: Pattern | undefined;
543
- let schema: Route.Schema | undefined;
544
-
545
- const resolve = (
546
- psm?:
547
- | Pattern
548
- | Route.Schema
549
- | FormSchema.Shape
550
- | Middleware<ExtractParams<Pattern>>
551
- | Middleware<ExtractParams<Pattern>, FormSchema.Shape>,
552
- ) => {
553
- if (psm) {
554
- if (typeof psm === "string") {
555
- pattern = psm;
556
- } else if (typeof psm !== "function") {
557
- schema = FormSchema.from(psm);
558
- } else {
559
- middleware.unshift(psm);
560
- }
561
- }
562
- };
563
-
564
- resolve(patternOrSchemaOrMiddleware);
565
- resolve(schemaOrMiddleware);
566
-
567
- if (!pattern) {
568
- // create pattern with checksum of all mw stringified
569
- pattern = `/_p/${Checksum.djb2(middleware.join())}` as Pattern;
570
- }
571
-
572
- return Route.#withSchema(
573
- Route.#withComponents(new Route(Method.post, pattern, ...middleware)),
574
- schema,
575
- );
851
+ static post<Pattern extends string>(pattern: Checked<Pattern>) {
852
+ return Route.#withComponents(new Route(Method.post, pattern)) as Route.Post<
853
+ Pattern,
854
+ ExtractParams<Pattern>,
855
+ Field.Shape
856
+ >;
576
857
  }
577
858
  }