@zerolith/forms 0.0.0-stage → 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +25 -2
- package/dist/form.d.ts +88 -0
- package/dist/form.d.ts.map +1 -0
- package/dist/form.js +172 -0
- package/dist/form.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/problem.d.ts +11 -0
- package/dist/problem.d.ts.map +1 -0
- package/dist/problem.js +17 -0
- package/dist/problem.js.map +1 -0
- package/dist/schema.d.ts +59 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +55 -0
- package/dist/schema.js.map +1 -0
- package/package.json +49 -5
- package/src/form.ts +296 -0
- package/src/index.ts +11 -0
- package/src/problem.ts +18 -0
- package/src/schema.ts +119 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zerolith/forms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Forms for zerolith applications. A form stays a native `<form>` that posts `FormData` to its action and works with JavaScript disabled; `createForm` enhances it when JavaScript runs: the submission goes through `fetch` with the form's own method, action, and encoding, pending state and the outcome are signals, and a failure arrives as an RFC 9457 problem details document whose `fields` map carries the messages for each input.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { html } from "zerolith";
|
|
7
|
+
import { createForm } from "@zerolith/forms";
|
|
8
|
+
|
|
9
|
+
const form = createForm({ onSuccess: () => router.navigate("/notes") });
|
|
10
|
+
|
|
11
|
+
html`<form method="post" action="/notes" @submit=${form.submit}>
|
|
12
|
+
<input name="title" aria-invalid=${form.field("title").invalid}>
|
|
13
|
+
<output>${form.field("title").error}</output>
|
|
14
|
+
<button ?disabled=${form.pending}>Save</button>
|
|
15
|
+
</form>`;
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Validation is written once as a Standard Schema and runs on both sides: `validateForm` turns the schema's issues into the same problem document the server returns, and `problemResponse` writes that document as a WinterTC `Response`, so the no-JavaScript path and the enhanced path share one handler and one wire shape. Any backend that can answer with `application/problem+json` fits.
|
|
19
|
+
|
|
20
|
+
The guide is `docs/guide/forms.md` in the repository.
|
|
21
|
+
|
|
22
|
+
Status: pre-alpha, nothing published.
|
|
23
|
+
|
|
24
|
+
## License
|
|
25
|
+
|
|
26
|
+
Apache-2.0. See `LICENSE`.
|
package/dist/form.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The enhancer. A form stays a native `<form>` that posts to its action and
|
|
3
|
+
* works without JavaScript; `createForm` takes over its submit event when
|
|
4
|
+
* JavaScript runs, sends the same request with `fetch`, and exposes the
|
|
5
|
+
* outcome as signals: pending state, a parsed result, or a problem whose
|
|
6
|
+
* `fields` feed the inputs that failed.
|
|
7
|
+
*/
|
|
8
|
+
import { type Problem, type ReadableSignal } from "zerolith";
|
|
9
|
+
import { type StandardSchema } from "./schema.js";
|
|
10
|
+
/** Where a form is in its current submission. */
|
|
11
|
+
export type FormStatus = "idle" | "pending" | "success" | "failure" | "error";
|
|
12
|
+
/** What the default sender, or a custom `send`, receives. */
|
|
13
|
+
export interface Submission {
|
|
14
|
+
/** The form that was submitted. */
|
|
15
|
+
readonly element: HTMLFormElement;
|
|
16
|
+
/** The button or input that submitted it, when there was one. */
|
|
17
|
+
readonly submitter: HTMLElement | null;
|
|
18
|
+
/** The form's data, including the submitter's name and value. */
|
|
19
|
+
readonly data: FormData;
|
|
20
|
+
/** The lowercase method, after the submitter's `formmethod` override. */
|
|
21
|
+
readonly method: string;
|
|
22
|
+
/** The resolved action URL, after the submitter's `formaction` override. */
|
|
23
|
+
readonly action: URL;
|
|
24
|
+
/** Aborted when the form is submitted again or reset. */
|
|
25
|
+
readonly signal: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
/** The outcome of one submission. */
|
|
28
|
+
export interface SubmissionOutcome {
|
|
29
|
+
/** The parsed body: JSON when the response says so, text otherwise, undefined for an empty body. */
|
|
30
|
+
readonly result: unknown;
|
|
31
|
+
readonly response: Response;
|
|
32
|
+
readonly element: HTMLFormElement;
|
|
33
|
+
}
|
|
34
|
+
/** Options for `createForm`. */
|
|
35
|
+
export interface FormOptions {
|
|
36
|
+
/** Validated on the client before anything is sent; failing issues become the problem's `fields`. */
|
|
37
|
+
schema?: StandardSchema;
|
|
38
|
+
/** Sends the submission. Defaults to a `fetch` of the form's method, action, and encoding that asks for JSON. */
|
|
39
|
+
send?: (submission: Submission) => Promise<Response>;
|
|
40
|
+
/** Headers added to the default request. */
|
|
41
|
+
headers?: HeadersInit;
|
|
42
|
+
/** The `fetch` the default sender uses; defaults to the global one. */
|
|
43
|
+
fetch?: typeof fetch;
|
|
44
|
+
/** Where a redirected response takes the page. Defaults to `location.assign`; pass the router's `navigate` to stay in the application. */
|
|
45
|
+
navigate?: (url: string) => void;
|
|
46
|
+
/** Resets the form element after a successful response. */
|
|
47
|
+
reset?: boolean;
|
|
48
|
+
/** Called after a successful response. */
|
|
49
|
+
onSuccess?: (outcome: SubmissionOutcome) => void;
|
|
50
|
+
/** Called with the problem from client-side validation or from the server. */
|
|
51
|
+
onFailure?: (problem: Problem, element: HTMLFormElement) => void;
|
|
52
|
+
/** Called when the request itself fails. */
|
|
53
|
+
onError?: (error: unknown, element: HTMLFormElement) => void;
|
|
54
|
+
}
|
|
55
|
+
/** One input's slice of the current problem. */
|
|
56
|
+
export interface Field {
|
|
57
|
+
/** Every message for the field, oldest first. */
|
|
58
|
+
readonly errors: ReadableSignal<readonly string[]>;
|
|
59
|
+
/** The first message, or undefined. */
|
|
60
|
+
readonly error: ReadableSignal<string | undefined>;
|
|
61
|
+
/** True while the field has a message; bind it to `aria-invalid`. */
|
|
62
|
+
readonly invalid: ReadableSignal<boolean>;
|
|
63
|
+
}
|
|
64
|
+
/** The enhanced form. */
|
|
65
|
+
export interface Form {
|
|
66
|
+
readonly status: ReadableSignal<FormStatus>;
|
|
67
|
+
/** True while a submission is in flight. */
|
|
68
|
+
readonly pending: ReadableSignal<boolean>;
|
|
69
|
+
/** The problem from the last failed submission, or undefined. */
|
|
70
|
+
readonly problem: ReadableSignal<Problem | undefined>;
|
|
71
|
+
/** The parsed body of the last successful submission. */
|
|
72
|
+
readonly result: ReadableSignal<unknown>;
|
|
73
|
+
/** The error of the last submission that did not complete. */
|
|
74
|
+
readonly error: ReadableSignal<unknown>;
|
|
75
|
+
/** A field's view of the problem; the same object for the same name. */
|
|
76
|
+
field(name: string): Field;
|
|
77
|
+
/** The submit handler; bind it with `@submit`. */
|
|
78
|
+
submit(event: SubmitEvent): void;
|
|
79
|
+
/** Aborts any submission in flight and returns the form to idle. */
|
|
80
|
+
reset(): void;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Creates the enhancer for one form. Bind `submit` to the form's `@submit`;
|
|
84
|
+
* the method, action, and encoding stay on the form element, so the same
|
|
85
|
+
* markup submits natively when the script has not run.
|
|
86
|
+
*/
|
|
87
|
+
export declare function createForm(options?: FormOptions): Form;
|
|
88
|
+
//# sourceMappingURL=form.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../src/form.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAsB,KAAK,OAAO,EAAE,KAAK,cAAc,EAAsC,MAAM,U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AE,WAAgB,GAAG,IAAI,CA+I1D"}
|
package/dist/form.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The enhancer. A form stays a native `<form>` that posts to its action and
|
|
3
|
+
* works without JavaScript; `createForm` takes over its submit event when
|
|
4
|
+
* JavaScript runs, sends the same request with `fetch`, and exposes the
|
|
5
|
+
* outcome as signals: pending state, a parsed result, or a problem whose
|
|
6
|
+
* `fields` feed the inputs that failed.
|
|
7
|
+
*/
|
|
8
|
+
import { PROBLEM_MEDIA_TYPE, batch, computed, isProblem, signal } from "zerolith";
|
|
9
|
+
import { validateForm } from "./schema.js";
|
|
10
|
+
const EMPTY = [];
|
|
11
|
+
function entries(data) {
|
|
12
|
+
return [...data].map(([name, value]) => [name, typeof value === "string" ? value : value.name]);
|
|
13
|
+
}
|
|
14
|
+
async function defaultSend(submission, headers, fetchImpl) {
|
|
15
|
+
const { element, submitter, data, method, action, signal: abort } = submission;
|
|
16
|
+
const requestHeaders = new Headers(headers);
|
|
17
|
+
if (!requestHeaders.has("accept")) {
|
|
18
|
+
requestHeaders.set("accept", `application/json, ${PROBLEM_MEDIA_TYPE}`);
|
|
19
|
+
}
|
|
20
|
+
const init = { method: method.toUpperCase(), headers: requestHeaders, signal: abort, credentials: "same-origin" };
|
|
21
|
+
if (method === "get") {
|
|
22
|
+
const url = new URL(action);
|
|
23
|
+
url.search = new URLSearchParams(entries(data)).toString();
|
|
24
|
+
return fetchImpl(url, init);
|
|
25
|
+
}
|
|
26
|
+
const enctype = submitter?.getAttribute("formenctype") ?? element.enctype;
|
|
27
|
+
if (enctype === "multipart/form-data") {
|
|
28
|
+
init.body = data;
|
|
29
|
+
}
|
|
30
|
+
else if (enctype === "text/plain") {
|
|
31
|
+
requestHeaders.set("content-type", "text/plain; charset=utf-8");
|
|
32
|
+
init.body = entries(data).map(([name, value]) => `${name}=${value}\r\n`).join("");
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
init.body = new URLSearchParams(entries(data));
|
|
36
|
+
}
|
|
37
|
+
return fetchImpl(action, init);
|
|
38
|
+
}
|
|
39
|
+
async function parseBody(response) {
|
|
40
|
+
if (response.status === 204 || response.status === 205) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const type = response.headers.get("content-type") ?? "";
|
|
44
|
+
if (type.includes("json")) {
|
|
45
|
+
return response.json();
|
|
46
|
+
}
|
|
47
|
+
const text = await response.text();
|
|
48
|
+
return text === "" ? undefined : text;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Creates the enhancer for one form. Bind `submit` to the form's `@submit`;
|
|
52
|
+
* the method, action, and encoding stay on the form element, so the same
|
|
53
|
+
* markup submits natively when the script has not run.
|
|
54
|
+
*/
|
|
55
|
+
export function createForm(options = {}) {
|
|
56
|
+
const status = signal("idle");
|
|
57
|
+
const problem = signal(undefined);
|
|
58
|
+
const result = signal(undefined);
|
|
59
|
+
const error = signal(undefined);
|
|
60
|
+
const pending = computed(() => status.get() === "pending");
|
|
61
|
+
const fields = new Map();
|
|
62
|
+
let controller;
|
|
63
|
+
const fail = (found, element) => {
|
|
64
|
+
batch(() => {
|
|
65
|
+
problem.set(found);
|
|
66
|
+
status.set("failure");
|
|
67
|
+
});
|
|
68
|
+
options.onFailure?.(found, element);
|
|
69
|
+
};
|
|
70
|
+
const run = async (element, submitter, method, action, current) => {
|
|
71
|
+
const data = new FormData(element, submitter ?? undefined);
|
|
72
|
+
batch(() => {
|
|
73
|
+
status.set("pending");
|
|
74
|
+
problem.set(undefined);
|
|
75
|
+
error.set(undefined);
|
|
76
|
+
});
|
|
77
|
+
if (options.schema !== undefined) {
|
|
78
|
+
const validation = await validateForm(options.schema, data);
|
|
79
|
+
if (current.signal.aborted) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (validation.problem !== undefined) {
|
|
83
|
+
fail(validation.problem, element);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const submission = { element, submitter, data, method, action, signal: current.signal };
|
|
88
|
+
const response = await (options.send ?? ((request) => defaultSend(request, options.headers, options.fetch ?? fetch)))(submission);
|
|
89
|
+
if (current.signal.aborted) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const type = response.headers.get("content-type") ?? "";
|
|
93
|
+
if (type.includes(PROBLEM_MEDIA_TYPE)) {
|
|
94
|
+
fail((await response.json()), element);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (!response.ok) {
|
|
98
|
+
const body = type.includes("json") ? await response.json().catch(() => undefined) : undefined;
|
|
99
|
+
fail(isProblem(body) ? body : { status: response.status, title: response.statusText === "" ? `HTTP ${response.status}` : response.statusText }, element);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const parsed = response.redirected ? undefined : await parseBody(response);
|
|
103
|
+
if (current.signal.aborted) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
batch(() => {
|
|
107
|
+
result.set(parsed);
|
|
108
|
+
status.set("success");
|
|
109
|
+
});
|
|
110
|
+
if (options.reset === true) {
|
|
111
|
+
element.reset();
|
|
112
|
+
}
|
|
113
|
+
options.onSuccess?.({ result: parsed, response, element });
|
|
114
|
+
if (response.redirected) {
|
|
115
|
+
(options.navigate ?? ((url) => location.assign(url)))(response.url);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
status,
|
|
120
|
+
pending,
|
|
121
|
+
problem,
|
|
122
|
+
result,
|
|
123
|
+
error,
|
|
124
|
+
field(name) {
|
|
125
|
+
let field = fields.get(name);
|
|
126
|
+
if (field === undefined) {
|
|
127
|
+
const errors = computed(() => problem.get()?.fields?.[name] ?? EMPTY);
|
|
128
|
+
field = {
|
|
129
|
+
errors,
|
|
130
|
+
error: computed(() => errors.get()[0]),
|
|
131
|
+
invalid: computed(() => errors.get().length > 0)
|
|
132
|
+
};
|
|
133
|
+
fields.set(name, field);
|
|
134
|
+
}
|
|
135
|
+
return field;
|
|
136
|
+
},
|
|
137
|
+
submit(event) {
|
|
138
|
+
const element = event.currentTarget;
|
|
139
|
+
const submitter = event.submitter;
|
|
140
|
+
const method = (submitter?.getAttribute("formmethod") ?? element.getAttribute("method") ?? "get").toLowerCase();
|
|
141
|
+
if (method === "dialog") {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
event.preventDefault();
|
|
145
|
+
const action = new URL(submitter?.hasAttribute("formaction") === true ? submitter.formAction : element.action);
|
|
146
|
+
controller?.abort();
|
|
147
|
+
const current = new AbortController();
|
|
148
|
+
controller = current;
|
|
149
|
+
run(element, submitter, method, action, current).catch((thrown) => {
|
|
150
|
+
if (current.signal.aborted) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
batch(() => {
|
|
154
|
+
error.set(thrown);
|
|
155
|
+
status.set("error");
|
|
156
|
+
});
|
|
157
|
+
options.onError?.(thrown, element);
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
reset() {
|
|
161
|
+
controller?.abort();
|
|
162
|
+
controller = undefined;
|
|
163
|
+
batch(() => {
|
|
164
|
+
status.set("idle");
|
|
165
|
+
problem.set(undefined);
|
|
166
|
+
result.set(undefined);
|
|
167
|
+
error.set(undefined);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=form.js.map
|
package/dist/form.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form.js","sourceRoot":"","sources":["../src/form.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,kBAAkB,EAAqC,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACrH,OAAO,EAAuB,YAAY,EAAE,MAAM,aAAa,CAAC;AAqFhE,MAAM,KAAK,GAAsB,EAAE,CAAC;AAEpC,SAAS,OAAO,CAAC,IAAc;IAE3B,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,EAAE;oBAEP,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;oBAClB,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBACxB,CAAC,CAAC,CAAC;gBACH,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACvC,CAAC,CAAC,CAAC;QACP,CAAC;QACD,KAAK;YAED,UAAU,EAAE,KAAK,EAAE,CAAC;YACpB,UAAU,GAAG,SAAS,CAAC;YACvB,KAAK,CAAC,GAAG,EAAE;gBAEP,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBACnB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;gBACvB,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;gBACtB,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACzB,CAAC,CAAC,CAAC;QACP,CAAC;KACJ,CAAC;AACN,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zerolith/forms: native forms, enhanced. The public surface is assembled here.
|
|
3
|
+
* The `Problem` type, `isProblem`, and `PROBLEM_MEDIA_TYPE` come from `zerolith`.
|
|
4
|
+
*/
|
|
5
|
+
export { problemResponse } from "./problem.js";
|
|
6
|
+
export type { FormValues, InferOutput, StandardIssue, StandardPathSegment, StandardResult, StandardSchema, Validation } from "./schema.js";
|
|
7
|
+
export { formValues, problemFromIssues, validateForm } from "./schema.js";
|
|
8
|
+
export type { Field, Form, FormOptions, FormStatus, Submission, SubmissionOutcome } from "./form.js";
|
|
9
|
+
export { createForm } from "./form.js";
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,aAAa,EAAE,mBAAmB,EAAE,cAAc,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC3I,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE1E,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AACrG,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zerolith/forms: native forms, enhanced. The public surface is assembled here.
|
|
3
|
+
* The `Problem` type, `isProblem`, and `PROBLEM_MEDIA_TYPE` come from `zerolith`.
|
|
4
|
+
*/
|
|
5
|
+
export { problemResponse } from "./problem.js";
|
|
6
|
+
export { formValues, problemFromIssues, validateForm } from "./schema.js";
|
|
7
|
+
export { createForm } from "./form.js";
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG1E,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server side of the problem document: writing a `Problem` as a
|
|
3
|
+
* WinterTC `Response` with the problem details media type.
|
|
4
|
+
*/
|
|
5
|
+
import { type Problem } from "zerolith";
|
|
6
|
+
/**
|
|
7
|
+
* Writes a problem as a `Response` with the problem details media type.
|
|
8
|
+
* The status comes from `init`, or the problem, or defaults to 400.
|
|
9
|
+
*/
|
|
10
|
+
export declare function problemResponse(problem: Problem, init?: ResponseInit): Response;
|
|
11
|
+
//# sourceMappingURL=problem.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"problem.d.ts","sourceRoot":"","sources":["../src/problem.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAsB,KAAK,OAAO,EAAE,MAAM,UAAU,CAAC;AAE5D;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,GAAE,YAAiB,GAAG,QAAQ,CAOnF"}
|
package/dist/problem.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server side of the problem document: writing a `Problem` as a
|
|
3
|
+
* WinterTC `Response` with the problem details media type.
|
|
4
|
+
*/
|
|
5
|
+
import { PROBLEM_MEDIA_TYPE } from "zerolith";
|
|
6
|
+
/**
|
|
7
|
+
* Writes a problem as a `Response` with the problem details media type.
|
|
8
|
+
* The status comes from `init`, or the problem, or defaults to 400.
|
|
9
|
+
*/
|
|
10
|
+
export function problemResponse(problem, init = {}) {
|
|
11
|
+
const status = init.status ?? problem.status ?? 400;
|
|
12
|
+
const headers = new Headers(init.headers);
|
|
13
|
+
headers.set("content-type", `${PROBLEM_MEDIA_TYPE}; charset=utf-8`);
|
|
14
|
+
const body = { ...problem, status };
|
|
15
|
+
return new Response(JSON.stringify(body), { ...init, status, headers });
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=problem.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"problem.js","sourceRoot":"","sources":["../src/problem.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,kBAAkB,EAAgB,MAAM,UAAU,CAAC;AAE5D;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,OAAgB,EAAE,IAAI,GAAiB,EAAE;IAErE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC;IACpD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,kBAAkB,iBAAiB,CAAC,CAAC;IACpE,MAAM,IAAI,GAAY,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,CAAC;IAC7C,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;AAC5E,CAAC"}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation through Standard Schema, the interface that zod, valibot,
|
|
3
|
+
* arktype, and others implement, so a schema written once validates a
|
|
4
|
+
* submission in the browser before it is sent and on the server when it
|
|
5
|
+
* arrives, producing the same problem document in both places.
|
|
6
|
+
*/
|
|
7
|
+
import type { Problem } from "zerolith";
|
|
8
|
+
/** One segment of an issue path in object form. */
|
|
9
|
+
export interface StandardPathSegment {
|
|
10
|
+
readonly key: PropertyKey;
|
|
11
|
+
}
|
|
12
|
+
/** One validation failure. */
|
|
13
|
+
export interface StandardIssue {
|
|
14
|
+
readonly message: string;
|
|
15
|
+
/** The path to the failing value; absent for an issue about the whole input. */
|
|
16
|
+
readonly path?: ReadonlyArray<PropertyKey | StandardPathSegment> | undefined;
|
|
17
|
+
}
|
|
18
|
+
/** What `validate` resolves to: a value, or issues. */
|
|
19
|
+
export type StandardResult<Output> = {
|
|
20
|
+
readonly value: Output;
|
|
21
|
+
readonly issues?: undefined;
|
|
22
|
+
} | {
|
|
23
|
+
readonly issues: ReadonlyArray<StandardIssue>;
|
|
24
|
+
};
|
|
25
|
+
/** The Standard Schema V1 interface, as published at standardschema.dev. */
|
|
26
|
+
export interface StandardSchema<Input = unknown, Output = Input> {
|
|
27
|
+
readonly "~standard": {
|
|
28
|
+
readonly version: 1;
|
|
29
|
+
readonly vendor: string;
|
|
30
|
+
readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
|
|
31
|
+
readonly types?: {
|
|
32
|
+
readonly input: Input;
|
|
33
|
+
readonly output: Output;
|
|
34
|
+
} | undefined;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** The output type of a schema. */
|
|
38
|
+
export type InferOutput<S extends StandardSchema> = S extends StandardSchema<unknown, infer Output> ? Output : never;
|
|
39
|
+
/** A form's values as a plain object: repeated names become arrays. */
|
|
40
|
+
export type FormValues = Record<string, FormDataEntryValue | FormDataEntryValue[]>;
|
|
41
|
+
/** What `validateForm` resolves to: the parsed value, or the problem to show. */
|
|
42
|
+
export type Validation<Output> = {
|
|
43
|
+
readonly value: Output;
|
|
44
|
+
readonly problem?: undefined;
|
|
45
|
+
} | {
|
|
46
|
+
readonly value?: undefined;
|
|
47
|
+
readonly problem: Problem;
|
|
48
|
+
};
|
|
49
|
+
/** Turns `FormData` into a plain object. A name that appears once maps to its value; a name that appears more than once maps to an array of its values, in order. */
|
|
50
|
+
export declare function formValues(data: FormData): FormValues;
|
|
51
|
+
/** Groups issues into a problem: path-bearing issues under `fields`, the rest in `detail`. */
|
|
52
|
+
export declare function problemFromIssues(issues: ReadonlyArray<StandardIssue>): Problem;
|
|
53
|
+
/**
|
|
54
|
+
* Validates a submission with a Standard Schema. `FormData` is converted
|
|
55
|
+
* with `formValues` first; any other value is validated as it is. Issues
|
|
56
|
+
* become a problem whose `fields` carry the messages per path.
|
|
57
|
+
*/
|
|
58
|
+
export declare function validateForm<S extends StandardSchema>(schema: S, data: FormData | Record<string, unknown>): Promise<Validation<InferOutput<S>>>;
|
|
59
|
+
//# sourceMappingURL=schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;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M,GAAG,KAAK,CAAC;AAErH,uEAAuE;AACvE,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,kBAAkB,GAAG,kBAAkB,EAAE,CAAC,CAAC;AAEnF,iFAAiF;AACjF,MAAM,MAAM,UAAU,CAAC,MAAM,IACvB;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,CAAA;CAAE,GACxD;IAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAEhE,qKAAqK;AACrK,wBAAgB,UAAU,CAAC,IAAI,EAAE,QAAQ,GAAG,UAAU,CAoBrD;AAWD,8FAA8F;AAC9F,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,CAAC,aAAa,CAAC,GAAG,OAAO,CAoB/E;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,CAAC,SAAS,cAAc,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CASrJ"}
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Turns `FormData` into a plain object. A name that appears once maps to its value; a name that appears more than once maps to an array of its values, in order. */
|
|
2
|
+
export function formValues(data) {
|
|
3
|
+
const values = {};
|
|
4
|
+
for (const [name, value] of data) {
|
|
5
|
+
const current = values[name];
|
|
6
|
+
if (current === undefined) {
|
|
7
|
+
values[name] = value;
|
|
8
|
+
}
|
|
9
|
+
else if (Array.isArray(current)) {
|
|
10
|
+
current.push(value);
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
values[name] = [current, value];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return values;
|
|
17
|
+
}
|
|
18
|
+
function fieldName(path) {
|
|
19
|
+
if (path === undefined || path.length === 0) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
return path.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
|
|
23
|
+
}
|
|
24
|
+
/** Groups issues into a problem: path-bearing issues under `fields`, the rest in `detail`. */
|
|
25
|
+
export function problemFromIssues(issues) {
|
|
26
|
+
const fields = {};
|
|
27
|
+
const general = [];
|
|
28
|
+
for (const issue of issues) {
|
|
29
|
+
const name = fieldName(issue.path);
|
|
30
|
+
if (name === undefined) {
|
|
31
|
+
general.push(issue.message);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
(fields[name] ??= []).push(issue.message);
|
|
35
|
+
}
|
|
36
|
+
const problem = { type: "about:blank", title: "The submission has invalid fields", status: 400, fields: fields };
|
|
37
|
+
if (general.length > 0) {
|
|
38
|
+
problem.detail = general.join(" ");
|
|
39
|
+
}
|
|
40
|
+
return problem;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Validates a submission with a Standard Schema. `FormData` is converted
|
|
44
|
+
* with `formValues` first; any other value is validated as it is. Issues
|
|
45
|
+
* become a problem whose `fields` carry the messages per path.
|
|
46
|
+
*/
|
|
47
|
+
export async function validateForm(schema, data) {
|
|
48
|
+
const input = data instanceof FormData ? formValues(data) : data;
|
|
49
|
+
const result = await schema["~standard"].validate(input);
|
|
50
|
+
if (result.issues !== undefined && result.issues.length > 0) {
|
|
51
|
+
return { problem: problemFromIssues(result.issues) };
|
|
52
|
+
}
|
|
53
|
+
return { value: result.value };
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAiDA,qKAAqK;AACrK,MAAM,UAAU,UAAU,CAAC,IAAc;IAErC,MAAM,MAAM,GAAe,EAAE,CAAC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AAC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9C,CAAC;IACD,MAAM,OAAO,GAAY,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,mCAAmC,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAqB,EAAE,CAAC;IACzI,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EACtB,CAAC;QACG,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,OAAO,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAA2B,MAAS,EAAE,IAAwC;IAE5G,MAAM,KAAK,GAAG,IAAI,YAAY,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACjE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAC3D,CAAC;QACG,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;IACzD,CAAC;IACD,OAAO,EAAE,KAAK,EAAG,MAAoC,CAAC,KAAK,EAAE,CAAC;AAClE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@zerolith/forms",
|
|
3
|
+
"version": "0.1.0-alpha.1",
|
|
4
|
+
"description": "Forms for zerolith: native forms that post FormData and work without JavaScript, enhanced with fetch, pending state, and RFC 9457 problem+json field errors when it runs, with Standard Schema validation shared by client and server",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "molexxxx",
|
|
7
|
+
"homepage": "https://github.com/molexxxx/zerolith#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/molexxxx/zerolith.git",
|
|
11
|
+
"directory": "packages/forms"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/molexxxx/zerolith/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"zerolith",
|
|
18
|
+
"forms",
|
|
19
|
+
"progressive-enhancement",
|
|
20
|
+
"problem-details",
|
|
21
|
+
"standard-schema"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=24.0.0"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"default": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"src",
|
|
38
|
+
"LICENSE",
|
|
39
|
+
"README.md"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p tsconfig.build.json"
|
|
43
|
+
},
|
|
44
|
+
"peerDependencies": {
|
|
45
|
+
"zerolith": "^0.1.0-alpha.1"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"zerolith": "^0.1.0-alpha.1"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/form.ts
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The enhancer. A form stays a native `<form>` that posts to its action and
|
|
3
|
+
* works without JavaScript; `createForm` takes over its submit event when
|
|
4
|
+
* JavaScript runs, sends the same request with `fetch`, and exposes the
|
|
5
|
+
* outcome as signals: pending state, a parsed result, or a problem whose
|
|
6
|
+
* `fields` feed the inputs that failed.
|
|
7
|
+
*/
|
|
8
|
+
import { PROBLEM_MEDIA_TYPE, type Problem, type ReadableSignal, batch, computed, isProblem, signal } from "zerolith";
|
|
9
|
+
import { type StandardSchema, validateForm } from "./schema.js";
|
|
10
|
+
|
|
11
|
+
/** Where a form is in its current submission. */
|
|
12
|
+
export type FormStatus = "idle" | "pending" | "success" | "failure" | "error";
|
|
13
|
+
|
|
14
|
+
/** What the default sender, or a custom `send`, receives. */
|
|
15
|
+
export interface Submission
|
|
16
|
+
{
|
|
17
|
+
/** The form that was submitted. */
|
|
18
|
+
readonly element: HTMLFormElement;
|
|
19
|
+
/** The button or input that submitted it, when there was one. */
|
|
20
|
+
readonly submitter: HTMLElement | null;
|
|
21
|
+
/** The form's data, including the submitter's name and value. */
|
|
22
|
+
readonly data: FormData;
|
|
23
|
+
/** The lowercase method, after the submitter's `formmethod` override. */
|
|
24
|
+
readonly method: string;
|
|
25
|
+
/** The resolved action URL, after the submitter's `formaction` override. */
|
|
26
|
+
readonly action: URL;
|
|
27
|
+
/** Aborted when the form is submitted again or reset. */
|
|
28
|
+
readonly signal: AbortSignal;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The outcome of one submission. */
|
|
32
|
+
export interface SubmissionOutcome
|
|
33
|
+
{
|
|
34
|
+
/** The parsed body: JSON when the response says so, text otherwise, undefined for an empty body. */
|
|
35
|
+
readonly result: unknown;
|
|
36
|
+
readonly response: Response;
|
|
37
|
+
readonly element: HTMLFormElement;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Options for `createForm`. */
|
|
41
|
+
export interface FormOptions
|
|
42
|
+
{
|
|
43
|
+
/** Validated on the client before anything is sent; failing issues become the problem's `fields`. */
|
|
44
|
+
schema?: StandardSchema;
|
|
45
|
+
/** Sends the submission. Defaults to a `fetch` of the form's method, action, and encoding that asks for JSON. */
|
|
46
|
+
send?: (submission: Submission) => Promise<Response>;
|
|
47
|
+
/** Headers added to the default request. */
|
|
48
|
+
headers?: HeadersInit;
|
|
49
|
+
/** The `fetch` the default sender uses; defaults to the global one. */
|
|
50
|
+
fetch?: typeof fetch;
|
|
51
|
+
/** Where a redirected response takes the page. Defaults to `location.assign`; pass the router's `navigate` to stay in the application. */
|
|
52
|
+
navigate?: (url: string) => void;
|
|
53
|
+
/** Resets the form element after a successful response. */
|
|
54
|
+
reset?: boolean;
|
|
55
|
+
/** Called after a successful response. */
|
|
56
|
+
onSuccess?: (outcome: SubmissionOutcome) => void;
|
|
57
|
+
/** Called with the problem from client-side validation or from the server. */
|
|
58
|
+
onFailure?: (problem: Problem, element: HTMLFormElement) => void;
|
|
59
|
+
/** Called when the request itself fails. */
|
|
60
|
+
onError?: (error: unknown, element: HTMLFormElement) => void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One input's slice of the current problem. */
|
|
64
|
+
export interface Field
|
|
65
|
+
{
|
|
66
|
+
/** Every message for the field, oldest first. */
|
|
67
|
+
readonly errors: ReadableSignal<readonly string[]>;
|
|
68
|
+
/** The first message, or undefined. */
|
|
69
|
+
readonly error: ReadableSignal<string | undefined>;
|
|
70
|
+
/** True while the field has a message; bind it to `aria-invalid`. */
|
|
71
|
+
readonly invalid: ReadableSignal<boolean>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The enhanced form. */
|
|
75
|
+
export interface Form
|
|
76
|
+
{
|
|
77
|
+
readonly status: ReadableSignal<FormStatus>;
|
|
78
|
+
/** True while a submission is in flight. */
|
|
79
|
+
readonly pending: ReadableSignal<boolean>;
|
|
80
|
+
/** The problem from the last failed submission, or undefined. */
|
|
81
|
+
readonly problem: ReadableSignal<Problem | undefined>;
|
|
82
|
+
/** The parsed body of the last successful submission. */
|
|
83
|
+
readonly result: ReadableSignal<unknown>;
|
|
84
|
+
/** The error of the last submission that did not complete. */
|
|
85
|
+
readonly error: ReadableSignal<unknown>;
|
|
86
|
+
/** A field's view of the problem; the same object for the same name. */
|
|
87
|
+
field(name: string): Field;
|
|
88
|
+
/** The submit handler; bind it with `@submit`. */
|
|
89
|
+
submit(event: SubmitEvent): void;
|
|
90
|
+
/** Aborts any submission in flight and returns the form to idle. */
|
|
91
|
+
reset(): void;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const EMPTY: readonly string[] = [];
|
|
95
|
+
|
|
96
|
+
function entries(data: FormData): [string, string][]
|
|
97
|
+
{
|
|
98
|
+
return [...data].map(([name, value]) => [name, typeof value === "string" ? value : value.name]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function defaultSend(submission: Submission, headers: HeadersInit | undefined, fetchImpl: typeof fetch): Promise<Response>
|
|
102
|
+
{
|
|
103
|
+
const { element, submitter, data, method, action, signal: abort } = submission;
|
|
104
|
+
const requestHeaders = new Headers(headers);
|
|
105
|
+
if (!requestHeaders.has("accept"))
|
|
106
|
+
{
|
|
107
|
+
requestHeaders.set("accept", `application/json, ${PROBLEM_MEDIA_TYPE}`);
|
|
108
|
+
}
|
|
109
|
+
const init: RequestInit = { method: method.toUpperCase(), headers: requestHeaders, signal: abort, credentials: "same-origin" };
|
|
110
|
+
if (method === "get")
|
|
111
|
+
{
|
|
112
|
+
const url = new URL(action);
|
|
113
|
+
url.search = new URLSearchParams(entries(data)).toString();
|
|
114
|
+
return fetchImpl(url, init);
|
|
115
|
+
}
|
|
116
|
+
const enctype = submitter?.getAttribute("formenctype") ?? element.enctype;
|
|
117
|
+
if (enctype === "multipart/form-data")
|
|
118
|
+
{
|
|
119
|
+
init.body = data;
|
|
120
|
+
}
|
|
121
|
+
else if (enctype === "text/plain")
|
|
122
|
+
{
|
|
123
|
+
requestHeaders.set("content-type", "text/plain; charset=utf-8");
|
|
124
|
+
init.body = entries(data).map(([name, value]) => `${name}=${value}\r\n`).join("");
|
|
125
|
+
}
|
|
126
|
+
else
|
|
127
|
+
{
|
|
128
|
+
init.body = new URLSearchParams(entries(data));
|
|
129
|
+
}
|
|
130
|
+
return fetchImpl(action, init);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function parseBody(response: Response): Promise<unknown>
|
|
134
|
+
{
|
|
135
|
+
if (response.status === 204 || response.status === 205)
|
|
136
|
+
{
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
const type = response.headers.get("content-type") ?? "";
|
|
140
|
+
if (type.includes("json"))
|
|
141
|
+
{
|
|
142
|
+
return response.json();
|
|
143
|
+
}
|
|
144
|
+
const text = await response.text();
|
|
145
|
+
return text === "" ? undefined : text;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Creates the enhancer for one form. Bind `submit` to the form's `@submit`;
|
|
150
|
+
* the method, action, and encoding stay on the form element, so the same
|
|
151
|
+
* markup submits natively when the script has not run.
|
|
152
|
+
*/
|
|
153
|
+
export function createForm(options: FormOptions = {}): Form
|
|
154
|
+
{
|
|
155
|
+
const status = signal<FormStatus>("idle");
|
|
156
|
+
const problem = signal<Problem | undefined>(undefined);
|
|
157
|
+
const result = signal<unknown>(undefined);
|
|
158
|
+
const error = signal<unknown>(undefined);
|
|
159
|
+
const pending = computed(() => status.get() === "pending");
|
|
160
|
+
const fields = new Map<string, Field>();
|
|
161
|
+
let controller: AbortController | undefined;
|
|
162
|
+
|
|
163
|
+
const fail = (found: Problem, element: HTMLFormElement): void =>
|
|
164
|
+
{
|
|
165
|
+
batch(() =>
|
|
166
|
+
{
|
|
167
|
+
problem.set(found);
|
|
168
|
+
status.set("failure");
|
|
169
|
+
});
|
|
170
|
+
options.onFailure?.(found, element);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const run = async (element: HTMLFormElement, submitter: HTMLElement | null, method: string, action: URL, current: AbortController): Promise<void> =>
|
|
174
|
+
{
|
|
175
|
+
const data = new FormData(element, submitter ?? undefined);
|
|
176
|
+
batch(() =>
|
|
177
|
+
{
|
|
178
|
+
status.set("pending");
|
|
179
|
+
problem.set(undefined);
|
|
180
|
+
error.set(undefined);
|
|
181
|
+
});
|
|
182
|
+
if (options.schema !== undefined)
|
|
183
|
+
{
|
|
184
|
+
const validation = await validateForm(options.schema, data);
|
|
185
|
+
if (current.signal.aborted)
|
|
186
|
+
{
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (validation.problem !== undefined)
|
|
190
|
+
{
|
|
191
|
+
fail(validation.problem, element);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const submission: Submission = { element, submitter, data, method, action, signal: current.signal };
|
|
196
|
+
const response = await (options.send ?? ((request) => defaultSend(request, options.headers, options.fetch ?? fetch)))(submission);
|
|
197
|
+
if (current.signal.aborted)
|
|
198
|
+
{
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const type = response.headers.get("content-type") ?? "";
|
|
202
|
+
if (type.includes(PROBLEM_MEDIA_TYPE))
|
|
203
|
+
{
|
|
204
|
+
fail((await response.json()) as Problem, element);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (!response.ok)
|
|
208
|
+
{
|
|
209
|
+
const body = type.includes("json") ? await response.json().catch(() => undefined) : undefined;
|
|
210
|
+
fail(isProblem(body) ? body : { status: response.status, title: response.statusText === "" ? `HTTP ${response.status}` : response.statusText }, element);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const parsed = response.redirected ? undefined : await parseBody(response);
|
|
214
|
+
if (current.signal.aborted)
|
|
215
|
+
{
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
batch(() =>
|
|
219
|
+
{
|
|
220
|
+
result.set(parsed);
|
|
221
|
+
status.set("success");
|
|
222
|
+
});
|
|
223
|
+
if (options.reset === true)
|
|
224
|
+
{
|
|
225
|
+
element.reset();
|
|
226
|
+
}
|
|
227
|
+
options.onSuccess?.({ result: parsed, response, element });
|
|
228
|
+
if (response.redirected)
|
|
229
|
+
{
|
|
230
|
+
(options.navigate ?? ((url) => location.assign(url)))(response.url);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
status,
|
|
236
|
+
pending,
|
|
237
|
+
problem,
|
|
238
|
+
result,
|
|
239
|
+
error,
|
|
240
|
+
field(name: string): Field
|
|
241
|
+
{
|
|
242
|
+
let field = fields.get(name);
|
|
243
|
+
if (field === undefined)
|
|
244
|
+
{
|
|
245
|
+
const errors = computed<readonly string[]>(() => problem.get()?.fields?.[name] ?? EMPTY);
|
|
246
|
+
field = {
|
|
247
|
+
errors,
|
|
248
|
+
error: computed(() => errors.get()[0]),
|
|
249
|
+
invalid: computed(() => errors.get().length > 0)
|
|
250
|
+
};
|
|
251
|
+
fields.set(name, field);
|
|
252
|
+
}
|
|
253
|
+
return field;
|
|
254
|
+
},
|
|
255
|
+
submit(event: SubmitEvent): void
|
|
256
|
+
{
|
|
257
|
+
const element = event.currentTarget as HTMLFormElement;
|
|
258
|
+
const submitter = event.submitter;
|
|
259
|
+
const method = (submitter?.getAttribute("formmethod") ?? element.getAttribute("method") ?? "get").toLowerCase();
|
|
260
|
+
if (method === "dialog")
|
|
261
|
+
{
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
event.preventDefault();
|
|
265
|
+
const action = new URL(submitter?.hasAttribute("formaction") === true ? (submitter as HTMLButtonElement).formAction : element.action);
|
|
266
|
+
controller?.abort();
|
|
267
|
+
const current = new AbortController();
|
|
268
|
+
controller = current;
|
|
269
|
+
run(element, submitter, method, action, current).catch((thrown: unknown) =>
|
|
270
|
+
{
|
|
271
|
+
if (current.signal.aborted)
|
|
272
|
+
{
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
batch(() =>
|
|
276
|
+
{
|
|
277
|
+
error.set(thrown);
|
|
278
|
+
status.set("error");
|
|
279
|
+
});
|
|
280
|
+
options.onError?.(thrown, element);
|
|
281
|
+
});
|
|
282
|
+
},
|
|
283
|
+
reset(): void
|
|
284
|
+
{
|
|
285
|
+
controller?.abort();
|
|
286
|
+
controller = undefined;
|
|
287
|
+
batch(() =>
|
|
288
|
+
{
|
|
289
|
+
status.set("idle");
|
|
290
|
+
problem.set(undefined);
|
|
291
|
+
result.set(undefined);
|
|
292
|
+
error.set(undefined);
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zerolith/forms: native forms, enhanced. The public surface is assembled here.
|
|
3
|
+
* The `Problem` type, `isProblem`, and `PROBLEM_MEDIA_TYPE` come from `zerolith`.
|
|
4
|
+
*/
|
|
5
|
+
export { problemResponse } from "./problem.js";
|
|
6
|
+
|
|
7
|
+
export type { FormValues, InferOutput, StandardIssue, StandardPathSegment, StandardResult, StandardSchema, Validation } from "./schema.js";
|
|
8
|
+
export { formValues, problemFromIssues, validateForm } from "./schema.js";
|
|
9
|
+
|
|
10
|
+
export type { Field, Form, FormOptions, FormStatus, Submission, SubmissionOutcome } from "./form.js";
|
|
11
|
+
export { createForm } from "./form.js";
|
package/src/problem.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server side of the problem document: writing a `Problem` as a
|
|
3
|
+
* WinterTC `Response` with the problem details media type.
|
|
4
|
+
*/
|
|
5
|
+
import { PROBLEM_MEDIA_TYPE, type Problem } from "zerolith";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Writes a problem as a `Response` with the problem details media type.
|
|
9
|
+
* The status comes from `init`, or the problem, or defaults to 400.
|
|
10
|
+
*/
|
|
11
|
+
export function problemResponse(problem: Problem, init: ResponseInit = {}): Response
|
|
12
|
+
{
|
|
13
|
+
const status = init.status ?? problem.status ?? 400;
|
|
14
|
+
const headers = new Headers(init.headers);
|
|
15
|
+
headers.set("content-type", `${PROBLEM_MEDIA_TYPE}; charset=utf-8`);
|
|
16
|
+
const body: Problem = { ...problem, status };
|
|
17
|
+
return new Response(JSON.stringify(body), { ...init, status, headers });
|
|
18
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation through Standard Schema, the interface that zod, valibot,
|
|
3
|
+
* arktype, and others implement, so a schema written once validates a
|
|
4
|
+
* submission in the browser before it is sent and on the server when it
|
|
5
|
+
* arrives, producing the same problem document in both places.
|
|
6
|
+
*/
|
|
7
|
+
import type { FieldErrors, Problem } from "zerolith";
|
|
8
|
+
|
|
9
|
+
/** One segment of an issue path in object form. */
|
|
10
|
+
export interface StandardPathSegment
|
|
11
|
+
{
|
|
12
|
+
readonly key: PropertyKey;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** One validation failure. */
|
|
16
|
+
export interface StandardIssue
|
|
17
|
+
{
|
|
18
|
+
readonly message: string;
|
|
19
|
+
/** The path to the failing value; absent for an issue about the whole input. */
|
|
20
|
+
readonly path?: ReadonlyArray<PropertyKey | StandardPathSegment> | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What `validate` resolves to: a value, or issues. */
|
|
24
|
+
export type StandardResult<Output> =
|
|
25
|
+
| { readonly value: Output; readonly issues?: undefined }
|
|
26
|
+
| { readonly issues: ReadonlyArray<StandardIssue> };
|
|
27
|
+
|
|
28
|
+
/** The Standard Schema V1 interface, as published at standardschema.dev. */
|
|
29
|
+
export interface StandardSchema<Input = unknown, Output = Input>
|
|
30
|
+
{
|
|
31
|
+
readonly "~standard": {
|
|
32
|
+
readonly version: 1;
|
|
33
|
+
readonly vendor: string;
|
|
34
|
+
readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
|
|
35
|
+
readonly types?: { readonly input: Input; readonly output: Output } | undefined;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The output type of a schema. */
|
|
40
|
+
export type InferOutput<S extends StandardSchema> = S extends StandardSchema<unknown, infer Output> ? Output : never;
|
|
41
|
+
|
|
42
|
+
/** A form's values as a plain object: repeated names become arrays. */
|
|
43
|
+
export type FormValues = Record<string, FormDataEntryValue | FormDataEntryValue[]>;
|
|
44
|
+
|
|
45
|
+
/** What `validateForm` resolves to: the parsed value, or the problem to show. */
|
|
46
|
+
export type Validation<Output> =
|
|
47
|
+
| { readonly value: Output; readonly problem?: undefined }
|
|
48
|
+
| { readonly value?: undefined; readonly problem: Problem };
|
|
49
|
+
|
|
50
|
+
/** Turns `FormData` into a plain object. A name that appears once maps to its value; a name that appears more than once maps to an array of its values, in order. */
|
|
51
|
+
export function formValues(data: FormData): FormValues
|
|
52
|
+
{
|
|
53
|
+
const values: FormValues = {};
|
|
54
|
+
for (const [name, value] of data)
|
|
55
|
+
{
|
|
56
|
+
const current = values[name];
|
|
57
|
+
if (current === undefined)
|
|
58
|
+
{
|
|
59
|
+
values[name] = value;
|
|
60
|
+
}
|
|
61
|
+
else if (Array.isArray(current))
|
|
62
|
+
{
|
|
63
|
+
current.push(value);
|
|
64
|
+
}
|
|
65
|
+
else
|
|
66
|
+
{
|
|
67
|
+
values[name] = [current, value];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return values;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function fieldName(path: ReadonlyArray<PropertyKey | StandardPathSegment> | undefined): string | undefined
|
|
74
|
+
{
|
|
75
|
+
if (path === undefined || path.length === 0)
|
|
76
|
+
{
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
return path.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Groups issues into a problem: path-bearing issues under `fields`, the rest in `detail`. */
|
|
83
|
+
export function problemFromIssues(issues: ReadonlyArray<StandardIssue>): Problem
|
|
84
|
+
{
|
|
85
|
+
const fields: Record<string, string[]> = {};
|
|
86
|
+
const general: string[] = [];
|
|
87
|
+
for (const issue of issues)
|
|
88
|
+
{
|
|
89
|
+
const name = fieldName(issue.path);
|
|
90
|
+
if (name === undefined)
|
|
91
|
+
{
|
|
92
|
+
general.push(issue.message);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
(fields[name] ??= []).push(issue.message);
|
|
96
|
+
}
|
|
97
|
+
const problem: Problem = { type: "about:blank", title: "The submission has invalid fields", status: 400, fields: fields as FieldErrors };
|
|
98
|
+
if (general.length > 0)
|
|
99
|
+
{
|
|
100
|
+
problem.detail = general.join(" ");
|
|
101
|
+
}
|
|
102
|
+
return problem;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Validates a submission with a Standard Schema. `FormData` is converted
|
|
107
|
+
* with `formValues` first; any other value is validated as it is. Issues
|
|
108
|
+
* become a problem whose `fields` carry the messages per path.
|
|
109
|
+
*/
|
|
110
|
+
export async function validateForm<S extends StandardSchema>(schema: S, data: FormData | Record<string, unknown>): Promise<Validation<InferOutput<S>>>
|
|
111
|
+
{
|
|
112
|
+
const input = data instanceof FormData ? formValues(data) : data;
|
|
113
|
+
const result = await schema["~standard"].validate(input);
|
|
114
|
+
if (result.issues !== undefined && result.issues.length > 0)
|
|
115
|
+
{
|
|
116
|
+
return { problem: problemFromIssues(result.issues) };
|
|
117
|
+
}
|
|
118
|
+
return { value: (result as { value: InferOutput<S> }).value };
|
|
119
|
+
}
|