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
@@ -0,0 +1,901 @@
1
+ import { Fragment, jsx } from "../jsx/index.js";
2
+ import { Schema, ShapeUtil, annotate, append, exact, normalizers, own, } from "../schema/index.js";
3
+ import { Checksum, Codec, Size } from "../util/index.js";
4
+ /** Internal protocol for a GET route, to make the form its fields render. */
5
+ export const query = Symbol("query");
6
+ /** A field's components and render, which a route's form reads */
7
+ const component = Symbol("component");
8
+ const render = Symbol("render");
9
+ /**
10
+ * Each route's form, kept apart from the route so its parsing is not part of
11
+ * the route's API.
12
+ */
13
+ export const forms = new WeakMap();
14
+ /**
15
+ * Maximum encoded state size in bytes. Outside the class, since a static that
16
+ * reads another module is a side effect, which keeps `Form` in bundles that
17
+ * only use `Field`.
18
+ */
19
+ const maxStateBytes = 4 * Size.kb;
20
+ /**
21
+ * Form schema with JSX rendering capabilities.
22
+ *
23
+ * Parses `FormData` or `URLSearchParams` and generates form field
24
+ * components.
25
+ *
26
+ * @template Shape Form field shape type
27
+ */
28
+ export class Form {
29
+ /** Query param keys ordered as `[return, form]`. */
30
+ static params = ["_return", "_form"];
31
+ /** Maximum serialized size for a single persisted value. */
32
+ static #maxValueChars = 512;
33
+ /** Schema used to validate persisted form values, see `#value`. */
34
+ static #valueSchema;
35
+ /** Form id. */
36
+ #id;
37
+ /**
38
+ * If search params fill the fields by name, as a GET form submits them.
39
+ * Other forms restore only what they persisted, so a link cannot fill them.
40
+ */
41
+ #query = false;
42
+ /** Field definitions. */
43
+ shape;
44
+ /** Field names in definition order. */
45
+ names;
46
+ /** Maximum expected multipart parts derived from field cardinality. */
47
+ parts;
48
+ /**
49
+ * Create a new form schema validator.
50
+ *
51
+ * @param shape Form fields
52
+ */
53
+ constructor(shape) {
54
+ this.shape = shape;
55
+ this.names = Object.keys(this.shape);
56
+ this.#id = Checksum.djb2(this.names.join());
57
+ this.parts = Object.values(this.shape).reduce((sum, field) => sum + field.parts, 0);
58
+ }
59
+ /**
60
+ * Built on first use: a schema built as the class loads is a side effect,
61
+ * which would keep `Form` in bundles that only use `Field`.
62
+ *
63
+ * @returns Schema used to validate persisted form values
64
+ */
65
+ static #value() {
66
+ return (Form.#valueSchema ??= Schema.union([
67
+ Schema.string(),
68
+ Schema.number(),
69
+ Schema.boolean(),
70
+ Schema.array(Schema.string()),
71
+ ]));
72
+ }
73
+ /** @returns The form for a GET route, whose submission is the page's URL */
74
+ [query]() {
75
+ const form = new Form(this.shape);
76
+ form.#query = true;
77
+ return form;
78
+ }
79
+ /**
80
+ * @param name Form data name
81
+ * @returns The field, own fields only, so a name such as "constructor" has none
82
+ */
83
+ #field(name) {
84
+ return Object.hasOwn(this.shape, name) ? this.shape[name] : undefined;
85
+ }
86
+ /**
87
+ * @param name Unexpected form field name
88
+ * @param path Parent path
89
+ * @returns Schema issue for unexpected form field names
90
+ */
91
+ #unexpected(name, path = []) {
92
+ return new Schema.Issue("known form data name", [...path, name], "Unexpected form data name");
93
+ }
94
+ /**
95
+ * Sanitizes render-state values by removing unsupported or oversized entries.
96
+ *
97
+ * @param values Candidate values to keep
98
+ * @param persist When `true`, only allow fields marked with `.persist()`
99
+ * @param limit When `true`, drop values too long to keep in the URL
100
+ * @returns Sanitized values
101
+ */
102
+ #sanitize(values, persist = true, limit = true) {
103
+ const sanitized = {};
104
+ if (values) {
105
+ for (const [name, value] of Object.entries(values)) {
106
+ const field = this.#field(name);
107
+ if (field &&
108
+ field.type !== "file" &&
109
+ (!persist || FieldSchema.persisted(field)) &&
110
+ value != null) {
111
+ const result = Form.#value().parse(value);
112
+ if (!result.issues &&
113
+ (!limit ||
114
+ JSON.stringify(result.data).length <= Form.#maxValueChars)) {
115
+ own(sanitized, name, result.data);
116
+ }
117
+ }
118
+ }
119
+ if (Object.keys(sanitized).length)
120
+ return sanitized;
121
+ }
122
+ }
123
+ /**
124
+ * Decode form state, over the initial values.
125
+ *
126
+ * @param stateInput Current page URL
127
+ * @param initial Initial values, submitted values take precedence
128
+ */
129
+ #decode(stateInput, initial) {
130
+ const state = this.#restore(stateInput);
131
+ // initial values come from the server, not the URL, so no size limit
132
+ const values = this.#sanitize(initial, false, false);
133
+ if (!values)
134
+ return state;
135
+ return { id: this.#id, ...state, values: { ...values, ...state?.values } };
136
+ }
137
+ /**
138
+ * Restore form state from the URL.
139
+ *
140
+ * @param stateInput Current page URL
141
+ */
142
+ #restore(stateInput) {
143
+ if (stateInput) {
144
+ const { searchParams } = stateInput;
145
+ const values = this.#sanitize((this.#query ? this.names : []).reduce((data, name) => {
146
+ if (searchParams.has(name)) {
147
+ const value = FieldSchema.read(this.shape[name], searchParams, name);
148
+ if (value != null)
149
+ own(data, name, value);
150
+ }
151
+ return data;
152
+ }, {}), false);
153
+ const encoded = searchParams.get(Form.params[1]);
154
+ if (encoded && encoded.length <= maxStateBytes * 2) {
155
+ try {
156
+ const result = Schema.string()
157
+ .json(Schema.object({
158
+ id: Schema.literal(this.#id),
159
+ issues: Schema.array(Schema.object({
160
+ expected: Schema.string(),
161
+ path: Schema.array(Schema.union([Schema.string(), Schema.number()])),
162
+ message: Schema.string(),
163
+ }).transform((issue) => new Schema.Issue(issue.expected, issue.path, issue.message))).optional(),
164
+ values: Schema.object(this.names.reduce((shape, name) => {
165
+ own(shape, name, Form.#value().optional());
166
+ return shape;
167
+ }, {})).optional(),
168
+ }))
169
+ .parse(Codec.decode(Codec.Base64Url.decode(encoded)));
170
+ // valid only for this form, its id is a literal
171
+ if (!result.issues) {
172
+ const current = this.#sanitize(result.data.values);
173
+ return {
174
+ ...result.data,
175
+ values: (values || current) && { ...values, ...current },
176
+ };
177
+ }
178
+ }
179
+ catch { }
180
+ }
181
+ return values && { id: this.#id, values };
182
+ }
183
+ }
184
+ /**
185
+ * Create an invalid result, encoding the issues and persisted values so the
186
+ * next render can show them.
187
+ *
188
+ * @param issues Issues
189
+ * @param values Submitted values, only persisted fields are kept
190
+ * @returns Invalid result with its encoded search param
191
+ */
192
+ #invalid(issues, values) {
193
+ const result = new Schema.AggregateIssue(issues, this.#sanitize(values));
194
+ const persisted = result.values;
195
+ let search;
196
+ // encode everything first, then trim persisted values until the state fits
197
+ for (let i = this.names.length;; i--) {
198
+ const state = Codec.encode(JSON.stringify({
199
+ issues: result.issues,
200
+ id: this.#id,
201
+ // issues only when nothing is persisted
202
+ ...(persisted && Object.keys(persisted).length
203
+ ? { values: persisted }
204
+ : {}),
205
+ }));
206
+ if (state.byteLength <= maxStateBytes) {
207
+ search = [[Form.params[1], Codec.Base64Url.encode(state)]];
208
+ break;
209
+ }
210
+ if (!persisted || !i)
211
+ break;
212
+ delete persisted[this.names[i - 1]];
213
+ }
214
+ return Object.assign(result, { search });
215
+ }
216
+ /**
217
+ * Parse and validate form data.
218
+ *
219
+ * @param source FormData, URLSearchParams, or Multipart to parse
220
+ * @param path Internal path reference
221
+ * @returns Parsed result
222
+ */
223
+ parse = async (source, path = []) => {
224
+ const data = {};
225
+ const issues = [];
226
+ const values = {};
227
+ let form;
228
+ let stream;
229
+ if (source instanceof FormData) {
230
+ form = source;
231
+ for (const name of new Set(source.keys())) {
232
+ if (!this.#field(name))
233
+ issues.push(this.#unexpected(name, path));
234
+ }
235
+ }
236
+ else if (source instanceof URLSearchParams) {
237
+ form = source;
238
+ }
239
+ else {
240
+ // the only other source is a Multipart, read one part at a time
241
+ form = new FormData();
242
+ const iter = source[Symbol.asyncIterator]();
243
+ // a failure ends the parts, which also stops the upload
244
+ try {
245
+ let current;
246
+ while ((current = await iter.next()) && !current.done) {
247
+ const part = current.value;
248
+ if (part.name) {
249
+ const field = this.#field(part.name);
250
+ if (!field) {
251
+ issues.push(this.#unexpected(part.name, path));
252
+ }
253
+ else if (field.streaming) {
254
+ // expose current and rest of the parts to the user
255
+ stream = (async function* () {
256
+ try {
257
+ // have to yield the current part first
258
+ // this is why the multipart can't be passed directly
259
+ yield part;
260
+ let next;
261
+ while ((next = await iter.next()) && !next.done) {
262
+ yield next.value;
263
+ }
264
+ }
265
+ finally {
266
+ try {
267
+ await iter.return?.();
268
+ }
269
+ catch { }
270
+ }
271
+ })();
272
+ break;
273
+ }
274
+ else {
275
+ form.append(part.name, await part.value());
276
+ }
277
+ }
278
+ }
279
+ }
280
+ catch (error) {
281
+ await iter.return?.().catch(() => { });
282
+ throw error;
283
+ }
284
+ }
285
+ for (const [name, field] of Object.entries(this.shape)) {
286
+ if (!field.streaming) {
287
+ const value = FieldSchema.read(field, form, name);
288
+ const result = field.parse(value, [...path, name]);
289
+ if (result.issues) {
290
+ append(issues, result.issues);
291
+ }
292
+ else if (result.data !== undefined) {
293
+ own(data, name, result.data);
294
+ }
295
+ // a cleared field is recorded empty, so it overrides initial values
296
+ if (FieldSchema.persisted(field))
297
+ own(values, name, value ?? "");
298
+ }
299
+ }
300
+ if (issues.length) {
301
+ if (stream) {
302
+ // invalid result does not expose streamed parts, drain
303
+ try {
304
+ for await (const _ of stream)
305
+ ;
306
+ }
307
+ catch { }
308
+ }
309
+ return this.#invalid(issues, values);
310
+ }
311
+ return {
312
+ data: data,
313
+ stream,
314
+ invalid: (messages) => this.#invalid(Object.entries(messages).flatMap(([name, message]) => typeof message === "string"
315
+ ? [new Schema.Issue("valid", [name], message)]
316
+ : []), values),
317
+ };
318
+ };
319
+ /**
320
+ * Render a single form field.
321
+ *
322
+ * @param props Component props
323
+ * @example
324
+ *
325
+ * ```tsx
326
+ * <User.Field name="username" />
327
+ * ```
328
+ */
329
+ Field = ({ values, ...props }) => this.shape[props.name][render]({
330
+ ...props,
331
+ state: this.#decode(props.state, values),
332
+ });
333
+ /**
334
+ * Render all form fields.
335
+ *
336
+ * @param props Component props
337
+ * @example
338
+ *
339
+ * ```tsx
340
+ * <User.Fields />
341
+ * ```
342
+ */
343
+ Fields = ({ values, ...props } = // partial because name is not required
344
+ {}) => {
345
+ const state = this.#decode(props.state, values); // pulled out to not call each map iteration
346
+ return this.names.map((name) => this.shape[name][render]({ ...props, name, state }));
347
+ };
348
+ /**
349
+ * Access bound sub-components for a field.
350
+ *
351
+ * @template N Type of the form field name
352
+ * @param props Field component props
353
+ * @example
354
+ *
355
+ * ```tsx
356
+ * const Radio = User.component({ name: "radio" });
357
+ *
358
+ * <Radio.Label />
359
+ * <Radio.Control />
360
+ * ```
361
+ */
362
+ component = ({ values, ...props }) => this.shape[props.name][component]({
363
+ ...props,
364
+ state: this.#decode(props.state, values),
365
+ });
366
+ }
367
+ /** Default message for a required field */
368
+ const required = "Required field";
369
+ /** Default message for a choice that is not one of the options */
370
+ const choose = "Select an option";
371
+ /**
372
+ * @param value Form data entry
373
+ * @returns `true` for a file a person chose, a browser sends an empty one otherwise
374
+ */
375
+ const chosenFile = (value) => value instanceof File && (value.name !== "" || value.size > 0);
376
+ /**
377
+ * @param data Form data
378
+ * @param name HTML name attribute
379
+ * @returns Every value of the name, or `undefined` when there is none
380
+ */
381
+ const readMany = (data, name) => {
382
+ const value = data.getAll(name);
383
+ return value.length ? value : undefined;
384
+ };
385
+ /**
386
+ * Represents a form field with parsing logic and rendering metadata.
387
+ *
388
+ * @template Output Output type of the field
389
+ * @template Tag Tag name
390
+ * @template Type Input type
391
+ * @template Values Persisted field value type
392
+ * @template Stream If the field should be streamed as a part
393
+ */
394
+ class FieldSchema extends Schema {
395
+ /** Read the value from form data */
396
+ #read;
397
+ /** Field type */
398
+ type;
399
+ // tag and options are public so emitted .d.ts preserves
400
+ // field discriminants for correct types
401
+ /** Field tag */
402
+ tag;
403
+ /** Choices of a select, radio, or checkbox group */
404
+ options;
405
+ /** Maximum expected multipart part count for this field name. */
406
+ parts;
407
+ /** If the field should be streamed as a part */
408
+ streaming;
409
+ /** If the field should persist invalid-state values. */
410
+ #persist;
411
+ /** Field options */
412
+ #config;
413
+ /** If the control can't be left empty, found on first render */
414
+ #requires;
415
+ /**
416
+ * Create a new field.
417
+ *
418
+ * @param options Field options
419
+ * @param schema How to validate the input
420
+ * @param read How to read the form data
421
+ * @param parts Maximum expected multipart parts for this field
422
+ * @param stream If this field should be streamed as a multipart part
423
+ * @param persist If this field should persist invalid state values
424
+ */
425
+ constructor(config, schema,
426
+ // default to a single value, treating blank as missing
427
+ read = (data, name) => data.get(name) || undefined, parts = 1, stream, persist = false) {
428
+ super(schema instanceof Schema ? schema.def : schema);
429
+ this.#config = config;
430
+ this.tag = (config.tag ?? "input");
431
+ this.options = config.options;
432
+ this.#read = read;
433
+ this.type = config.props?.type;
434
+ this.parts = parts;
435
+ this.streaming = stream;
436
+ this.#persist = persist;
437
+ }
438
+ /**
439
+ * @returns `true` when the control can't be left empty
440
+ */
441
+ #required() {
442
+ return (this.#requires ??=
443
+ // a lone checkbox reads as false, and `required` on each box of a
444
+ // group would make every box required
445
+ this.type !== "checkbox" &&
446
+ this.type !== "hidden" &&
447
+ Boolean(this.parse(this.#read(new URLSearchParams(), "")).issues));
448
+ }
449
+ /** How each picker writes its value */
450
+ static #formats = {
451
+ date: "Date as YYYY-MM-DD",
452
+ "datetime-local": "Date and time as YYYY-MM-DDTHH:mm",
453
+ month: "Month as YYYY-MM",
454
+ week: "Week as YYYY-Www, such as 2026-W46",
455
+ time: "Time as HH:mm",
456
+ color: "Color as #rrggbb",
457
+ };
458
+ /**
459
+ * @internal The label people read, which names a terse field such as
460
+ * `dob`, and an unchecked box's default
461
+ * @param io Side of the description
462
+ * @returns Keywords added to the property's JSON Schema
463
+ */
464
+ [annotate](io) {
465
+ const { label } = this.#config;
466
+ const { description } = this;
467
+ // what a browser's picker sends, which a string alone does not say
468
+ const format = FieldSchema.#formats[this.type];
469
+ const described = [description?.replace(/\.$/, ""), format]
470
+ .filter(Boolean)
471
+ .join(". ");
472
+ return {
473
+ ...(label && { title: label }),
474
+ ...(described && { description: described }),
475
+ ...(this.type === "date" && { format: "date" }),
476
+ // a browser leaves an unchecked box out and it reads as false, so
477
+ // input, such as an agent's, may leave it out too
478
+ ...(io === "input" &&
479
+ this.type === "checkbox" &&
480
+ !this.options && { default: false }),
481
+ };
482
+ }
483
+ /**
484
+ * @param field Field instance
485
+ * @param data Form data source
486
+ * @param name HTML name attribute
487
+ * @returns Raw field input
488
+ */
489
+ static read(field, data, name) {
490
+ return field.#read(data, name);
491
+ }
492
+ /**
493
+ * Stream this field as a multipart request `Part`.
494
+ *
495
+ * @returns Part field
496
+ */
497
+ stream() {
498
+ return this.#copy({ stream: true });
499
+ }
500
+ /**
501
+ * Name the field. People read it as the control's label, or a group's
502
+ * legend, and agents as the field's `title`. Without one it is the field's
503
+ * name.
504
+ *
505
+ * ```ts
506
+ * Field.email().label("Email address");
507
+ * ```
508
+ *
509
+ * @param text Label
510
+ * @returns Field with the label
511
+ */
512
+ label(text) {
513
+ return this.#with({ label: text });
514
+ }
515
+ /**
516
+ * Attributes for the field's control wherever it renders, such as a
517
+ * placeholder. Those for one form are passed when it renders.
518
+ *
519
+ * ```ts
520
+ * Field.email().control({ placeholder: "name@example.com" });
521
+ * ```
522
+ *
523
+ * @param attributes Attributes of the control's element
524
+ * @returns Field with the attributes
525
+ */
526
+ control(attributes) {
527
+ return this.#with({
528
+ props: { ...this.#config.props, ...attributes },
529
+ });
530
+ }
531
+ /**
532
+ * @param changes What to change
533
+ * @returns The same field with them
534
+ */
535
+ #with(changes) {
536
+ return this.#copy({ config: { ...this.#config, ...changes } });
537
+ }
538
+ /**
539
+ * @template O Output type of the copy
540
+ * @template S If the copy streams as a part
541
+ * @param changes What the copy changes, the rest is this field's
542
+ * @returns A copy of this field
543
+ */
544
+ #copy({ config = this.#config, def = this.def, stream = this.streaming, persist = this.#persist, }) {
545
+ return new FieldSchema(config, def, this.#read, this.parts, stream, persist);
546
+ }
547
+ // the overloads above are its types
548
+ multiple() {
549
+ const file = this.type === "file";
550
+ const { description, ...def } = this.def;
551
+ // each value is checked as this field checks one, and a description
552
+ // given before describes the field, not each value
553
+ const array = Schema.array((description === undefined
554
+ ? this
555
+ : this.#copy({ def })), file ? required : choose);
556
+ return new FieldSchema({ ...this.#config, props: { ...this.#config.props, multiple: true } }, description === undefined ? array : { ...array.def, description }, file
557
+ ? (data, name) => {
558
+ const files = data.getAll(name).filter(chosenFile);
559
+ return files.length ? files : undefined;
560
+ }
561
+ : readMany, file ? Infinity : this.options.length, this.streaming, this.#persist);
562
+ }
563
+ persist() {
564
+ return this.#copy({ persist: true });
565
+ }
566
+ /**
567
+ * Derive a new Field from the current instance type.
568
+ *
569
+ * @template O Output type of the new Field
570
+ * @param def Definition of the new Field
571
+ * @returns New `Field` instance
572
+ */
573
+ derive(def) {
574
+ return this.#copy({ def });
575
+ }
576
+ [component]({ state, ...props }) {
577
+ const value = state?.values?.[props.name];
578
+ const issue = state?.issues?.find((i) => i.path[0] === props.name);
579
+ const issueId = issue && `${props.name}-issue`;
580
+ const hidden = this.type === "hidden";
581
+ const { label = props.name } = this.#config;
582
+ const { description } = this;
583
+ const descriptionId = description && !hidden ? `${props.name}-description` : undefined;
584
+ const control = {
585
+ id: hidden ? undefined : props.name,
586
+ required: this.#required(),
587
+ autofocus: issue && state?.issues?.[0] === issue,
588
+ "aria-invalid": issue && "true",
589
+ // read with the control: its description, then what is wrong with it
590
+ "aria-describedby": [descriptionId, issueId].filter(Boolean).join(" ") || undefined,
591
+ ...this.#config.props,
592
+ ...props,
593
+ };
594
+ /**
595
+ * @param option Option value
596
+ * @returns `true` when the value has the option
597
+ */
598
+ const chosen = (option) => Array.isArray(value)
599
+ ? value.includes(option) // checkboxes and multiselect
600
+ : value === option; // radio and select
601
+ const Description = (data = {}) => descriptionId && // render nothing without a description
602
+ jsx("p", {
603
+ id: descriptionId,
604
+ children: description,
605
+ "data-description": true,
606
+ ...data,
607
+ });
608
+ const Issue = (data = {}) => issue && // render nothing if no issue
609
+ !hidden &&
610
+ jsx("p", {
611
+ id: issueId,
612
+ children: issue.message,
613
+ "data-issue": issue && state.issues.indexOf(issue), // issue index starting from 0
614
+ ...data,
615
+ });
616
+ if (this.options && this.tag !== "select") {
617
+ // radio/checkboxes
618
+ // make multiple ids for the group so all don't have the same id
619
+ const groupId = (value) => `${control.name}-${value}`.toLowerCase();
620
+ const Control = (data) => jsx(this.tag, {
621
+ ...control,
622
+ id: groupId(data.value),
623
+ // autofocus only the first input in the group
624
+ autofocus: control.autofocus && data.value === this.options?.[0],
625
+ checked: chosen(data.value),
626
+ ...data,
627
+ });
628
+ const Label = ({ value, ...rest }) => jsx("label", { for: groupId(value), children: value, ...rest });
629
+ return {
630
+ Description,
631
+ Issue,
632
+ Label,
633
+ Control,
634
+ Root: (data = {}) => jsx("fieldset", data),
635
+ Option: ({ value, ...rest }) => jsx("div", {
636
+ children: [Control({ value }), Label({ value })],
637
+ ...rest,
638
+ }),
639
+ Legend: (data = {}) => jsx("legend", { children: label, ...data }),
640
+ ...this,
641
+ };
642
+ }
643
+ return {
644
+ Description,
645
+ Issue,
646
+ Root: (data = {}) => hidden ? Fragment(data) : jsx("div", data),
647
+ Label: (data = {}) => !hidden && jsx("label", { for: control.id, children: label, ...data }),
648
+ Control: (data) => {
649
+ const attrs = { ...control, ...data };
650
+ if (value !== undefined) {
651
+ if (this.tag === "textarea") {
652
+ attrs.children = value;
653
+ }
654
+ else if (this.tag === "input") {
655
+ if (this.type === "checkbox") {
656
+ attrs.checked = value;
657
+ }
658
+ else {
659
+ attrs.value = value;
660
+ }
661
+ }
662
+ }
663
+ return jsx(this.tag, attrs);
664
+ },
665
+ Option:
666
+ // select
667
+ this.options &&
668
+ ((data) => jsx("option", {
669
+ children: data.value,
670
+ selected: chosen(data.value),
671
+ ...data,
672
+ })),
673
+ ...this,
674
+ };
675
+ }
676
+ /**
677
+ * @template S Form shape type
678
+ * @param props Field control props including `name` of the field to render
679
+ * @returns Component that renders the HTML field with default structure
680
+ */
681
+ [render](props) {
682
+ // the sub-components of each kind of field, told apart by `options` and `tag` below
683
+ const c = this[component](props);
684
+ const { options } = this;
685
+ return c.Root({
686
+ children: [
687
+ options && this.tag !== "select"
688
+ ? // radio/checkboxes, a group with a legend, each value labelled
689
+ [
690
+ c.Legend(),
691
+ options.map((value) => jsx("div", {
692
+ children: [c.Control({ value }), c.Label({ value })],
693
+ })),
694
+ ]
695
+ : [
696
+ c.Label(),
697
+ // a select has an option for each value
698
+ c.Control(options && {
699
+ children: options.map((value) => c.Option({ value })),
700
+ }),
701
+ ],
702
+ c.Description(),
703
+ c.Issue(),
704
+ ],
705
+ });
706
+ }
707
+ /**
708
+ * @param field Field definition
709
+ * @returns `true` when the field persists invalid-state values
710
+ */
711
+ static persisted(field) {
712
+ return field.#persist;
713
+ }
714
+ }
715
+ /**
716
+ * @param value Schema
717
+ * @returns `true` for a form field, such as a table column made with `Field`
718
+ */
719
+ export const field = (value) => value instanceof FieldSchema;
720
+ /** Field factory functions */
721
+ export class Field {
722
+ // this is used instead of the defaults for example "Expected string"
723
+ // since "string" doesn't make sense to end users
724
+ /**
725
+ * @template T Input type
726
+ * @param props Input props
727
+ * @returns Generic input field
728
+ */
729
+ static #input(props) {
730
+ return new FieldSchema({ props }, Schema.string(required));
731
+ }
732
+ /**
733
+ * @returns Text input field
734
+ */
735
+ static text() {
736
+ return Field.#input({ type: "text" });
737
+ }
738
+ /**
739
+ * @returns Password input field
740
+ */
741
+ static password() {
742
+ return Field.#input({ type: "password" });
743
+ }
744
+ /**
745
+ * @returns Search input field
746
+ */
747
+ static search() {
748
+ return Field.#input({ type: "search" });
749
+ }
750
+ /**
751
+ * @returns Telephone input field
752
+ */
753
+ static tel() {
754
+ return Field.#input({ type: "tel" });
755
+ }
756
+ /**
757
+ * @returns Color input field
758
+ */
759
+ static color() {
760
+ return Field.#input({ type: "color" });
761
+ }
762
+ /**
763
+ * @returns Hidden input field
764
+ */
765
+ static hidden() {
766
+ return Field.#input({ type: "hidden" });
767
+ }
768
+ /**
769
+ * @returns Date input field
770
+ */
771
+ static date() {
772
+ return Field.#input({ type: "date" });
773
+ }
774
+ /**
775
+ * @returns Datetime input field
776
+ */
777
+ static datetime() {
778
+ return Field.#input({ type: "datetime-local" });
779
+ }
780
+ /**
781
+ * @returns Month input field
782
+ */
783
+ static month() {
784
+ return Field.#input({ type: "month" });
785
+ }
786
+ /**
787
+ * @returns Week input field
788
+ */
789
+ static week() {
790
+ return Field.#input({ type: "week" });
791
+ }
792
+ /**
793
+ * @returns Time input field
794
+ */
795
+ static time() {
796
+ return Field.#input({ type: "time" });
797
+ }
798
+ /**
799
+ * Validates email string.
800
+ *
801
+ * @param message Issue message when invalid
802
+ * @returns Email input field
803
+ */
804
+ static email(message) {
805
+ return Field.#input({ type: "email" }).email(message);
806
+ }
807
+ /**
808
+ * Validates parsable URL.
809
+ *
810
+ * @param message Issue message when invalid
811
+ * @returns URL input field
812
+ */
813
+ static url(message) {
814
+ return Field.#input({ type: "url" }).url(message);
815
+ }
816
+ /**
817
+ * @template T Input type, `number` or `range`
818
+ * @param props Input props
819
+ * @returns Input field
820
+ */
821
+ static #number(props) {
822
+ // registered here rather than as the class loads, which is a side effect
823
+ // that would keep `Field` in bundles that only use `Form`
824
+ normalizers.add(Field.#toNumber);
825
+ return new FieldSchema({ props }, Schema.number(required).preprocess(Field.#toNumber));
826
+ }
827
+ /**
828
+ * @param value Form entry or stored number
829
+ * @returns The number to validate
830
+ */
831
+ static #toNumber(value) {
832
+ // form submissions read numeric controls as strings
833
+ if (value == null || value === "")
834
+ return undefined;
835
+ return exact(value);
836
+ }
837
+ /**
838
+ * Coerces to number.
839
+ *
840
+ * @returns Number input field
841
+ */
842
+ static number() {
843
+ return Field.#number({ type: "number" });
844
+ }
845
+ /**
846
+ * Coerces to number.
847
+ *
848
+ * @returns Range input field
849
+ */
850
+ static range() {
851
+ return Field.#number({ type: "range" });
852
+ }
853
+ /**
854
+ * - unchecked => key missing => `false`
855
+ * - checked => key present => `true`
856
+ *
857
+ * @returns Checkbox input field
858
+ */
859
+ static checkbox() {
860
+ return new FieldSchema({ props: { type: "checkbox" } }, Schema.boolean(), (formData, name) => formData.has(name));
861
+ }
862
+ /**
863
+ * @returns File input field
864
+ */
865
+ static file() {
866
+ return new FieldSchema({ props: { type: "file" } }, Schema.instance(File, required), (data, name) => {
867
+ const value = data.get(name);
868
+ return (chosenFile(value) && value) || undefined;
869
+ });
870
+ }
871
+ /**
872
+ * @template V Value type
873
+ * @param options Checkbox options
874
+ * @returns Checkbox group input field
875
+ */
876
+ static checkboxes(options) {
877
+ return new FieldSchema({ options, props: { type: "checkbox" } }, Schema.array(Schema.enum(options, choose), choose), readMany, options.length);
878
+ }
879
+ /**
880
+ * @template V Value type
881
+ * @param options Radio button options
882
+ * @returns Radio group input field
883
+ */
884
+ static radio(options) {
885
+ return new FieldSchema({ options, props: { type: "radio" } }, Schema.enum(options, choose));
886
+ }
887
+ /**
888
+ * @returns Textarea field
889
+ */
890
+ static textarea() {
891
+ return new FieldSchema({ tag: "textarea" }, Schema.string(required));
892
+ }
893
+ /**
894
+ * @template V Value type
895
+ * @param options Select options
896
+ * @returns Select field
897
+ */
898
+ static select(options) {
899
+ return new FieldSchema({ tag: "select", options }, Schema.enum(options, choose));
900
+ }
901
+ }