@uniweb/kit 0.10.16 → 0.10.18
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/package.json +2 -2
- package/src/hooks/useFormSubmit.js +14 -0
- package/src/utils/submitForm.js +170 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uniweb/kit",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.18",
|
|
4
4
|
"description": "Standard component library for Uniweb foundations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
"fuse.js": "^7.0.0",
|
|
44
44
|
"shiki": "^3.0.0",
|
|
45
45
|
"tailwind-merge": "^3.6.0",
|
|
46
|
-
"@uniweb/core": "0.8.2",
|
|
47
46
|
"@uniweb/scene": "0.1.2",
|
|
47
|
+
"@uniweb/core": "0.8.2",
|
|
48
48
|
"@uniweb/semantic-parser": "1.2.1"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
@@ -104,6 +104,20 @@ export function useFormSubmit(defaults = {}) {
|
|
|
104
104
|
response,
|
|
105
105
|
canSubmit: !!target,
|
|
106
106
|
unavailableReason,
|
|
107
|
+
// Whether attachments can be delivered. True once there is a target: the
|
|
108
|
+
// client sends the manifest, then the bytes, then finalizes.
|
|
109
|
+
//
|
|
110
|
+
// It tracks `canSubmit` because it is a statement about THIS client, not
|
|
111
|
+
// about the endpoint — whether a given endpoint accepts uploads is
|
|
112
|
+
// discovered on submit, and a failure there throws with a message saying
|
|
113
|
+
// the submission landed and the attachment did not. What this rules out is
|
|
114
|
+
// the case that has no honest report: offering a file input when nothing
|
|
115
|
+
// could ever send the bytes.
|
|
116
|
+
//
|
|
117
|
+
// Kept as its own field rather than folded into `canSubmit` because a
|
|
118
|
+
// component decides *whether to render a file input* separately from
|
|
119
|
+
// whether to render the form, and that decision belongs at render time.
|
|
120
|
+
canUploadFiles: !!target,
|
|
107
121
|
submit,
|
|
108
122
|
reset,
|
|
109
123
|
}
|
package/src/utils/submitForm.js
CHANGED
|
@@ -35,8 +35,17 @@
|
|
|
35
35
|
* pageId, pageLabel
|
|
36
36
|
* @param {string} [args.verificationToken] — bot-protection token, when the
|
|
37
37
|
* endpoint verifies one
|
|
38
|
+
* @param {Array<File|{file:File,field?:string}>} [args.files]
|
|
39
|
+
* — attachments to upload. The
|
|
40
|
+
* manifest is derived from
|
|
41
|
+
* these; phase two sends the
|
|
42
|
+
* bytes. The `{file, field}`
|
|
43
|
+
* form records which field an
|
|
44
|
+
* attachment came from.
|
|
38
45
|
* @param {Array<{name:string,size:number,mime?:string}>} [args.fileSlots]
|
|
39
|
-
* —
|
|
46
|
+
* — a manifest with no bytes.
|
|
47
|
+
* Accepted, but ONLY sends the
|
|
48
|
+
* declaration; prefer `files`
|
|
40
49
|
* @param {typeof fetch} [args.fetchFn=fetch] — fetch override (testing / SSR)
|
|
41
50
|
*
|
|
42
51
|
* @returns {Promise<{ submissionId: string, uploadUrls?: Array }>}
|
|
@@ -48,6 +57,7 @@ export async function submitForm({
|
|
|
48
57
|
summary,
|
|
49
58
|
context = {},
|
|
50
59
|
verificationToken,
|
|
60
|
+
files,
|
|
51
61
|
fileSlots,
|
|
52
62
|
fetchFn = typeof fetch === 'function' ? fetch : null,
|
|
53
63
|
} = {}) {
|
|
@@ -64,12 +74,33 @@ export async function submitForm({
|
|
|
64
74
|
throw new Error('submitForm: fetch is unavailable in this environment')
|
|
65
75
|
}
|
|
66
76
|
|
|
77
|
+
const entries = normalizeFiles(files)
|
|
78
|
+
|
|
79
|
+
// A manifest without the files it describes cannot be delivered — the bytes
|
|
80
|
+
// are what phase two sends. Passing `fileSlots` alone declares attachments
|
|
81
|
+
// nobody receives, which is a success that is not one, so say so.
|
|
82
|
+
if (entries.length === 0 && Array.isArray(fileSlots) && fileSlots.length > 0) {
|
|
83
|
+
console.warn(
|
|
84
|
+
`[uniweb] submitForm: ${fileSlots.length} file(s) declared via \`fileSlots\` with no ` +
|
|
85
|
+
'`files` — the manifest is sent and the bytes are NOT. Pass `files` so they upload.',
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const slots = entries.length
|
|
90
|
+
? entries.map(({ file, field }) => ({
|
|
91
|
+
name: file.name,
|
|
92
|
+
size: file.size,
|
|
93
|
+
mime: file.type || 'application/octet-stream',
|
|
94
|
+
...(field ? { field } : {}),
|
|
95
|
+
}))
|
|
96
|
+
: fileSlots
|
|
97
|
+
|
|
67
98
|
// ── API name → wire name. See the header before "correcting" these. ──
|
|
68
99
|
const body = {
|
|
69
100
|
formData,
|
|
70
101
|
metadata: { ...context, preview: summary || deriveSummary(formData) },
|
|
71
102
|
...(verificationToken ? { turnstileToken: verificationToken } : {}),
|
|
72
|
-
...(Array.isArray(
|
|
103
|
+
...(Array.isArray(slots) && slots.length ? { fileSlots: slots } : {}),
|
|
73
104
|
}
|
|
74
105
|
|
|
75
106
|
const res = await fetchFn(target, {
|
|
@@ -84,7 +115,143 @@ export async function submitForm({
|
|
|
84
115
|
throw new Error(serverMessage || `Submission failed (HTTP ${res.status})`)
|
|
85
116
|
}
|
|
86
117
|
|
|
87
|
-
|
|
118
|
+
const result = await res.json()
|
|
119
|
+
|
|
120
|
+
// A submission with no attachments is COMPLETE at this point — the create
|
|
121
|
+
// call wrote the whole record. Finalizing anyway would re-assert the state it
|
|
122
|
+
// already has: accepted, and pointless.
|
|
123
|
+
if (entries.length === 0) return result
|
|
124
|
+
|
|
125
|
+
const report = await uploadFiles(entries, result, target, fetchFn)
|
|
126
|
+
return { ...result, filesUploaded: entries.length, ...report }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Accept either bare `File`s or `{ file, field }` pairs, and drop anything that
|
|
131
|
+
* is not a file. The pair form exists so a submission can say WHICH field an
|
|
132
|
+
* attachment came from — a form may have more than one file input.
|
|
133
|
+
*/
|
|
134
|
+
function normalizeFiles(files) {
|
|
135
|
+
if (!Array.isArray(files)) return []
|
|
136
|
+
return files
|
|
137
|
+
.map((f) => (f && typeof f === 'object' && 'file' in f ? f : { file: f }))
|
|
138
|
+
.filter(({ file }) => file && typeof file === 'object' && 'name' in file)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Phase two — send the bytes.
|
|
143
|
+
*
|
|
144
|
+
* Phase one posts a *manifest* and gets back a submission id; the bytes go
|
|
145
|
+
* separately so they never ride inside the JSON. Two shapes are honoured:
|
|
146
|
+
*
|
|
147
|
+
* - **`uploadUrls` in the response** — one per slot, in slot order. Used when
|
|
148
|
+
* present, because an endpoint returning them is telling you where to write.
|
|
149
|
+
* - **Otherwise `{target}/upload`** — raw body, `X-Submission-Id` and `X-Slot`
|
|
150
|
+
* headers, then `{target}/finalize`. This is the shape the endpoint
|
|
151
|
+
* documents, and it is the default rather than a fallback.
|
|
152
|
+
*
|
|
153
|
+
* `X-Slot` is the **0-based index into the manifest sent in phase one** — which
|
|
154
|
+
* is why the entries and the slots are built from one list in one order, and
|
|
155
|
+
* why nothing here reorders them. An endpoint bounds it to the declared count
|
|
156
|
+
* and rejects anything outside the range.
|
|
157
|
+
*
|
|
158
|
+
* The filename is NOT sent as a header. It travels in the manifest, which is
|
|
159
|
+
* the contract; an endpoint takes the name from there.
|
|
160
|
+
*
|
|
161
|
+
* **Failures throw, and the message says what did land.** The submission row
|
|
162
|
+
* already exists at this point, so a silent failure here is the same
|
|
163
|
+
* discarded-attachment bug in a new place — a caller must be able to tell the
|
|
164
|
+
* visitor that their message arrived and their file did not.
|
|
165
|
+
*/
|
|
166
|
+
async function uploadFiles(entries, result, target, fetchFn) {
|
|
167
|
+
const submissionId = result?.submissionId
|
|
168
|
+
if (!submissionId) {
|
|
169
|
+
throw new Error(
|
|
170
|
+
'submitForm: the submission was recorded but returned no submissionId, so its ' +
|
|
171
|
+
`${entries.length} attachment(s) could not be uploaded.`,
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const base = String(target).replace(/\/+$/, '')
|
|
176
|
+
const urls = Array.isArray(result?.uploadUrls) ? result.uploadUrls : []
|
|
177
|
+
|
|
178
|
+
for (const [slot, { file }] of entries.entries()) {
|
|
179
|
+
const url = urls[slot] || `${base}/upload`
|
|
180
|
+
let res
|
|
181
|
+
try {
|
|
182
|
+
res = await fetchFn(url, {
|
|
183
|
+
method: 'POST',
|
|
184
|
+
headers: {
|
|
185
|
+
'Content-Type': file.type || 'application/octet-stream',
|
|
186
|
+
'X-Submission-Id': submissionId,
|
|
187
|
+
'X-Slot': String(slot),
|
|
188
|
+
},
|
|
189
|
+
body: file,
|
|
190
|
+
})
|
|
191
|
+
} catch (err) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`submitForm: submission ${submissionId} was recorded, but uploading ` +
|
|
194
|
+
`"${file.name}" failed — ${err.message}`,
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
if (!res.ok) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`submitForm: submission ${submissionId} was recorded, but uploading ` +
|
|
200
|
+
`"${file.name}" failed (HTTP ${res.status}).`,
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The manifest rides the finalize body as well as the create body. An
|
|
206
|
+
// endpoint may or may not trust it — the one we are built against verifies
|
|
207
|
+
// each slot against storage instead, precisely because a client-supplied
|
|
208
|
+
// count is what a quota or an invoice would otherwise derive from. Sending it
|
|
209
|
+
// costs a few bytes and satisfies the stricter reading of the contract, in
|
|
210
|
+
// which `files` is required and its absence is a malformed call.
|
|
211
|
+
const manifest = entries.map(({ file }, slot) => ({
|
|
212
|
+
slot,
|
|
213
|
+
name: file.name,
|
|
214
|
+
size: file.size,
|
|
215
|
+
mime: file.type || 'application/octet-stream',
|
|
216
|
+
}))
|
|
217
|
+
|
|
218
|
+
const done = await fetchFn(`${base}/finalize`, {
|
|
219
|
+
method: 'POST',
|
|
220
|
+
headers: { 'Content-Type': 'application/json' },
|
|
221
|
+
body: JSON.stringify({ submissionId, files: manifest }),
|
|
222
|
+
})
|
|
223
|
+
if (!done.ok) {
|
|
224
|
+
throw new Error(
|
|
225
|
+
`submitForm: submission ${submissionId} and its ${entries.length} attachment(s) ` +
|
|
226
|
+
`were uploaded, but finalizing failed (HTTP ${done.status}).`,
|
|
227
|
+
)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Finalize reports what the endpoint actually found in storage, which is not
|
|
231
|
+
// necessarily what we believe we sent. Checking it is the whole point of
|
|
232
|
+
// reading this body: every upload can return 2xx and one can still be absent,
|
|
233
|
+
// and the alternative to catching it here is a support ticket about an
|
|
234
|
+
// attachment nobody received.
|
|
235
|
+
//
|
|
236
|
+
// Only acted on when the endpoint reports a number — an endpoint that returns
|
|
237
|
+
// nothing (or something else) is not thereby claiming a loss.
|
|
238
|
+
let report
|
|
239
|
+
try {
|
|
240
|
+
report = await done.json()
|
|
241
|
+
} catch {
|
|
242
|
+
return undefined // not JSON — nothing to verify against
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const recorded = report?.filesRecorded
|
|
246
|
+
if (typeof recorded === 'number' && recorded < entries.length) {
|
|
247
|
+
throw new Error(
|
|
248
|
+
`submitForm: submission ${submissionId} was recorded, but only ${recorded} of ` +
|
|
249
|
+
`${entries.length} attachment(s) reached storage. The endpoint verifies each upload, ` +
|
|
250
|
+
'so the difference did not arrive.',
|
|
251
|
+
)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return report && typeof report === 'object' ? report : undefined
|
|
88
255
|
}
|
|
89
256
|
|
|
90
257
|
/**
|