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,8 +1,59 @@
1
- import { Fragment, jsx } from "../jsx/index.js";
2
- import { Multipart } from "../multipart/index.js";
3
- import { Checksum, Codec, Size } from "../util/index.js";
1
+ /**
2
+ * Keywords a schema adds to its JSON Schema as an object's property, which
3
+ * fields use for their label and an unchecked box's default.
4
+ */
5
+ export const annotate = Symbol("annotate");
6
+ /**
7
+ * Preprocessors that only normalize input, so a stored value parses unchanged.
8
+ * Tables allow these and reject other preprocessors.
9
+ */
10
+ export const normalizers = new WeakSet();
11
+ /**
12
+ * Set a property, defining `__proto__` as data since assigning it would
13
+ * change the object's prototype.
14
+ *
15
+ * @param data Object to set it on
16
+ * @param name Property name
17
+ * @param value Property value
18
+ */
19
+ export const own = (data, name, value) => {
20
+ if (name === "__proto__")
21
+ Object.defineProperty(data, name, {
22
+ value,
23
+ enumerable: true,
24
+ writable: true,
25
+ configurable: true,
26
+ });
27
+ else
28
+ data[name] = value;
29
+ };
30
+ /**
31
+ * Add issues to a list, one at a time, since spreading a very long list
32
+ * into `push` overflows the stack.
33
+ *
34
+ * @template I Issue
35
+ * @param issues List to add to
36
+ * @param more Issues to add
37
+ */
38
+ export const append = (issues, more) => {
39
+ for (const issue of more)
40
+ issues.push(issue);
41
+ };
42
+ /**
43
+ * Convert to a number without rounding. Integers beyond 2^53 were or would
44
+ * be rounded, so they are left as text, which fails a number's validation.
45
+ *
46
+ * @param value Value to convert, such as form text or a driver's `numeric`
47
+ * @returns The number, or the text of an integer too large to be one
48
+ */
49
+ export const exact = (value) => {
50
+ const number = Number(value);
51
+ return Number.isInteger(number) && !Number.isSafeInteger(number)
52
+ ? String(value)
53
+ : number;
54
+ };
4
55
  /** Shared runtime shape operations used by object and form schema methods. */
5
- class ShapeUtil {
56
+ export class ShapeUtil {
6
57
  /**
7
58
  * Merge two record-like shapes where `extra` keys override `shape`.
8
59
  *
@@ -28,7 +79,7 @@ class ShapeUtil {
28
79
  const out = {};
29
80
  for (const name of names) {
30
81
  if (name in shape)
31
- out[name] = shape[name];
82
+ own(out, name, shape[name]);
32
83
  }
33
84
  return out;
34
85
  }
@@ -46,91 +97,105 @@ class ShapeUtil {
46
97
  const out = {};
47
98
  for (const [name, value] of Object.entries(shape)) {
48
99
  if (!remove.has(name))
49
- out[name] = value;
100
+ own(out, name, value);
50
101
  }
51
102
  return out;
52
103
  }
53
104
  }
105
+ // named classes, so their published types are written by name and do not
106
+ // spell out what `Error` has in each runtime, such as Node's
107
+ /** Validation issue produced during parsing. */
108
+ class Issue extends Error {
109
+ /** Expected type/value. */
110
+ expected;
111
+ /** Path to the invalid value. */
112
+ path;
113
+ /**
114
+ * @param expected Expected value
115
+ * @param path Path to the invalid value
116
+ * @param message Issue message
117
+ */
118
+ constructor(expected, path, message) {
119
+ const exp = String(expected);
120
+ super(message ?? `Expected ${exp}`);
121
+ this.name = "Schema.Issue";
122
+ this.expected = exp;
123
+ this.path = path;
124
+ }
125
+ /**
126
+ * @returns `Schema.Issue(path): message`
127
+ */
128
+ toString() {
129
+ let path = "";
130
+ for (const segment of this.path) {
131
+ path +=
132
+ typeof segment === "number"
133
+ ? `[${segment}]`
134
+ : `${path ? "." : path}${segment}`;
135
+ }
136
+ return `${this.name}${path ? `(${path})` : ""}: ${this.message}`;
137
+ }
138
+ toJSON() {
139
+ return { ...this, message: this.message };
140
+ }
141
+ }
142
+ /** AggregateIssue containing at least one Schema.Issue */
143
+ class AggregateIssue extends AggregateError {
144
+ /** Non-empty tuple of issues */
145
+ issues;
146
+ /** User submitted / sanitized values */
147
+ values;
148
+ /**
149
+ * Create a new AggregateIssue.
150
+ *
151
+ * Coerces issues into a non-empty tuple.
152
+ *
153
+ * @param issues Issues
154
+ * @param values Received values
155
+ */
156
+ constructor([first, ...rest], values) {
157
+ if (!first)
158
+ throw new TypeError("AggregateIssue must have an issue.");
159
+ const issues = [first, ...rest];
160
+ const name = "Schema.AggregateIssue";
161
+ const count = issues.length;
162
+ super(issues, `${name}(${count})\n${issues.join("\n")}`);
163
+ this.name = name;
164
+ this.issues = issues;
165
+ this.values = values;
166
+ }
167
+ toString() {
168
+ // prevents name being in the default twice since it's
169
+ // already in the message
170
+ return this.message;
171
+ }
172
+ toJSON() {
173
+ return { ...this, message: this.message };
174
+ }
175
+ }
54
176
  /**
55
177
  * Minimal schema validator geared around parsing form data like
56
178
  * multipart `FormData` and `URLSearchParams`.
57
179
  *
58
- * Implements Standard Schema v1 via the `~standard` property (sync validate).
180
+ * Implements Standard Schema v1 and Standard JSON Schema v1 via the
181
+ * `~standard` property (sync validate).
59
182
  *
60
183
  * @template Output Output type after parsing
61
184
  */
62
185
  export class Schema {
63
186
  /** Email regular expression */
64
187
  static #emailRegex = /^(?!\.)(?!.*\.\.)([a-z0-9_'+\-\.]*)[a-z0-9_'+\-]@([a-z0-9][a-z0-9\-]*\.)+[a-z]{2,}$/i;
65
- /** Validation issue produced during parsing. */
66
- static Issue = class Issue extends Error {
67
- /** Expected type/value. */
68
- expected;
69
- /** Path to the invalid value. */
70
- path;
71
- /**
72
- * @param expected Expected value
73
- * @param path Path to the invalid value
74
- * @param message Issue message
75
- */
76
- constructor(expected, path, message) {
77
- const exp = String(expected);
78
- super(message ?? `Expected ${exp}`);
79
- this.name = "Schema.Issue";
80
- this.expected = exp;
81
- this.path = path;
82
- }
83
- /**
84
- * @returns `Schema.Issue(path): message`
85
- */
86
- toString() {
87
- let path = "";
88
- for (const segment of this.path) {
89
- path +=
90
- typeof segment === "number"
91
- ? `[${segment}]`
92
- : `${path ? "." : path}${segment}`;
93
- }
94
- return `${this.name}${path ? `(${path})` : ""}: ${this.message}`;
95
- }
96
- toJSON() {
97
- return { ...this, message: this.message };
98
- }
188
+ /** UUID regular expression, any version */
189
+ static #uuidRegex = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
190
+ /** `$schema` URI for each supported target. */
191
+ static #dialects = {
192
+ "draft-2020-12": "https://json-schema.org/draft/2020-12/schema",
193
+ "draft-07": "http://json-schema.org/draft-07/schema#",
99
194
  };
195
+ /** Validation issue produced during parsing. */
196
+ static Issue = Issue;
100
197
  /** AggregateIssue containing at least one Schema.Issue */
101
- static AggregateIssue = class AggregateIssue extends AggregateError {
102
- /** Non-empty tuple of issues */
103
- issues;
104
- /** User submitted / sanitized values */
105
- values;
106
- /**
107
- * Create a new AggregateIssue.
108
- *
109
- * Coerces issues into a non-empty tuple.
110
- *
111
- * @param issues Issues
112
- * @param values Received values
113
- */
114
- constructor([first, ...rest], values) {
115
- if (!first)
116
- throw new TypeError("AggregateIssue must have an issue.");
117
- const issues = [first, ...rest];
118
- const name = "Schema.AggregateIssue";
119
- const count = issues.length;
120
- super(issues, `${name}(${count})\n${issues.join("\n")}`);
121
- this.name = name;
122
- this.issues = issues;
123
- this.values = values;
124
- }
125
- toString() {
126
- // prevents name being in the default twice since it's
127
- // already in the message
128
- return this.message;
129
- }
130
- toJSON() {
131
- return { ...this, message: this.message };
132
- }
133
- };
198
+ static AggregateIssue = AggregateIssue;
134
199
  "~standard" = {
135
200
  version: 1,
136
201
  vendor: "ovr",
@@ -138,7 +203,13 @@ export class Schema {
138
203
  const result = this.parse(value);
139
204
  return result.issues ? result : { value: result.data };
140
205
  },
206
+ jsonSchema: {
207
+ input: (options) => this.#standard(options, "input"),
208
+ output: (options) => this.#standard(options, "output"),
209
+ },
141
210
  };
211
+ /** Inspectable definition this schema was built from. */
212
+ def;
142
213
  /**
143
214
  * Parse and validate an unknown value.
144
215
  *
@@ -147,118 +218,642 @@ export class Schema {
147
218
  * @returns Parse result containing data or issues
148
219
  */
149
220
  parse;
221
+ /** Compiled parse, nested schemas share one path that is copied only into issues. */
222
+ #run;
150
223
  /**
151
224
  * Construct a new schema - used internally.
152
225
  *
153
226
  * Use static methods on `Schema` to make a new schema.
154
227
  *
155
- * @param parse Parse function that validates and transforms input
156
- */
157
- constructor(parse) {
158
- this.parse = (value, path = []) => parse(value, path);
228
+ * @param def Schema definition
229
+ */
230
+ constructor(def) {
231
+ const run = Schema.#compile(def);
232
+ this.def = def;
233
+ this.#run = run;
234
+ this.parse = (value, path) => {
235
+ const result = run(value, path ? [...path] : []);
236
+ return result.issues
237
+ ? new Schema.AggregateIssue(result.issues.map((issue) => new Schema.Issue(issue.expected, issue.path, issue.message)))
238
+ : result;
239
+ };
159
240
  }
160
241
  /**
161
- * @internal Required for Field to override and return a `Field` instance
242
+ * Required for Field to override and return a `Field` instance
162
243
  * from the chained methods instead of a `Schema`
163
244
  * @template O Output type of the new schema
164
- * @param parse Parse function that validates and transforms input
245
+ * @param def Definition of the new schema
165
246
  * @returns New schema instance based on the current instance
166
247
  */
167
- derive(parse) {
168
- return new Schema(parse);
248
+ derive(def) {
249
+ return new Schema(def);
169
250
  }
170
- optional() {
171
- return this.derive((v, path) => {
172
- if (v === undefined)
173
- return { data: undefined };
174
- return this.parse(v, path);
251
+ /**
252
+ * Say what the value is. Agents read it as the `description` in its JSON
253
+ * Schema, such as of a tool's argument, and a field shows it to people
254
+ * under its control.
255
+ *
256
+ * ```ts
257
+ * Schema.string().uuid().describe("The bookmark's ID");
258
+ * Field.url().describe("An http or https address");
259
+ * ```
260
+ *
261
+ * @param text Description
262
+ * @returns Schema with the description
263
+ */
264
+ describe(text) {
265
+ return this.derive({ ...this.def, description: text });
266
+ }
267
+ /**
268
+ * @returns The description given with `describe()`, here or on the
269
+ * schema this one wraps, such as before `optional()`
270
+ */
271
+ get description() {
272
+ let def = this.def;
273
+ while (def) {
274
+ if (def.description !== undefined)
275
+ return def.description;
276
+ def = "inner" in def ? def.inner.def : undefined;
277
+ }
278
+ }
279
+ /**
280
+ * @internal Overridden by Field to describe itself as an object's property
281
+ * @param _io Side of the description
282
+ * @returns Keywords added to the property's JSON Schema
283
+ */
284
+ [annotate](_io) { }
285
+ /**
286
+ * Convert the schema into a JSON Schema document.
287
+ *
288
+ * Refinements without a JSON Schema equivalent are omitted.
289
+ *
290
+ * @param options Target dialect, input/output side, and unrepresentable handling
291
+ * @returns JSON Schema object
292
+ */
293
+ toJsonSchema(options = {}) {
294
+ const { target = "draft-2020-12", io = "output", unrepresentable = "throw", } = options;
295
+ if (!Object.hasOwn(Schema.#dialects, target)) {
296
+ throw new TypeError(`Unsupported JSON Schema target: ${target}`);
297
+ }
298
+ return {
299
+ $schema: Schema.#dialects[target],
300
+ ...Schema.#node(this, { target, io, unrepresentable }).schema,
301
+ };
302
+ }
303
+ /**
304
+ * @param options Standard JSON Schema options
305
+ * @param io Side of the description
306
+ * @returns JSON Schema object
307
+ */
308
+ #standard({ target, libraryOptions }, io) {
309
+ return this.toJsonSchema({
310
+ ...libraryOptions,
311
+ target: target,
312
+ io,
175
313
  });
176
314
  }
315
+ /**
316
+ * @param check Check to apply to the output
317
+ * @returns Checked schema
318
+ */
319
+ #check(check) {
320
+ return this.derive({ type: "check", inner: this, check });
321
+ }
322
+ /**
323
+ * @param expected Expected value
324
+ * @param path Issue path, copied since parsing continues to change it
325
+ * @param message Issue message
326
+ * @returns Invalid result with one issue
327
+ */
328
+ static #issue(expected, path, message) {
329
+ return { issues: [{ expected, path: [...path], message }] };
330
+ }
331
+ /**
332
+ * Compile a definition into its parse function once, at construction.
333
+ *
334
+ * Nested schemas run with the parent's path, adding their key while they
335
+ * parse and removing it after, so valid values allocate no paths.
336
+ *
337
+ * @param def Schema definition
338
+ * @returns Parse function
339
+ */
340
+ static #compile(def) {
341
+ switch (def.type) {
342
+ case "unknown":
343
+ return (v) => ({ data: v });
344
+ case "string":
345
+ case "boolean":
346
+ case "bigint":
347
+ return (v, path) => typeof v === def.type
348
+ ? { data: v }
349
+ : Schema.#issue(def.type, path, def.message);
350
+ case "number":
351
+ return (v, path) => Number.isFinite(v) // isFinite checks type
352
+ ? { data: v }
353
+ : Schema.#issue("number", path, def.message);
354
+ case "date":
355
+ return (v, path) => v instanceof Date && !Number.isNaN(v.getTime())
356
+ ? { data: v }
357
+ : Schema.#issue("Date", path, def.message);
358
+ case "literal":
359
+ return (v, path) => v === def.value
360
+ ? { data: def.value }
361
+ : Schema.#issue(def.value, path, def.message);
362
+ case "enum":
363
+ return (v, path) => {
364
+ for (const value of def.values) {
365
+ if (v === value)
366
+ return { data: value };
367
+ }
368
+ return Schema.#issue(def.values.map((v) => JSON.stringify(v)).join(" | "), path, def.message);
369
+ };
370
+ case "instance":
371
+ return (v, path) => v instanceof def.class
372
+ ? { data: v }
373
+ : Schema.#issue(def.class.name, path, def.message);
374
+ case "array":
375
+ return (v, path) => {
376
+ if (!Array.isArray(v))
377
+ return Schema.#issue("Array", path, def.message);
378
+ const data = [];
379
+ let issues;
380
+ for (let i = 0; i < v.length; i++) {
381
+ path.push(i);
382
+ const result = def.item.#run(v[i], path);
383
+ path.pop();
384
+ if (result.issues) {
385
+ // the first failure's list is new, so it is reused
386
+ if (issues)
387
+ append(issues, result.issues);
388
+ else
389
+ issues = result.issues;
390
+ }
391
+ else {
392
+ data.push(result.data);
393
+ }
394
+ }
395
+ return issues ? { issues } : { data };
396
+ };
397
+ case "object": {
398
+ const shape = Object.entries(def.shape);
399
+ return (value, path) => {
400
+ if (value == null ||
401
+ typeof value !== "object" ||
402
+ Array.isArray(value)) {
403
+ return Schema.#issue("Object", path);
404
+ }
405
+ const data = {};
406
+ let issues;
407
+ for (const [name, schema] of shape) {
408
+ path.push(name);
409
+ const result = schema.#run(value[name], path);
410
+ path.pop();
411
+ if (result.issues) {
412
+ if (issues)
413
+ append(issues, result.issues);
414
+ else
415
+ issues = result.issues;
416
+ }
417
+ else if (result.data !== undefined) {
418
+ own(data, name, result.data);
419
+ }
420
+ }
421
+ if (def.mode !== "strip") {
422
+ for (const [name, next] of Object.entries(value)) {
423
+ if (!Object.hasOwn(def.shape, name)) {
424
+ if (def.mode === "strict") {
425
+ (issues ??= []).push({
426
+ expected: "never",
427
+ path: [...path, name],
428
+ message: "Unexpected key",
429
+ });
430
+ }
431
+ else {
432
+ own(data, name, next);
433
+ }
434
+ }
435
+ }
436
+ }
437
+ return issues ? { issues } : { data };
438
+ };
439
+ }
440
+ case "union":
441
+ return (v, path) => {
442
+ const issues = [];
443
+ for (const schema of def.options) {
444
+ const result = schema.#run(v, path);
445
+ // return as soon as one passes
446
+ if (!result.issues)
447
+ return result;
448
+ append(issues, result.issues);
449
+ }
450
+ return { issues };
451
+ };
452
+ case "optional":
453
+ return (v, path) => v === undefined ? { data: v } : def.inner.#run(v, path);
454
+ case "nullable":
455
+ return (v, path) => v === null ? { data: v } : def.inner.#run(v, path);
456
+ case "nullish":
457
+ return (v, path) => (v == null ? { data: v } : def.inner.#run(v, path));
458
+ case "default":
459
+ return (v, path) => v === undefined ? { data: def.value } : def.inner.#run(v, path);
460
+ case "preprocess":
461
+ return (v, path) => def.inner.#run(def.fn(v), path);
462
+ case "transform":
463
+ return (v, path) => {
464
+ const result = def.inner.#run(v, path);
465
+ return result.issues ? result : { data: def.fn(result.data) };
466
+ };
467
+ case "pipe":
468
+ return (v, path) => {
469
+ const result = def.inner.#run(v, path);
470
+ return result.issues ? result : def.next.#run(result.data, path);
471
+ };
472
+ case "json":
473
+ return (v, path) => {
474
+ const result = def.inner.#run(v, path);
475
+ if (result.issues)
476
+ return result;
477
+ let data;
478
+ try {
479
+ data = JSON.parse(result.data);
480
+ }
481
+ catch {
482
+ return Schema.#issue("JSON", path, def.message);
483
+ }
484
+ return def.schema.#run(data, path);
485
+ };
486
+ case "check": {
487
+ const test = Schema.#test(def.check);
488
+ return (v, path) => {
489
+ const result = def.inner.#run(v, path);
490
+ return result.issues || test(result.data)
491
+ ? result
492
+ : Schema.#issue("refine", path, def.check.message);
493
+ };
494
+ }
495
+ }
496
+ }
497
+ /**
498
+ * @param check Output check
499
+ * @returns Function that returns `false` when the value fails the check
500
+ */
501
+ static #test(check) {
502
+ switch (check.name) {
503
+ // a string has between length / 2 and length code points, count only between
504
+ case "min": {
505
+ const min = Number(check.value);
506
+ return (v) => typeof v === "string"
507
+ ? v.length >= min * 2 ||
508
+ (v.length >= min && Schema.#length(v) >= min)
509
+ : v >= check.value;
510
+ }
511
+ case "max": {
512
+ const max = Number(check.value);
513
+ return (v) => typeof v === "string"
514
+ ? v.length <= max ||
515
+ (v.length <= max * 2 && Schema.#length(v) <= max)
516
+ : v <= check.value;
517
+ }
518
+ case "int":
519
+ return Number.isSafeInteger;
520
+ case "email":
521
+ return (v) => Schema.#emailRegex.test(v);
522
+ case "url":
523
+ return URL.canParse;
524
+ case "uuid":
525
+ return (v) => Schema.#uuidRegex.test(v);
526
+ case "refine":
527
+ return check.fn;
528
+ }
529
+ }
530
+ /**
531
+ * @param value String
532
+ * @returns Number of Unicode code points, a surrogate pair counts once
533
+ */
534
+ static #length(value) {
535
+ let length = value.length;
536
+ for (let i = 0; i < value.length - 1; i++) {
537
+ const code = value.charCodeAt(i);
538
+ if (code >= 0xd800 && code <= 0xdbff) {
539
+ const next = value.charCodeAt(i + 1);
540
+ if (next >= 0xdc00 && next <= 0xdfff) {
541
+ length--;
542
+ i++;
543
+ }
544
+ }
545
+ }
546
+ return length;
547
+ }
548
+ /**
549
+ * Describe a schema as JSON Schema by walking its definition.
550
+ *
551
+ * @param schema Schema to describe
552
+ * @param c Description context
553
+ * @returns Description, optional when its key may be omitted
554
+ */
555
+ static #node(schema, c) {
556
+ const node = Schema.#kind(schema, c);
557
+ const { description } = schema.def;
558
+ return description === undefined
559
+ ? node
560
+ : { ...node, schema: { ...node.schema, description } };
561
+ }
562
+ /**
563
+ * @param schema Schema to describe
564
+ * @param c Context
565
+ * @returns JSON Schema of the schema's kind
566
+ */
567
+ static #kind(schema, c) {
568
+ const { def } = schema;
569
+ switch (def.type) {
570
+ case "unknown":
571
+ // accepts undefined, so the key may be absent
572
+ return { schema: {}, optional: true };
573
+ case "string":
574
+ case "boolean":
575
+ case "number":
576
+ return { schema: { type: def.type } };
577
+ case "bigint":
578
+ case "date":
579
+ case "instance":
580
+ return Schema.#unrepresentable(c, def.type === "instance" ? `${def.class.name} instance` : def.type);
581
+ case "literal":
582
+ return Schema.#values(c, [def.value]);
583
+ case "enum":
584
+ return Schema.#values(c, def.values);
585
+ case "array":
586
+ return {
587
+ schema: { type: "array", items: Schema.#node(def.item, c).schema },
588
+ };
589
+ case "object": {
590
+ const properties = {};
591
+ const required = [];
592
+ for (const [name, schema] of Object.entries(def.shape)) {
593
+ const node = Schema.#node(schema, c);
594
+ const extra = schema[annotate](c.io);
595
+ own(properties, name, { ...node.schema, ...extra });
596
+ // a key with a default may be left out
597
+ if (!node.optional && extra?.default === undefined)
598
+ required.push(name);
599
+ }
600
+ return {
601
+ schema: {
602
+ type: "object",
603
+ properties,
604
+ ...(required.length && { required }),
605
+ // strip accepts unknown input keys but removes them from the output
606
+ ...((def.mode === "strict" ||
607
+ (def.mode === "strip" && c.io === "output")) && {
608
+ additionalProperties: false,
609
+ }),
610
+ },
611
+ };
612
+ }
613
+ case "union": {
614
+ const nodes = def.options.map((schema) => Schema.#node(schema, c));
615
+ return {
616
+ schema: nodes.length === 1
617
+ ? nodes[0].schema
618
+ : { anyOf: nodes.map((node) => node.schema) },
619
+ optional: nodes.some((node) => node.optional),
620
+ };
621
+ }
622
+ case "optional":
623
+ return { ...Schema.#node(def.inner, c), optional: true };
624
+ case "nullable":
625
+ case "nullish": {
626
+ const node = Schema.#node(def.inner, c);
627
+ return {
628
+ schema: { anyOf: [node.schema, { type: "null" }] },
629
+ optional: def.type === "nullish" || node.optional,
630
+ };
631
+ }
632
+ case "default": {
633
+ const node = Schema.#node(def.inner, c);
634
+ if (c.io === "input")
635
+ return {
636
+ schema: Schema.#isJson(def.value)
637
+ ? { ...node.schema, default: def.value }
638
+ : node.schema,
639
+ optional: true,
640
+ };
641
+ // the default is output without validation by the inner schema
642
+ if (def.value === undefined)
643
+ return { schema: node.schema, optional: true };
644
+ if (!def.inner.parse(def.value).issues)
645
+ return { schema: node.schema };
646
+ if (!Schema.#isJson(def.value))
647
+ return Schema.#unrepresentable(c, "Non-JSON default");
648
+ return { schema: { anyOf: [node.schema, { const: def.value }] } };
649
+ }
650
+ case "preprocess":
651
+ // any input, or none, may be preprocessed into a valid value, unless
652
+ // the preprocessor only normalizes, where the input is the value
653
+ return c.io === "input" && !normalizers.has(def.fn)
654
+ ? { schema: {}, optional: true }
655
+ : Schema.#node(def.inner, c);
656
+ case "transform":
657
+ return c.io === "input"
658
+ ? Schema.#node(def.inner, c)
659
+ : Schema.#unrepresentable(c, "Transform output");
660
+ case "pipe":
661
+ return Schema.#node(c.io === "input" ? def.inner : def.next, c);
662
+ case "json": {
663
+ if (c.io === "output")
664
+ return Schema.#node(def.schema, c);
665
+ const node = Schema.#node(def.inner, c);
666
+ return {
667
+ ...node,
668
+ schema: {
669
+ ...node.schema,
670
+ contentMediaType: "application/json",
671
+ // contentSchema was added after draft-07
672
+ ...(c.target === "draft-2020-12" && {
673
+ contentSchema: Schema.#node(def.schema, c).schema,
674
+ }),
675
+ },
676
+ };
677
+ }
678
+ case "check": {
679
+ const node = Schema.#node(def.inner, c);
680
+ // checks constrain the output, so they describe the input only when it is unchanged
681
+ if (c.io === "input" && !Schema.#unchanged(def.inner.def))
682
+ return node;
683
+ return {
684
+ ...node,
685
+ schema: {
686
+ ...node.schema,
687
+ ...Schema.#keywords(def.check, node.schema),
688
+ },
689
+ };
690
+ }
691
+ }
692
+ }
693
+ /**
694
+ * @param def Schema definition
695
+ * @returns `true` when parsing never changes a valid value
696
+ */
697
+ static #unchanged(def) {
698
+ switch (def.type) {
699
+ case "preprocess":
700
+ // a normalizer leaves a valid value as it is
701
+ return normalizers.has(def.fn) && Schema.#unchanged(def.inner.def);
702
+ case "transform":
703
+ case "json":
704
+ return false;
705
+ case "pipe":
706
+ return (Schema.#unchanged(def.inner.def) && Schema.#unchanged(def.next.def));
707
+ case "union":
708
+ return def.options.every((schema) => Schema.#unchanged(schema.def));
709
+ case "optional":
710
+ case "nullable":
711
+ case "nullish":
712
+ case "default":
713
+ case "check":
714
+ return Schema.#unchanged(def.inner.def);
715
+ }
716
+ return true;
717
+ }
718
+ /**
719
+ * @param check Output check
720
+ * @param schema Description being checked
721
+ * @returns JSON Schema keywords equivalent to the check
722
+ */
723
+ static #keywords(check, schema) {
724
+ switch (check.name) {
725
+ case "email":
726
+ case "uuid":
727
+ return { format: check.name };
728
+ case "url":
729
+ return { format: "uri" };
730
+ case "int":
731
+ return schema.type === "number" && { type: "integer" };
732
+ case "min":
733
+ case "max": {
734
+ if (typeof check.value !== "number")
735
+ return;
736
+ const min = check.name === "min";
737
+ const length = schema.type === "string";
738
+ const key = length
739
+ ? `${check.name}Length`
740
+ : (schema.type === "number" || schema.type === "integer") &&
741
+ (min ? "minimum" : "maximum");
742
+ if (!key)
743
+ return;
744
+ // lengths are integers, so fractional bounds round inward
745
+ const value = length
746
+ ? min
747
+ ? Math.max(0, Math.ceil(check.value))
748
+ : Math.floor(check.value)
749
+ : check.value;
750
+ const current = schema[key];
751
+ // repeated bounds all apply, so keep the strictest
752
+ return {
753
+ [key]: typeof current !== "number"
754
+ ? value
755
+ : min
756
+ ? Math.max(current, value)
757
+ : Math.min(current, value),
758
+ };
759
+ }
760
+ }
761
+ }
762
+ /**
763
+ * @param c Description context
764
+ * @param name Unrepresentable schema name
765
+ * @returns `{}` when allowed by `c`
766
+ */
767
+ static #unrepresentable(c, name) {
768
+ if (c.unrepresentable === "any")
769
+ return { schema: {} };
770
+ throw new TypeError(`${name} cannot be represented in JSON Schema`);
771
+ }
772
+ /**
773
+ * @param value Value to check
774
+ * @returns `true` when the value round-trips through JSON unchanged
775
+ */
776
+ static #isJson(value) {
777
+ if (value === null ||
778
+ typeof value === "string" ||
779
+ typeof value === "boolean")
780
+ return true;
781
+ if (typeof value === "number")
782
+ return Number.isFinite(value);
783
+ if (Array.isArray(value))
784
+ return value.every(Schema.#isJson);
785
+ if (typeof value === "object" &&
786
+ Object.getPrototypeOf(value) === Object.prototype)
787
+ return Object.values(value).every(Schema.#isJson);
788
+ return false;
789
+ }
790
+ /**
791
+ * @param c Description context
792
+ * @param values Allowed literal values
793
+ * @returns `const` or `enum` description, optional when `undefined` is allowed
794
+ */
795
+ static #values(c, values) {
796
+ const defined = values.filter((v) => v !== undefined);
797
+ if (!defined.every(Schema.#isJson)) {
798
+ return Schema.#unrepresentable(c, "Non-JSON literal");
799
+ }
800
+ return {
801
+ // `not: {}` matches nothing, so the key must be absent
802
+ schema: defined.length === 0
803
+ ? { not: {} }
804
+ : defined.length === 1
805
+ ? { const: defined[0] }
806
+ : { enum: defined },
807
+ optional: defined.length < values.length,
808
+ };
809
+ }
810
+ optional() {
811
+ return this.derive({ type: "optional", inner: this });
812
+ }
177
813
  nullable() {
178
- return this.derive((v, path) => {
179
- if (v === null)
180
- return { data: null };
181
- return this.parse(v, path);
182
- });
814
+ return this.derive({ type: "nullable", inner: this });
183
815
  }
184
816
  nullish() {
185
- return this.derive((v, path) => {
186
- if (v == null)
187
- return { data: v };
188
- return this.parse(v, path);
817
+ return this.derive({
818
+ type: "nullish",
819
+ inner: this,
189
820
  });
190
821
  }
191
822
  default(value) {
192
- return this.derive((v, path) => {
193
- if (v === undefined)
194
- return { data: value };
195
- return this.parse(v, path);
196
- });
823
+ return this.derive({ type: "default", inner: this, value });
197
824
  }
198
825
  preprocess(fn) {
199
- return this.derive((v, path) => this.parse(fn(v), path));
826
+ return this.derive({ type: "preprocess", inner: this, fn });
200
827
  }
201
828
  transform(fn) {
202
- return this.derive((v, path) => {
203
- const out = this.parse(v, path);
204
- return out.issues ? out : { data: fn(out.data) };
205
- });
829
+ return this.derive({ type: "transform", inner: this, fn });
206
830
  }
207
831
  pipe(next) {
208
- return this.derive((v, path) => {
209
- const result = this.parse(v, path);
210
- return result.issues ? result : next.parse(result.data, path);
211
- });
832
+ return this.derive({ type: "pipe", inner: this, next });
212
833
  }
213
834
  json(schema, message) {
214
- return this.derive((v, path) => {
215
- const result = this.parse(v, path);
216
- if (result.issues)
217
- return result;
218
- let data;
219
- try {
220
- data = JSON.parse(result.data);
221
- }
222
- catch {
223
- return new Schema.AggregateIssue([
224
- new Schema.Issue("JSON", path, message),
225
- ]);
226
- }
227
- return schema.parse(data, path);
228
- });
835
+ return this.derive({ type: "json", inner: this, schema, message });
229
836
  }
230
837
  email(message = "Expected email") {
231
- return this.refine((s) => Schema.#emailRegex.test(s), message);
838
+ return this.#check({ name: "email", message });
839
+ }
840
+ uuid(message = "Expected UUID") {
841
+ return this.#check({ name: "uuid", message });
232
842
  }
233
843
  url(message = "Expected URL") {
234
- return this.refine(URL.canParse, message);
844
+ return this.#check({ name: "url", message });
235
845
  }
236
846
  int(message = "Expected integer") {
237
- return this.refine(Number.isSafeInteger, message);
847
+ return this.#check({ name: "int", message });
238
848
  }
239
- min(value, message = `Expected minimum ${String(value)}`) {
240
- return this.refine((next) => {
241
- return typeof next === "string"
242
- ? next.length >= value
243
- : next >= value;
244
- }, message);
849
+ min(value, message = `Expected minimum ${value}`) {
850
+ return this.#check({ name: "min", value, message });
245
851
  }
246
- max(value, message = `Expected maximum ${String(value)}`) {
247
- return this.refine((next) => {
248
- return typeof next === "string"
249
- ? next.length <= value
250
- : next <= value;
251
- }, message);
852
+ max(value, message = `Expected maximum ${value}`) {
853
+ return this.#check({ name: "max", value, message });
252
854
  }
253
855
  refine(check, message) {
254
- return this.derive((v, path) => {
255
- const out = this.parse(v, path);
256
- return out.issues || check(out.data)
257
- ? out
258
- : new Schema.AggregateIssue([
259
- new Schema.Issue("refine", path, message),
260
- ]);
261
- });
856
+ return this.#check({ name: "refine", fn: check, message });
262
857
  }
263
858
  /**
264
859
  * Accepts any value and presents the data as `unknown`.
@@ -266,7 +861,7 @@ export class Schema {
266
861
  * @returns Unknown schema
267
862
  */
268
863
  static unknown() {
269
- return new Schema((v) => ({ data: v }));
864
+ return new Schema({ type: "unknown" });
270
865
  }
271
866
  /**
272
867
  * Validate an input is a string.
@@ -275,13 +870,7 @@ export class Schema {
275
870
  * @returns String schema
276
871
  */
277
872
  static string(message) {
278
- return new Schema((v, path) => {
279
- return typeof v === "string"
280
- ? { data: v }
281
- : new Schema.AggregateIssue([
282
- new Schema.Issue("string", path, message),
283
- ]);
284
- });
873
+ return new Schema({ type: "string", message });
285
874
  }
286
875
  /**
287
876
  * Validate an input is a `true` or `false` boolean.
@@ -290,13 +879,7 @@ export class Schema {
290
879
  * @returns Boolean schema
291
880
  */
292
881
  static boolean(message) {
293
- return new Schema((v, path) => {
294
- return typeof v === "boolean"
295
- ? { data: v }
296
- : new Schema.AggregateIssue([
297
- new Schema.Issue("boolean", path, message),
298
- ]);
299
- });
882
+ return new Schema({ type: "boolean", message });
300
883
  }
301
884
  /**
302
885
  * Validate an input is a number.
@@ -307,13 +890,7 @@ export class Schema {
307
890
  * @returns Number schema
308
891
  */
309
892
  static number(message) {
310
- return new Schema((v, path) => {
311
- return Number.isFinite(v) // isFinite checks type
312
- ? { data: v }
313
- : new Schema.AggregateIssue([
314
- new Schema.Issue("number", path, message),
315
- ]);
316
- });
893
+ return new Schema({ type: "number", message });
317
894
  }
318
895
  /**
319
896
  * Validate an input is a big integer.
@@ -322,13 +899,18 @@ export class Schema {
322
899
  * @returns Big integer schema
323
900
  */
324
901
  static bigint(message) {
325
- return new Schema((v, path) => {
326
- return typeof v === "bigint"
327
- ? { data: v }
328
- : new Schema.AggregateIssue([
329
- new Schema.Issue("bigint", path, message),
330
- ]);
331
- });
902
+ return new Schema({ type: "bigint", message });
903
+ }
904
+ /**
905
+ * Validate an input is a valid `Date`.
906
+ *
907
+ * Rejects invalid dates like `new Date("")`.
908
+ *
909
+ * @param message Issue message when invalid
910
+ * @returns Date schema
911
+ */
912
+ static date(message) {
913
+ return new Schema({ type: "date", message });
332
914
  }
333
915
  /**
334
916
  * @template L Literal type
@@ -337,11 +919,7 @@ export class Schema {
337
919
  * @returns Literal schema
338
920
  */
339
921
  static literal(literal, message) {
340
- return new Schema((v, path) => {
341
- return v === literal
342
- ? { data: literal }
343
- : new Schema.AggregateIssue([new Schema.Issue(literal, path, message)]);
344
- });
922
+ return new Schema({ type: "literal", value: literal, message });
345
923
  }
346
924
  /**
347
925
  * Validates that the input is strictly equal (`===`) to one of the allowed
@@ -353,15 +931,7 @@ export class Schema {
353
931
  * @returns Enum schema
354
932
  */
355
933
  static enum(allowed, message) {
356
- return new Schema((v, path) => {
357
- for (const a of allowed) {
358
- if (v === a)
359
- return { data: a };
360
- }
361
- return new Schema.AggregateIssue([
362
- new Schema.Issue(allowed.map((v) => JSON.stringify(v)).join(" | "), path, message),
363
- ]);
364
- });
934
+ return new Schema({ type: "enum", values: allowed, message });
365
935
  }
366
936
  /**
367
937
  * Tries each schema in order and returns the first successfully parsed result.
@@ -371,17 +941,9 @@ export class Schema {
371
941
  * @returns Union schema
372
942
  */
373
943
  static union(schemas) {
374
- return new Schema((v, path) => {
375
- const issues = [];
376
- for (const schema of schemas) {
377
- const result = schema.parse(v, path);
378
- if (!result.issues) {
379
- // return as soon as one passes
380
- return result;
381
- }
382
- issues.push(...result.issues);
383
- }
384
- return new Schema.AggregateIssue(issues);
944
+ return new Schema({
945
+ type: "union",
946
+ options: schemas,
385
947
  });
386
948
  }
387
949
  /**
@@ -393,11 +955,7 @@ export class Schema {
393
955
  * @returns Validated instance
394
956
  */
395
957
  static instance(constructor, message) {
396
- return new Schema((v, path) => v instanceof constructor
397
- ? { data: v }
398
- : new Schema.AggregateIssue([
399
- new Schema.Issue(constructor.name, path, message),
400
- ]));
958
+ return new Schema({ type: "instance", class: constructor, message });
401
959
  }
402
960
  /**
403
961
  * Validates that the input is an array and parses each item.
@@ -408,27 +966,7 @@ export class Schema {
408
966
  * @returns Array schema
409
967
  */
410
968
  static array(schema, message) {
411
- return new Schema((v, path) => {
412
- if (!Array.isArray(v)) {
413
- return new Schema.AggregateIssue([
414
- new Schema.Issue("Array", path, message),
415
- ]);
416
- }
417
- const data = [];
418
- const issues = [];
419
- for (let i = 0; i < v.length; i++) {
420
- const result = schema.parse(v[i], [...path, i]);
421
- if (result.issues) {
422
- issues.push(...result.issues);
423
- }
424
- else {
425
- data.push(result.data);
426
- }
427
- }
428
- if (issues.length)
429
- return new Schema.AggregateIssue(issues);
430
- return { data };
431
- });
969
+ return new Schema({ type: "array", item: schema, message });
432
970
  }
433
971
  /**
434
972
  * Validates each key in the shape and returns a new object of parsed outputs.
@@ -457,48 +995,24 @@ class ObjectSchema extends Schema {
457
995
  *
458
996
  * @param shape Object shape
459
997
  * @param mode Object parsing mode
460
- */
461
- constructor(shape, mode = "strip") {
462
- super((value, path) => {
463
- if (value == null || typeof value !== "object" || Array.isArray(value)) {
464
- return new Schema.AggregateIssue([new Schema.Issue("Object", path)]);
465
- }
466
- const data = {};
467
- const issues = [];
468
- for (const [name, schema] of Object.entries(shape)) {
469
- const result = schema.parse(value[name], [
470
- ...path,
471
- name,
472
- ]);
473
- if (result.issues) {
474
- issues.push(...result.issues);
475
- }
476
- else if (result.data !== undefined) {
477
- data[name] = result.data;
478
- }
479
- }
480
- if (mode !== "strip") {
481
- const names = new Set(Object.keys(shape));
482
- for (const [name, next] of Object.entries(value)) {
483
- if (!names.has(name)) {
484
- if (mode === "strict") {
485
- issues.push(new Schema.Issue("never", [...path, name], "Unexpected key"));
486
- }
487
- else {
488
- data[name] = next;
489
- }
490
- }
491
- }
492
- }
493
- return issues.length
494
- ? new Schema.AggregateIssue(issues)
495
- : { data };
998
+ * @param description Description from `describe()`
999
+ */
1000
+ constructor(shape, mode = "strip", description) {
1001
+ super({
1002
+ type: "object",
1003
+ shape,
1004
+ mode,
1005
+ ...(description !== undefined && { description }),
496
1006
  });
497
1007
  this.shape = shape;
498
1008
  this.#mode = mode;
499
1009
  }
1010
+ describe(text) {
1011
+ // still an object schema, which `derive` would not make
1012
+ return new ObjectSchema(this.shape, this.#mode, text);
1013
+ }
500
1014
  extend(extra) {
501
- return new ObjectSchema(ShapeUtil.extend(this.shape, extra instanceof ObjectSchema ? extra.shape : extra), this.#mode);
1015
+ return new ObjectSchema(ShapeUtil.extend(this.shape, extra instanceof ObjectSchema ? extra.shape : extra), this.#mode, this.def.description);
502
1016
  }
503
1017
  /**
504
1018
  * Keep only selected field names.
@@ -508,7 +1022,7 @@ class ObjectSchema extends Schema {
508
1022
  * @returns New object schema with only selected keys
509
1023
  */
510
1024
  pick(names) {
511
- return new ObjectSchema(ShapeUtil.pick(this.shape, names), this.#mode);
1025
+ return new ObjectSchema(ShapeUtil.pick(this.shape, names), this.#mode, this.def.description);
512
1026
  }
513
1027
  /**
514
1028
  * Remove selected field names.
@@ -518,7 +1032,7 @@ class ObjectSchema extends Schema {
518
1032
  * @returns New object schema without selected keys
519
1033
  */
520
1034
  omit(names) {
521
- return new ObjectSchema(ShapeUtil.omit(this.shape, names), this.#mode);
1035
+ return new ObjectSchema(ShapeUtil.omit(this.shape, names), this.#mode, this.def.description);
522
1036
  }
523
1037
  /**
524
1038
  * Reject unknown keys during parsing.
@@ -526,7 +1040,7 @@ class ObjectSchema extends Schema {
526
1040
  * @returns New object schema in strict mode
527
1041
  */
528
1042
  strict() {
529
- return new ObjectSchema(this.shape, "strict");
1043
+ return new ObjectSchema(this.shape, "strict", this.def.description);
530
1044
  }
531
1045
  /**
532
1046
  * Preserve unknown keys during parsing.
@@ -534,787 +1048,6 @@ class ObjectSchema extends Schema {
534
1048
  * @returns New object schema in loose mode
535
1049
  */
536
1050
  loose() {
537
- return new ObjectSchema(this.shape, "loose");
538
- }
539
- }
540
- /**
541
- * Form schema with JSX rendering capabilities.
542
- *
543
- * Parses `FormData` or `URLSearchParams` and generates form field
544
- * components.
545
- *
546
- * @template Shape Form field shape type
547
- */
548
- export class Form {
549
- /** Query param keys ordered as `[return, form]`. */
550
- static params = ["_return", "_form"];
551
- /** Maximum encoded state size in bytes. */
552
- static #maxStateBytes = 4 * Size.kb;
553
- /** Maximum serialized size for a single persisted value. */
554
- static #maxValueChars = 512;
555
- /** Schema used to validate persisted form values. */
556
- static #valueSchema = Schema.union([
557
- Schema.string(),
558
- Schema.number(),
559
- Schema.boolean(),
560
- Schema.array(Schema.string()),
561
- ]);
562
- /** Form id. */
563
- #id;
564
- /** Field definitions. */
565
- shape;
566
- /** Field names in definition order. */
567
- names;
568
- /** Maximum expected multipart parts derived from field cardinality. */
569
- parts;
570
- /**
571
- * Create a new form schema validator.
572
- *
573
- * @param shape Form fields
574
- */
575
- constructor(shape) {
576
- this.shape = shape;
577
- this.names = Object.keys(this.shape);
578
- this.#id = Checksum.djb2(this.names.join());
579
- this.parts = Object.values(this.shape).reduce((sum, field) => sum + field.parts, 0);
580
- }
581
- /**
582
- * Merge `extra` into the current fields.
583
- *
584
- * @template E Extra field shape type
585
- * @param extra Extra fields or form schema to merge
586
- * @returns New form schema with merged fields
587
- */
588
- extend = (extra) => Form.from(ShapeUtil.extend(this.shape, extra instanceof Form ? extra.shape : extra));
589
- /**
590
- * Keep only selected field names.
591
- *
592
- * @template N Selected field names
593
- * @param names Non-empty list of field names to keep
594
- * @returns New form schema with only selected fields
595
- */
596
- pick = (names) => Form.from(ShapeUtil.pick(this.shape, names));
597
- /**
598
- * Remove selected field names.
599
- *
600
- * @template N Field names to remove
601
- * @param names Non-empty list of field names to remove
602
- * @returns New form schema without selected fields
603
- */
604
- omit = (names) => Form.from(ShapeUtil.omit(this.shape, names));
605
- /**
606
- * @param name Unexpected form field name
607
- * @param path Parent path
608
- * @returns Schema issue for unexpected form field names
609
- */
610
- #unexpected(name, path = []) {
611
- return new Schema.Issue("known form data name", [...path, name], "Unexpected form data name");
612
- }
613
- /**
614
- * Sanitizes render-state values by removing unsupported or oversized entries.
615
- *
616
- * @param values Candidate values to keep
617
- * @param persist When `true`, only allow fields marked with `.persist()`
618
- * @returns Sanitized values
619
- */
620
- #sanitize(values, persist = true) {
621
- const sanitized = {};
622
- if (values) {
623
- for (const [name, value] of Object.entries(values)) {
624
- const field = this.shape[name];
625
- if (field &&
626
- field.type !== "file" &&
627
- (!persist || FieldSchema.persisted(field)) &&
628
- value != null) {
629
- const result = Form.#valueSchema.parse(value);
630
- if (!result.issues &&
631
- JSON.stringify(result.data).length <= Form.#maxValueChars) {
632
- sanitized[name] = result.data;
633
- }
634
- }
635
- }
636
- if (Object.keys(sanitized).length)
637
- return sanitized;
638
- }
639
- }
640
- /**
641
- * Decode form state from input.
642
- *
643
- * @param stateInput Current page URL
644
- */
645
- #decode(stateInput) {
646
- if (stateInput) {
647
- const values = this.#sanitize(this.names.reduce((data, name) => {
648
- if (stateInput.searchParams.has(name)) {
649
- const value = FieldSchema.read(this.shape[name], stateInput.searchParams, name);
650
- if (value != null)
651
- data[name] = value;
652
- }
653
- return data;
654
- }, {}), false);
655
- const encoded = stateInput.searchParams.get(Form.params[1]);
656
- if (encoded && encoded.length <= Form.#maxStateBytes * 2) {
657
- try {
658
- const result = Schema.string()
659
- .json(Schema.object({
660
- id: Schema.literal(this.#id),
661
- issues: Schema.array(Schema.object({
662
- expected: Schema.string(),
663
- path: Schema.array(Schema.union([Schema.string(), Schema.number()])),
664
- message: Schema.string(),
665
- }).transform((issue) => new Schema.Issue(issue.expected, issue.path, issue.message))).optional(),
666
- values: Schema.object(this.names.reduce((shape, name) => {
667
- shape[name] = Form.#valueSchema.optional();
668
- return shape;
669
- }, {})).optional(),
670
- }))
671
- .parse(Codec.decode(Codec.Base64Url.decode(encoded)));
672
- if (result.data?.id === this.#id) {
673
- const current = this.#sanitize(result.data.values);
674
- return {
675
- ...result.data,
676
- values: (values || current) && { ...values, ...current },
677
- };
678
- }
679
- }
680
- catch { }
681
- }
682
- return values && { id: this.#id, values };
683
- }
684
- }
685
- /**
686
- * Parse and validate form data.
687
- *
688
- * @param source FormData, URLSearchParams, or Multipart to parse
689
- * @param path Internal path reference
690
- * @returns Parsed result
691
- */
692
- parse = async (source, path = []) => {
693
- const data = {};
694
- const issues = [];
695
- const values = {};
696
- let form;
697
- let stream;
698
- if (source instanceof Multipart) {
699
- form = new FormData();
700
- const iter = source[Symbol.asyncIterator]();
701
- let current;
702
- while ((current = await iter.next()) && !current.done) {
703
- const part = current.value;
704
- if (part.name) {
705
- const field = this.shape[part.name];
706
- if (!field) {
707
- issues.push(this.#unexpected(part.name, path));
708
- }
709
- else if (field.streaming) {
710
- // expose current and rest of the parts to the user
711
- stream = (async function* () {
712
- try {
713
- // have to yield the current part first
714
- // this is why the multipart can't be passed directly
715
- yield part;
716
- let next;
717
- while ((next = await iter.next()) && !next.done) {
718
- yield next.value;
719
- }
720
- }
721
- finally {
722
- try {
723
- await iter.return?.();
724
- }
725
- catch { }
726
- }
727
- })();
728
- break;
729
- }
730
- else {
731
- form.append(part.name, await part.value());
732
- }
733
- }
734
- }
735
- }
736
- else if (source instanceof FormData) {
737
- form = source;
738
- for (const name of new Set(source.keys())) {
739
- if (!this.shape[name])
740
- issues.push(this.#unexpected(name, path));
741
- }
742
- }
743
- else {
744
- // allow passthrough for URLSearchParams
745
- form = source;
746
- }
747
- for (const [name, field] of Object.entries(this.shape)) {
748
- if (!field.streaming) {
749
- const value = FieldSchema.read(field, form, name);
750
- const result = field.parse(value, [...path, name]);
751
- if (result.issues) {
752
- issues.push(...result.issues);
753
- }
754
- else if (result.data !== undefined) {
755
- data[name] = result.data;
756
- }
757
- if (FieldSchema.persisted(field) && value != null) {
758
- values[name] = value;
759
- }
760
- }
761
- }
762
- if (issues.length) {
763
- const result = new Schema.AggregateIssue(issues, this.#sanitize(values));
764
- let search;
765
- if (result.values) {
766
- // trim persisted values until the encoded state fits
767
- for (let i = this.names.length; i >= 0; i--) {
768
- // skip on the first time - try to encode everything first
769
- if (i !== this.names.length)
770
- delete result.values[this.names[i]];
771
- const state = Codec.encode(JSON.stringify({
772
- issues: result.issues,
773
- id: this.#id,
774
- ...(Object.keys(result.values).length
775
- ? { values: result.values }
776
- : {}),
777
- }));
778
- if (state.byteLength <= Form.#maxStateBytes) {
779
- search = [[Form.params[1], Codec.Base64Url.encode(state)]];
780
- break;
781
- }
782
- }
783
- }
784
- else {
785
- // fall back to issues-only state when nothing persisted.
786
- const state = Codec.encode(JSON.stringify({
787
- issues: result.issues,
788
- id: this.#id,
789
- }));
790
- if (state.byteLength <= Form.#maxStateBytes) {
791
- search = [[Form.params[1], Codec.Base64Url.encode(state)]];
792
- }
793
- }
794
- if (stream) {
795
- // invalid result does not expose streamed parts, drain
796
- try {
797
- for await (const _ of stream)
798
- ;
799
- }
800
- catch { }
801
- }
802
- return Object.assign(result, { search });
803
- }
804
- return { data: data, stream };
805
- };
806
- /**
807
- * Render a single form field.
808
- *
809
- * @param props Component props
810
- * @example
811
- *
812
- * ```tsx
813
- * <User.Field name="username" />
814
- * ```
815
- */
816
- Field = (props) => this.shape[props.name].render({
817
- ...props,
818
- state: this.#decode(props.state),
819
- });
820
- /**
821
- * Render all form fields.
822
- *
823
- * @param props Component props
824
- * @example
825
- *
826
- * ```tsx
827
- * <User.Fields />
828
- * ```
829
- */
830
- Fields = (props = // partial because name is not required
831
- {}) => {
832
- const state = this.#decode(props.state); // pulled out to not call each map iteration
833
- return this.names.map((name) => this.shape[name].render({ ...props, name, state }));
834
- };
835
- /**
836
- * Access bound sub-components for a field.
837
- *
838
- * @template N Type of the form field name
839
- * @param props Field component props
840
- * @example
841
- *
842
- * ```tsx
843
- * const Radio = User.component({ name: "radio" });
844
- *
845
- * <Radio.Label />
846
- * <Radio.Control />
847
- * ```
848
- */
849
- component = (props) => this.shape[props.name].component({
850
- ...props,
851
- state: this.#decode(props.state),
852
- });
853
- /**
854
- * Create a Form from a shape or use another Form.
855
- *
856
- * @template S Form field shape type
857
- * @param shape Form fields
858
- */
859
- static from(shape) {
860
- return shape instanceof Form ? shape : new Form(shape);
861
- }
862
- }
863
- /**
864
- * Represents a form field with parsing logic and rendering metadata.
865
- *
866
- * @template Output Output type of the field
867
- * @template Tag Tag name
868
- * @template Type Input type
869
- * @template Values Persisted field value type
870
- * @template Stream If the field should be streamed as a part
871
- */
872
- class FieldSchema extends Schema {
873
- /** Read the value from form data */
874
- #read;
875
- /** Field type */
876
- type;
877
- // tag and values are public so emitted .d.ts preserves
878
- // field discriminants for correct types
879
- /** Field tag */
880
- tag;
881
- /** Field values */
882
- values;
883
- /** Maximum expected multipart part count for this field name. */
884
- parts;
885
- /** If the field should be streamed as a part */
886
- streaming;
887
- /** If the field should persist invalid-state values. */
888
- #persist;
889
- /** Field options */
890
- #options;
891
- /**
892
- * Create a new field.
893
- *
894
- * @param options Field options
895
- * @param parse How to validate the input
896
- * @param read How to read the form data
897
- * @param parts Maximum expected multipart parts for this field
898
- * @param stream If this field should be streamed as a multipart part
899
- * @param persist If this field should persist invalid state values
900
- */
901
- constructor(options, parse,
902
- // default to a single value, treating blank as missing
903
- read = (data, name) => data.get(name) || undefined, parts = 1, stream, persist = false) {
904
- super(parse instanceof Schema ? parse.parse : parse);
905
- this.#options = options;
906
- this.tag = (options.tag ?? "input");
907
- this.values = options.values;
908
- this.#read = read;
909
- this.type = options.props?.type;
910
- this.parts = parts;
911
- this.streaming = stream;
912
- this.#persist = persist;
913
- }
914
- /**
915
- * @param field Field instance
916
- * @param data Form data source
917
- * @param name HTML name attribute
918
- * @returns Raw field input
919
- */
920
- static read(field, data, name) {
921
- return field.#read(data, name);
922
- }
923
- /**
924
- * Stream this field as a multipart request `Part`.
925
- *
926
- * @returns Part field
927
- */
928
- stream() {
929
- return new FieldSchema(this.#options, this.parse, this.#read, this.parts, true, this.#persist);
930
- }
931
- persist() {
932
- return new FieldSchema(this.#options, this.parse, this.#read, this.parts, this.streaming, true);
933
- }
934
- /**
935
- * Derive a new Field from the current instance type.
936
- *
937
- * @template O Output type of the new Field
938
- * @param parse Parse function that validates and transforms input
939
- * @returns New `Field` instance
940
- */
941
- derive(parse) {
942
- return new FieldSchema(this.#options, parse, this.#read, this.parts, this.streaming, this.#persist);
943
- }
944
- component({ state, ...props }) {
945
- const value = state?.values?.[props.name];
946
- const issue = state?.issues?.find((i) => i.path[0] === props.name);
947
- const issueId = issue && `${props.name}-issue`;
948
- const hidden = this.type === "hidden";
949
- const { label = props.name, ...control } = {
950
- id: props.name,
951
- autofocus: issue && state?.issues?.[0] === issue,
952
- "aria-invalid": issue && "true",
953
- "aria-describedby": issueId,
954
- ...this.#options.props,
955
- ...props,
956
- };
957
- const Issue = (data = {}) => issue && // render nothing if no issue
958
- !hidden &&
959
- jsx("p", {
960
- id: issueId,
961
- children: issue.message,
962
- "data-issue": issue && state.issues.indexOf(issue), // issue index starting from 0
963
- ...data,
964
- });
965
- if (this.values && this.tag !== "select") {
966
- // radio/checkboxes
967
- // make multiple ids for the group so all don't have the same id
968
- const groupId = (value) => `${control.name}-${value}`.toLowerCase();
969
- const Control = (data) => jsx(this.tag, {
970
- ...control,
971
- id: groupId(data.value),
972
- // autofocus only the first input in the group
973
- autofocus: control.autofocus && data.value === this.values?.[0],
974
- checked: Array.isArray(value)
975
- ? value.includes(data.value) // checkboxes
976
- : value === data.value, // radio
977
- ...data,
978
- });
979
- const Label = ({ value, ...rest }) => jsx("label", { for: groupId(value), children: value, ...rest });
980
- return {
981
- Issue,
982
- Label,
983
- Control,
984
- Root: (data = {}) => jsx("fieldset", data),
985
- Option: ({ value, ...rest }) => jsx("div", {
986
- children: [Control({ value }), Label({ value })],
987
- ...rest,
988
- }),
989
- Legend: (data = {}) => jsx("legend", { children: label, ...data }),
990
- ...this,
991
- };
992
- }
993
- return {
994
- Issue,
995
- Root: (data = {}) => hidden ? Fragment(data) : jsx("div", data),
996
- Label: (data = {}) => !hidden && jsx("label", { for: control.id, children: label, ...data }),
997
- Control: (data) => {
998
- const attrs = { ...control, ...data };
999
- if (value !== undefined) {
1000
- if (this.tag === "textarea") {
1001
- attrs.children = value;
1002
- }
1003
- else if (this.tag === "input") {
1004
- if (this.type === "checkbox") {
1005
- attrs.checked = value;
1006
- }
1007
- else {
1008
- attrs.value = value;
1009
- }
1010
- }
1011
- }
1012
- return jsx(this.tag, attrs);
1013
- },
1014
- Option:
1015
- // select
1016
- this.values &&
1017
- ((data) => jsx("option", {
1018
- children: data.value,
1019
- selected: Array.isArray(value)
1020
- ? value.includes(data.value) // multiselect
1021
- : value === data.value,
1022
- ...data,
1023
- })),
1024
- ...this,
1025
- };
1026
- }
1027
- /**
1028
- * @template S Form shape type
1029
- * @param props Field control props
1030
- * @returns Input group component
1031
- */
1032
- #Group(props) {
1033
- const c = this.component(props);
1034
- return c.Root({
1035
- children: [
1036
- // @ts-expect-error - `#Group` runs for grouped inputs, includes `Legend` with label
1037
- c.Legend(),
1038
- this.values.map((value) => {
1039
- return jsx("div", {
1040
- children: [c.Control({ value }), c.Label({ value })],
1041
- });
1042
- }),
1043
- c.Issue(),
1044
- ],
1045
- });
1046
- }
1047
- /**
1048
- * @template S Form shape type
1049
- * @param props Field control props
1050
- * @returns Select component
1051
- */
1052
- #Select(props) {
1053
- const c = this.component(props);
1054
- return c.Root({
1055
- children: [
1056
- c.Label(),
1057
- c.Control({
1058
- children: this.values.map((value) => c.Option({ value })),
1059
- }),
1060
- c.Issue(),
1061
- ],
1062
- });
1063
- }
1064
- /**
1065
- * @template S Form shape type
1066
- * @param props Field control props
1067
- * @returns Default input component
1068
- */
1069
- #Input(props) {
1070
- const c = this.component(props);
1071
- return c.Root({ children: [c.Label(), c.Control(), c.Issue()] });
1072
- }
1073
- /**
1074
- * @template S Form shape type
1075
- * @param props Field control props including `name` of the field to render
1076
- * @returns Component that renders the HTML field with default structure
1077
- */
1078
- render(props) {
1079
- if (this.values) {
1080
- if (this.tag === "select")
1081
- return this.#Select(props);
1082
- return this.#Group(props);
1083
- }
1084
- return this.#Input(props);
1085
- }
1086
- /**
1087
- * @param field Field definition
1088
- * @returns `true` when the field persists invalid-state values
1089
- */
1090
- static persisted(field) {
1091
- return field.#persist;
1092
- }
1093
- }
1094
- /** Field factory functions */
1095
- export class Field {
1096
- // this is used instead of the defaults for example "Expected string"
1097
- // since "string" doesn't make sense to end users
1098
- /** Default message for required field values. */
1099
- static #required = "Required field";
1100
- /**
1101
- * @param value Raw form entry
1102
- * @returns `true` when the file input contains a real file value
1103
- */
1104
- static #nonEmptyFile(value) {
1105
- return value instanceof File && (value.name !== "" || value.size > 0);
1106
- }
1107
- /**
1108
- * @param data Form data
1109
- * @param name HTML name attribute
1110
- * @returns Field values or `undefined` when missing
1111
- */
1112
- static #readMany(data, name) {
1113
- const value = data.getAll(name);
1114
- return value.length ? value : undefined;
1115
- }
1116
- /**
1117
- * @param props Input props
1118
- * @returns Generic input field
1119
- */
1120
- static #input(props) {
1121
- return new FieldSchema({ props }, Schema.string(Field.#required));
1122
- }
1123
- /**
1124
- * @param props Input props
1125
- * @returns Text input field
1126
- */
1127
- static text(props) {
1128
- return Field.#input({ ...props, type: "text" });
1129
- }
1130
- /**
1131
- * @param props Input props
1132
- * @returns Password input field
1133
- */
1134
- static password(props) {
1135
- return Field.#input({ ...props, type: "password" });
1136
- }
1137
- /**
1138
- * @param props Input props
1139
- * @returns Search input field
1140
- */
1141
- static search(props) {
1142
- return Field.#input({ ...props, type: "search" });
1143
- }
1144
- /**
1145
- * @param props Input props
1146
- * @returns Telephone input field
1147
- */
1148
- static tel(props) {
1149
- return Field.#input({ ...props, type: "tel" });
1150
- }
1151
- /**
1152
- * @param props Input props
1153
- * @returns Color input field
1154
- */
1155
- static color(props) {
1156
- return Field.#input({ ...props, type: "color" });
1157
- }
1158
- /**
1159
- * @param props Input props
1160
- * @returns Hidden input field
1161
- */
1162
- static hidden(props) {
1163
- return Field.#input({ ...props, type: "hidden" });
1164
- }
1165
- /**
1166
- * @param props Input props
1167
- * @returns Date input field
1168
- */
1169
- static date(props) {
1170
- return Field.#input({ ...props, type: "date" });
1171
- }
1172
- /**
1173
- * @param props Input props
1174
- * @returns Datetime input field
1175
- */
1176
- static datetime(props) {
1177
- return Field.#input({ ...props, type: "datetime-local" });
1178
- }
1179
- /**
1180
- * @param props Input props
1181
- * @returns Month input field
1182
- */
1183
- static month(props) {
1184
- return Field.#input({ ...props, type: "month" });
1185
- }
1186
- /**
1187
- * @param props Input props
1188
- * @returns Week input field
1189
- */
1190
- static week(props) {
1191
- return Field.#input({ ...props, type: "week" });
1192
- }
1193
- /**
1194
- * @param props Input props
1195
- * @returns Time input field
1196
- */
1197
- static time(props) {
1198
- return Field.#input({ ...props, type: "time" });
1199
- }
1200
- /**
1201
- * Validates email string.
1202
- *
1203
- * @param props Input props
1204
- * @param message Issue message when invalid
1205
- * @returns Email input field
1206
- */
1207
- static email(props, message) {
1208
- return new FieldSchema({ props: { ...props, type: "email" } }, Schema.string(Field.#required).email(message));
1209
- }
1210
- /**
1211
- * Validates parsable URL.
1212
- *
1213
- * @param props Input props
1214
- * @param message Issue message when invalid
1215
- * @returns URL input field
1216
- */
1217
- static url(props, message) {
1218
- return new FieldSchema({ props: { ...props, type: "url" } }, Schema.string(Field.#required).url(message));
1219
- }
1220
- /**
1221
- * @param props Input props
1222
- * @returns Input field
1223
- */
1224
- static #number(props) {
1225
- return new FieldSchema({ props }, Schema.number(Field.#required).preprocess((value) =>
1226
- // form submissions read numeric controls as strings
1227
- value == null || value === "" ? undefined : Number(value)));
1228
- }
1229
- /**
1230
- * Coerces to number.
1231
- *
1232
- * @param props Input props
1233
- * @returns Number input field
1234
- */
1235
- static number(props) {
1236
- return Field.#number({ ...props, type: "number" });
1237
- }
1238
- /**
1239
- * Coerces to number.
1240
- *
1241
- * @param props Input props
1242
- * @returns Range input field
1243
- */
1244
- static range(props) {
1245
- return Field.#number({ ...props, type: "range" });
1246
- }
1247
- /**
1248
- * - unchecked => key missing => `false`
1249
- * - checked => key present => `true`
1250
- *
1251
- * @param props Input props
1252
- * @returns Checkbox input field
1253
- */
1254
- static checkbox(props) {
1255
- return new FieldSchema({ props: { ...props, type: "checkbox" } }, Schema.boolean(), (formData, name) => formData.has(name));
1256
- }
1257
- /**
1258
- * @param props Input props
1259
- * @returns File input field
1260
- */
1261
- static file(props) {
1262
- return new FieldSchema({ props: { ...props, type: "file" } }, Schema.instance(File, Field.#required), (data, name) => {
1263
- const value = data.get(name);
1264
- return (Field.#nonEmptyFile(value) && value) || undefined;
1265
- });
1266
- }
1267
- /**
1268
- * @param props Input props
1269
- * @returns Multiple file input field
1270
- */
1271
- static files(props) {
1272
- return new FieldSchema({ props: { ...props, type: "file", multiple: true } }, Schema.array(Schema.instance(File, Field.#required), Field.#required), (data, name) => {
1273
- const value = data.getAll(name).filter(Field.#nonEmptyFile);
1274
- return value.length ? value : undefined;
1275
- }, Infinity);
1276
- }
1277
- /**
1278
- * @template V Value type
1279
- * @param values Checkbox values
1280
- * @param props Input props
1281
- * @returns Checkbox group input field
1282
- */
1283
- static checkboxes(values, props) {
1284
- return new FieldSchema({ values, props: { ...props, type: "checkbox" } }, Schema.array(Schema.enum(values, Field.#required), Field.#required), Field.#readMany, values.length);
1285
- }
1286
- /**
1287
- * @template V Value type
1288
- * @param values Radio button values
1289
- * @param props Input props
1290
- * @returns Radio group input field
1291
- */
1292
- static radio(values, props) {
1293
- return new FieldSchema({ values, props: { ...props, type: "radio" } }, Schema.enum(values, Field.#required));
1294
- }
1295
- /**
1296
- * @param props Textarea props
1297
- * @returns Textarea field
1298
- */
1299
- static textarea(props) {
1300
- return new FieldSchema({ tag: "textarea", props }, Schema.string(Field.#required));
1301
- }
1302
- /**
1303
- * @template V Value type
1304
- * @param values Select options
1305
- * @param props Select props
1306
- * @returns Select field
1307
- */
1308
- static select(values, props) {
1309
- return new FieldSchema({ tag: "select", values, props }, Schema.enum(values, Field.#required));
1310
- }
1311
- /**
1312
- * @template V Value type
1313
- * @param values Select options
1314
- * @param props Select props
1315
- * @returns Multi-select field
1316
- */
1317
- static multiselect(values, props) {
1318
- return new FieldSchema({ tag: "select", values, props: { ...props, multiple: true } }, Schema.array(Schema.enum(values, Field.#required), Field.#required), Field.#readMany, values.length);
1051
+ return new ObjectSchema(this.shape, "loose", this.def.description);
1319
1052
  }
1320
1053
  }