@timber-js/app 0.2.0-alpha.217 → 0.2.0-alpha.219
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/agent-skill.md +5 -5
- package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
- package/dist/_chunks/actions-BwkmAYXq.js.map +1 -0
- package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -1
- package/dist/_chunks/dev-server-B8zsT-ee.js.map +1 -1
- package/dist/_chunks/dist-DtrJyBbw.js.map +1 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -1
- package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -1
- package/dist/adapters/cloudflare.js +1 -2
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/client/error-boundary.js +1 -2
- package/dist/client/form.d.ts +34 -37
- package/dist/client/form.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +40 -75
- package/dist/client/index.js.map +1 -1
- package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
- package/dist/client/use-field-state.d.ts.map +1 -0
- package/dist/config-types.d.ts +15 -18
- package/dist/config-types.d.ts.map +1 -1
- package/dist/cookies/index.js.map +1 -1
- package/dist/index.js +29 -27
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-manifest.d.ts.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/search-params/index.js.map +1 -1
- package/dist/server/action-client.d.ts +11 -172
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +0 -7
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/action-schema.d.ts +126 -0
- package/dist/server/action-schema.d.ts.map +1 -0
- package/dist/server/action-types.d.ts +108 -0
- package/dist/server/action-types.d.ts.map +1 -0
- package/dist/server/form-data.d.ts +7 -0
- package/dist/server/form-data.d.ts.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +511 -148
- package/dist/server/index.js.map +1 -1
- package/dist/server/internal.js +12 -3
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline-metadata.d.ts +9 -0
- package/dist/server/pipeline-metadata.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
- package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/schema-introspection.d.ts +68 -0
- package/dist/server/schema-introspection.d.ts.map +1 -0
- package/dist/server/sensitive-fields.d.ts +40 -26
- package/dist/server/sensitive-fields.d.ts.map +1 -1
- package/dist/server/sitemap-handler.d.ts.map +1 -1
- package/docs/api/31-api-client.mdx +19 -18
- package/docs/api/34-api-config.mdx +1 -1
- package/docs/learn/08-forms-and-actions.mdx +57 -23
- package/package.json +8 -8
- package/src/client/browser-entry/index.ts +7 -1
- package/src/client/form.tsx +57 -108
- package/src/client/index.ts +3 -3
- package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
- package/src/config-types.ts +15 -18
- package/src/plugins/build-manifest.ts +12 -27
- package/src/plugins/shims.ts +0 -1
- package/src/server/action-client.ts +82 -307
- package/src/server/action-handler.ts +1 -42
- package/src/server/action-schema.ts +203 -0
- package/src/server/action-types.ts +145 -0
- package/src/server/form-data.ts +7 -0
- package/src/server/index.ts +5 -3
- package/src/server/pipeline-metadata.ts +11 -1
- package/src/server/pipeline-phases.ts +9 -2
- package/src/server/rsc-entry/action-dispatcher.ts +0 -4
- package/src/server/rsc-entry/index.ts +1 -2
- package/src/server/schema-introspection.ts +393 -0
- package/src/server/sensitive-fields.ts +115 -58
- package/src/server/sitemap-handler.ts +14 -21
- package/dist/_chunks/actions-CUh3cClk.js.map +0 -1
- package/dist/client/use-form-field.d.ts.map +0 -1
package/dist/server/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { A as getSpanId, C as isRedirectSignal, E as addSpanEvent, F as withSpan, S as isDenySignal, T as isDevMode, j as getTraceId, w as isDebug } from "../_chunks/logger-CbLdcy-W.js";
|
|
2
2
|
import { t as formatSize } from "../_chunks/format-BKclgVbk.js";
|
|
3
|
-
import { _ as getHeaders, a as parseFormData, c as deny, d as waitUntil, i as coerce, l as redirect, n as revalidatePath, p as getCookieJar, r as revalidateTag, u as redirectExternal, y as getSegmentParams } from "../_chunks/actions-
|
|
3
|
+
import { _ as getHeaders, a as parseFormData, c as deny, d as waitUntil, i as coerce, l as redirect, n as revalidatePath, p as getCookieJar, r as revalidateTag, u as redirectExternal, y as getSegmentParams } from "../_chunks/actions-BwkmAYXq.js";
|
|
4
4
|
//#region src/shared/redirect-type.ts
|
|
5
5
|
/**
|
|
6
6
|
* Next.js redirect type discriminator.
|
|
@@ -20,28 +20,36 @@ var RedirectType = {
|
|
|
20
20
|
//#endregion
|
|
21
21
|
//#region src/server/sensitive-fields.ts
|
|
22
22
|
/**
|
|
23
|
-
* Sensitive field stripping — removes password/token/CVV-style fields
|
|
24
|
-
*
|
|
25
|
-
*
|
|
23
|
+
* Sensitive field stripping — removes password/token/CVV-style fields from
|
|
24
|
+
* the `submittedValues` a `createActionClient` action echoes back to the
|
|
25
|
+
* client for form repopulation.
|
|
26
26
|
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* - No-JS form POST path: `handleFormAction()` in `action-handler.ts`
|
|
27
|
+
* **This is hygiene, not a security boundary.** `submittedValues` only ever
|
|
28
|
+
* returns to the user who typed it, in the response to their own POST:
|
|
30
29
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
30
|
+
* - With JavaScript, it travels in the action's response, a non-cacheable
|
|
31
|
+
* POST fetch. What remains is exposure to devtools, HAR exports and
|
|
32
|
+
* TLS-inspecting proxies.
|
|
33
|
+
* - Without JavaScript, it is rendered into the page's HTML as a field's
|
|
34
|
+
* `defaultValue`: one uncached response, but one that view-source, the
|
|
35
|
+
* back-forward cache and a shared machine can surface. OWASP advises not
|
|
36
|
+
* pre-filling password fields for this reason.
|
|
37
37
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* `timber.config.ts` or per-action via `createActionClient({ stripSensitiveFields: false })`.
|
|
38
|
+
* The main reason to strip is UX: a password or card field comes back empty
|
|
39
|
+
* after a failed submit, as users expect.
|
|
41
40
|
*
|
|
42
|
-
*
|
|
41
|
+
* What is stripped: a field whose name matches the built-in deny-list (or the
|
|
42
|
+
* configured option), and a field the action's schema marks sensitive with
|
|
43
|
+
* `.meta({ sensitive: true })` (Valibot: `v.metadata({ sensitive: true })`),
|
|
44
|
+
* at its exact path. The schema mark covers names the list misses
|
|
45
|
+
* (`recoveryPhrase`) and always applies, even with the name list turned off.
|
|
46
|
+
*
|
|
47
|
+
* Only `createActionClient` strips, because only it builds `submittedValues`.
|
|
48
|
+
* A raw `'use server'` action owns its return value: whatever it returns is
|
|
49
|
+
* what the client gets, on both paths.
|
|
50
|
+
*
|
|
51
|
+
* See design/08-forms-and-actions.md §"Sensitive field stripping"
|
|
43
52
|
* See design/13-security.md §"Sensitive field stripping"
|
|
44
|
-
* See TIM-816
|
|
45
53
|
*/
|
|
46
54
|
/**
|
|
47
55
|
* Substring patterns matched against the normalized field name.
|
|
@@ -49,29 +57,39 @@ var RedirectType = {
|
|
|
49
57
|
*
|
|
50
58
|
* Any field whose normalized name *contains* one of these strings is
|
|
51
59
|
* considered sensitive. Entries like `currentPassword`, `passwordConfirmation`,
|
|
52
|
-
* and `user.password` all match via the `password` substring.
|
|
60
|
+
* and `user.password` all match via the `password` substring. Every pattern
|
|
61
|
+
* here is long enough not to occur inside an ordinary word.
|
|
53
62
|
*/
|
|
54
63
|
var BUILTIN_SUBSTRING_PATTERNS = [
|
|
55
64
|
"password",
|
|
56
65
|
"passwd",
|
|
57
|
-
"pwd",
|
|
58
66
|
"secret",
|
|
59
67
|
"apikey",
|
|
60
68
|
"accesstoken",
|
|
61
69
|
"refreshtoken",
|
|
62
|
-
"cvv",
|
|
63
|
-
"cvc",
|
|
64
70
|
"cardnumber",
|
|
65
71
|
"cardcvc",
|
|
66
|
-
"ssn",
|
|
67
72
|
"socialsecuritynumber",
|
|
68
|
-
"otp",
|
|
69
|
-
"totp",
|
|
70
73
|
"mfacode",
|
|
71
74
|
"twofactorcode",
|
|
72
75
|
"privatekey"
|
|
73
76
|
];
|
|
74
77
|
/**
|
|
78
|
+
* Patterns matched at the start or end of a word of the field name. These are
|
|
79
|
+
* short enough to occur inside ordinary words (`otp` in `footPath` and
|
|
80
|
+
* `notpublic`, `ssn` in `class_number` and `classnumber`), so they must
|
|
81
|
+
* begin or end a word: `otp`, `otpCode`, `otpcode`, `userotp`, `user_ssn`,
|
|
82
|
+
* `SSNLast4`, `newpwd`, `cardcvv`.
|
|
83
|
+
*/
|
|
84
|
+
var BUILTIN_WORD_PATTERNS = [
|
|
85
|
+
"pwd",
|
|
86
|
+
"cvv",
|
|
87
|
+
"cvc",
|
|
88
|
+
"ssn",
|
|
89
|
+
"otp",
|
|
90
|
+
"totp"
|
|
91
|
+
];
|
|
92
|
+
/**
|
|
75
93
|
* Exact matches against the normalized field name. These are field names that
|
|
76
94
|
* are too short or too common to substring-match safely. e.g. `token` alone
|
|
77
95
|
* would match `csrfToken`, which is not sensitive — so `token` is exact-only,
|
|
@@ -84,26 +102,33 @@ var BUILTIN_EXACT_PATTERNS = ["token"];
|
|
|
84
102
|
* kebab-case variants all compare equal (`api_key` / `apiKey` / `api-key` →
|
|
85
103
|
* `apikey`).
|
|
86
104
|
*/
|
|
87
|
-
function normalize(name) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
105
|
+
function normalize$1(name) {
|
|
106
|
+
return name.replace(/[_-]/g, "").toLowerCase();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Split a field name into lowercase words at anything that is not a letter
|
|
110
|
+
* and at a lowercase-to-uppercase hump: `user_ssnLast4` → `user`, `ssn`,
|
|
111
|
+
* `last`. An acronym stays joined to what follows it (`OTPcode` →
|
|
112
|
+
* `otpcode`, `SSNLast` → `ssnlast`), which a start-of-word match still finds.
|
|
113
|
+
*/
|
|
114
|
+
function words(name) {
|
|
115
|
+
return name.split(/[^A-Za-z]+|(?<=[a-z])(?=[A-Z])/).filter(Boolean).map((w) => w.toLowerCase());
|
|
116
|
+
}
|
|
117
|
+
/** Whether a short pattern begins or ends one of the name's words. */
|
|
118
|
+
function hasWordPattern(name) {
|
|
119
|
+
return words(name).some((word) => BUILTIN_WORD_PATTERNS.some((p) => word.startsWith(p) || word.endsWith(p)));
|
|
96
120
|
}
|
|
97
121
|
/**
|
|
98
122
|
* Check whether a name matches the built-in deny-list (with optional extras).
|
|
99
123
|
* Extras are merged into the substring pattern list after normalization.
|
|
100
124
|
*/
|
|
101
125
|
function isBuiltinSensitive(name, extras) {
|
|
102
|
-
const normalized = normalize(name);
|
|
126
|
+
const normalized = normalize$1(name);
|
|
103
127
|
if (BUILTIN_EXACT_PATTERNS.includes(normalized)) return true;
|
|
104
128
|
for (const pattern of BUILTIN_SUBSTRING_PATTERNS) if (normalized.includes(pattern)) return true;
|
|
129
|
+
if (hasWordPattern(name)) return true;
|
|
105
130
|
if (extras && extras.length > 0) for (const extra of extras) {
|
|
106
|
-
const normExtra = normalize(extra);
|
|
131
|
+
const normExtra = normalize$1(extra);
|
|
107
132
|
if (normExtra.length === 0) continue;
|
|
108
133
|
if (normalized.includes(normExtra)) return true;
|
|
109
134
|
}
|
|
@@ -115,7 +140,7 @@ function isBuiltinSensitive(name, extras) {
|
|
|
115
140
|
*
|
|
116
141
|
* - Per-action `undefined` → fall back to global.
|
|
117
142
|
* - Global `undefined` → use built-in list.
|
|
118
|
-
* - Either level set to `false` →
|
|
143
|
+
* - Either level set to `false` → no name matching (returns `null`).
|
|
119
144
|
* - `true` → built-in list.
|
|
120
145
|
* - `string[]` → built-in ∪ extras.
|
|
121
146
|
* - function → custom, replaces the built-in list entirely.
|
|
@@ -129,16 +154,18 @@ function resolveSensitivePredicate(perAction, global) {
|
|
|
129
154
|
return (name) => isBuiltinSensitive(name, extras);
|
|
130
155
|
}
|
|
131
156
|
var warnedFields = /* @__PURE__ */ new Set();
|
|
132
|
-
function warnStripped(name) {
|
|
157
|
+
function warnStripped(name, markedInSchema) {
|
|
133
158
|
if (!isDebug()) return;
|
|
134
159
|
if (warnedFields.has(name)) return;
|
|
135
160
|
warnedFields.add(name);
|
|
136
|
-
console.warn(`[timber] stripped sensitive field "${name}" from submittedValues. Override via forms.stripSensitiveFields in timber.config.ts.`);
|
|
161
|
+
console.warn(`[timber] stripped sensitive field "${name}" from submittedValues. ` + (markedInSchema ? `The action's schema marks it sensitive; remove the mark to echo it.` : `Override via forms.stripSensitiveFields in timber.config.ts.`));
|
|
137
162
|
}
|
|
138
163
|
/**
|
|
139
|
-
* Walk an object (recursively) and return a copy
|
|
140
|
-
* `predicate`
|
|
141
|
-
*
|
|
164
|
+
* Walk an object (recursively) and return a copy without its sensitive
|
|
165
|
+
* fields: every key `predicate` matches, and every field `shape` (the
|
|
166
|
+
* schema's declared shape) marks sensitive. Nested objects like
|
|
167
|
+
* `{ user: { password: '...' } }` are handled — `user.password` is stripped
|
|
168
|
+
* while other `user.*` fields remain.
|
|
142
169
|
*
|
|
143
170
|
* - Arrays are walked element-wise (object entries inside arrays are cleaned).
|
|
144
171
|
* - Non-plain values (strings, numbers, Files, Dates, etc.) are returned as-is.
|
|
@@ -146,22 +173,428 @@ function warnStripped(name) {
|
|
|
146
173
|
* — we do NOT set it to an empty string, because that would overwrite a
|
|
147
174
|
* valid `defaultValue` the form author might have set.
|
|
148
175
|
*/
|
|
149
|
-
function stripSensitiveFields(value, predicate) {
|
|
150
|
-
if (predicate === null) return value;
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (
|
|
176
|
+
function stripSensitiveFields(value, predicate, shape) {
|
|
177
|
+
if (predicate === null && !hasSensitive(shape)) return value;
|
|
178
|
+
return stripFrom(value, predicate, shape);
|
|
179
|
+
}
|
|
180
|
+
function stripFrom(value, predicate, shape) {
|
|
181
|
+
if (value === null || typeof value !== "object") return value;
|
|
182
|
+
if (value instanceof Blob || value instanceof Date) return value;
|
|
183
|
+
if (Array.isArray(value)) return value.map((item) => stripFrom(item, predicate, shape?.item));
|
|
184
|
+
const indexed = shape?.item !== void 0 && shape.properties === void 0;
|
|
155
185
|
const result = {};
|
|
156
186
|
for (const [key, nested] of Object.entries(value)) {
|
|
157
|
-
|
|
158
|
-
|
|
187
|
+
const child = indexed ? shape.item : shape?.properties?.[key];
|
|
188
|
+
if (child?.sensitive || predicate?.(key)) {
|
|
189
|
+
warnStripped(key, child?.sensitive === true);
|
|
159
190
|
continue;
|
|
160
191
|
}
|
|
161
|
-
result[key] =
|
|
192
|
+
result[key] = stripFrom(nested, predicate, child);
|
|
162
193
|
}
|
|
163
194
|
return result;
|
|
164
195
|
}
|
|
196
|
+
/** Whether `shape` marks any field at or below it sensitive. */
|
|
197
|
+
function hasSensitive(shape) {
|
|
198
|
+
if (!shape) return false;
|
|
199
|
+
if (shape.sensitive) return true;
|
|
200
|
+
if (hasSensitive(shape.item)) return true;
|
|
201
|
+
return Object.values(shape.properties ?? {}).some(hasSensitive);
|
|
202
|
+
}
|
|
203
|
+
[
|
|
204
|
+
...BUILTIN_SUBSTRING_PATTERNS,
|
|
205
|
+
...BUILTIN_WORD_PATTERNS,
|
|
206
|
+
...BUILTIN_EXACT_PATTERNS
|
|
207
|
+
];
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/server/action-schema.ts
|
|
210
|
+
/** Check if a schema implements the Standard Schema protocol. */
|
|
211
|
+
function isStandardSchema(schema) {
|
|
212
|
+
return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"].validate === "function";
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Validate `input` with `schema`, through Standard Schema when the schema
|
|
216
|
+
* implements it, and through `.safeParse()` / `.parse()` otherwise. Only
|
|
217
|
+
* synchronous Standard Schema validation is supported.
|
|
218
|
+
*/
|
|
219
|
+
function validateWithSchema(schema, input) {
|
|
220
|
+
if (isStandardSchema(schema)) {
|
|
221
|
+
const result = schema["~standard"].validate(input);
|
|
222
|
+
if (result instanceof Promise) throw new Error("[timber] createActionClient: schema returned a Promise — only sync schemas are supported.");
|
|
223
|
+
if (result.issues) return {
|
|
224
|
+
ok: false,
|
|
225
|
+
validationErrors: extractStandardSchemaErrors(result.issues)
|
|
226
|
+
};
|
|
227
|
+
return {
|
|
228
|
+
ok: true,
|
|
229
|
+
value: result.value
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
if (typeof schema.safeParse === "function") {
|
|
233
|
+
const result = schema.safeParse(input);
|
|
234
|
+
if (!result.success) return {
|
|
235
|
+
ok: false,
|
|
236
|
+
validationErrors: extractValidationErrors(result.error)
|
|
237
|
+
};
|
|
238
|
+
return {
|
|
239
|
+
ok: true,
|
|
240
|
+
value: result.data
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
return {
|
|
245
|
+
ok: true,
|
|
246
|
+
value: schema.parse(input)
|
|
247
|
+
};
|
|
248
|
+
} catch (parseError) {
|
|
249
|
+
return {
|
|
250
|
+
ok: false,
|
|
251
|
+
validationErrors: extractValidationErrors(parseError)
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Extract validation errors from a schema error.
|
|
257
|
+
* Supports Zod's flatten() and generic issues array.
|
|
258
|
+
*/
|
|
259
|
+
function extractValidationErrors(error) {
|
|
260
|
+
if (typeof error.flatten === "function") return error.flatten().fieldErrors;
|
|
261
|
+
if (error.issues) {
|
|
262
|
+
const errors = {};
|
|
263
|
+
for (const issue of error.issues) {
|
|
264
|
+
const path = issue.path?.join(".") ?? "_root";
|
|
265
|
+
(errors[path] ??= []).push(issue.message);
|
|
266
|
+
}
|
|
267
|
+
return errors;
|
|
268
|
+
}
|
|
269
|
+
return { _root: ["Validation failed"] };
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Extract validation errors from Standard Schema issues.
|
|
273
|
+
*/
|
|
274
|
+
function extractStandardSchemaErrors(issues) {
|
|
275
|
+
const errors = {};
|
|
276
|
+
for (const issue of issues) {
|
|
277
|
+
const path = issue.path?.map((p) => {
|
|
278
|
+
if (typeof p === "object" && p !== null && "key" in p) return String(p.key);
|
|
279
|
+
return String(p);
|
|
280
|
+
}).join(".") ?? "_root";
|
|
281
|
+
(errors[path] ??= []).push(issue.message);
|
|
282
|
+
}
|
|
283
|
+
return Object.keys(errors).length > 0 ? errors : { _root: ["Validation failed"] };
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region src/server/schema-introspection.ts
|
|
287
|
+
/**
|
|
288
|
+
* Schema introspection — the shape of an action's input as its schema
|
|
289
|
+
* declares it: which fields are lists, which may be absent, and which the
|
|
290
|
+
* schema marks sensitive.
|
|
291
|
+
*
|
|
292
|
+
* Standard Schema v1 has no introspection API, so this feature-detects what
|
|
293
|
+
* the libraries expose:
|
|
294
|
+
*
|
|
295
|
+
* - **Zod 4**: its schema tree (`_zod.def`, documented for library authors),
|
|
296
|
+
* with `.meta()` for marks and `_zod.optin` for fields that may be absent.
|
|
297
|
+
* Not Zod's JSON Schema: that describes a `z.preprocess(fn, z.array(…))`
|
|
298
|
+
* field as the inner array, and wrapping a scalar before `fn` runs would
|
|
299
|
+
* hand a comma-splitting preprocessor `['a,b']`. A preprocessed field is
|
|
300
|
+
* its author's to read, so it has no shape here.
|
|
301
|
+
* - **Valibot**: its schema objects (`entries`, `item`, `wrapped`, `options`),
|
|
302
|
+
* with `v.metadata({ sensitive: true })` read from the pipe.
|
|
303
|
+
* - **Standard JSON Schema** (`~standard.jsonSchema.input()`) for any other
|
|
304
|
+
* library that implements it, such as ArkType, whose
|
|
305
|
+
* `.configure({ sensitive: true })` lands in the JSON Schema node.
|
|
306
|
+
*
|
|
307
|
+
* Any other schema (a legacy `.parse()` schema, Zod 3, a hand-written
|
|
308
|
+
* Standard Schema) has no shape: its form input is not normalized and only
|
|
309
|
+
* the name deny-list strips its echo.
|
|
310
|
+
*
|
|
311
|
+
* A union merges its branches: a field is sensitive if any branch marks it,
|
|
312
|
+
* and a list only if every branch declares it one. An intersection merges
|
|
313
|
+
* its parts, which all apply: a list or sensitive if any part says so.
|
|
314
|
+
*
|
|
315
|
+
* `createActionClient` computes the shape once per action and keeps it on the
|
|
316
|
+
* action's closure. It is used twice, by `normalizeListFields` (before
|
|
317
|
+
* validation, and for `submittedValues`) and by `stripSensitiveFields`.
|
|
318
|
+
*
|
|
319
|
+
* See design/08-forms-and-actions.md §"The Form Model" and
|
|
320
|
+
* §"Sensitive field stripping".
|
|
321
|
+
*/
|
|
322
|
+
/**
|
|
323
|
+
* The shape of `schema`'s input, or `undefined` when the schema library
|
|
324
|
+
* exposes nothing to read it from.
|
|
325
|
+
*/
|
|
326
|
+
function introspectSchema(schema) {
|
|
327
|
+
if (!isStandardSchema(schema)) return void 0;
|
|
328
|
+
const standard = schema["~standard"];
|
|
329
|
+
if (standard.vendor === "zod" && isRecord(schema) && isRecord(schema._zod)) return fromZod(schema, /* @__PURE__ */ new Set());
|
|
330
|
+
if (standard.vendor === "valibot") return fromValibot(schema, /* @__PURE__ */ new Set());
|
|
331
|
+
const jsonSchema = standard.jsonSchema;
|
|
332
|
+
if (!isRecord(jsonSchema) || typeof jsonSchema.input !== "function") return void 0;
|
|
333
|
+
let root;
|
|
334
|
+
try {
|
|
335
|
+
root = jsonSchema.input({ target: "draft-2020-12" });
|
|
336
|
+
} catch {
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
return isRecord(root) ? fromJsonSchema(root, root, /* @__PURE__ */ new Set()) : void 0;
|
|
340
|
+
}
|
|
341
|
+
/** Zod wrappers whose `innerType` is the field's real type. */
|
|
342
|
+
var ZOD_WRAPPERS = /* @__PURE__ */ new Set([
|
|
343
|
+
"optional",
|
|
344
|
+
"nullable",
|
|
345
|
+
"default",
|
|
346
|
+
"prefault",
|
|
347
|
+
"nonoptional",
|
|
348
|
+
"readonly",
|
|
349
|
+
"catch"
|
|
350
|
+
]);
|
|
351
|
+
function fromZod(schema, seen) {
|
|
352
|
+
if (!isRecord(schema) || seen.has(schema) || !isRecord(schema._zod)) return void 0;
|
|
353
|
+
const inner = new Set(seen).add(schema);
|
|
354
|
+
const def = schema._zod.def;
|
|
355
|
+
if (!isRecord(def)) return void 0;
|
|
356
|
+
const marks = withMarks(schema._zod.optin === "optional", zodSensitive(schema));
|
|
357
|
+
switch (def.type) {
|
|
358
|
+
case "object": {
|
|
359
|
+
if (!isRecord(def.shape)) return marks(void 0);
|
|
360
|
+
const properties = {};
|
|
361
|
+
for (const [key, child] of Object.entries(def.shape)) {
|
|
362
|
+
const shape = fromZod(child, inner);
|
|
363
|
+
if (shape) properties[key] = shape;
|
|
364
|
+
}
|
|
365
|
+
return marks({ properties });
|
|
366
|
+
}
|
|
367
|
+
case "array": return marks({
|
|
368
|
+
item: fromZod(def.element, inner) ?? {},
|
|
369
|
+
list: true
|
|
370
|
+
});
|
|
371
|
+
case "union": return marks(mergeAll(asList(def.options).map((option) => fromZod(option, inner))));
|
|
372
|
+
case "intersection": return marks(intersectAll([fromZod(def.left, inner), fromZod(def.right, inner)]));
|
|
373
|
+
case "pipe":
|
|
374
|
+
if (isRecord(def.in) && isRecord(def.in._zod) && isRecord(def.in._zod.def)) {
|
|
375
|
+
if (def.in._zod.def.type === "transform") return marks(void 0);
|
|
376
|
+
}
|
|
377
|
+
return marks(fromZod(def.in, inner));
|
|
378
|
+
default:
|
|
379
|
+
if (typeof def.type === "string" && ZOD_WRAPPERS.has(def.type)) return marks(fromZod(def.innerType, inner));
|
|
380
|
+
return marks(void 0);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** `.meta()` read back: Zod returns the schema's registered metadata. */
|
|
384
|
+
function zodSensitive(schema) {
|
|
385
|
+
if (typeof schema.meta !== "function") return false;
|
|
386
|
+
try {
|
|
387
|
+
const meta = schema.meta();
|
|
388
|
+
return isRecord(meta) && meta.sensitive === true;
|
|
389
|
+
} catch {
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** Valibot wrappers whose `wrapped` schema is the field's real type. */
|
|
394
|
+
var VALIBOT_WRAPPERS = /* @__PURE__ */ new Set([
|
|
395
|
+
"optional",
|
|
396
|
+
"exact_optional",
|
|
397
|
+
"nullable",
|
|
398
|
+
"nullish",
|
|
399
|
+
"undefinedable",
|
|
400
|
+
"non_optional",
|
|
401
|
+
"non_nullable",
|
|
402
|
+
"non_nullish"
|
|
403
|
+
]);
|
|
404
|
+
/** Valibot wrappers that let the field be absent. */
|
|
405
|
+
var VALIBOT_OPTIONAL = /* @__PURE__ */ new Set([
|
|
406
|
+
"optional",
|
|
407
|
+
"exact_optional",
|
|
408
|
+
"nullish",
|
|
409
|
+
"undefinedable"
|
|
410
|
+
]);
|
|
411
|
+
var VALIBOT_OBJECTS = /* @__PURE__ */ new Set([
|
|
412
|
+
"object",
|
|
413
|
+
"loose_object",
|
|
414
|
+
"strict_object",
|
|
415
|
+
"object_with_rest"
|
|
416
|
+
]);
|
|
417
|
+
function fromValibot(schema, seen) {
|
|
418
|
+
if (!isRecord(schema) || seen.has(schema)) return void 0;
|
|
419
|
+
const inner = new Set(seen).add(schema);
|
|
420
|
+
const sensitive = Array.isArray(schema.pipe) && schema.pipe.some((action) => isRecord(action) && action.kind === "metadata" && isRecord(action.metadata) && action.metadata.sensitive === true);
|
|
421
|
+
const type = schema.type;
|
|
422
|
+
const marks = withMarks(typeof type === "string" && VALIBOT_OPTIONAL.has(type), sensitive);
|
|
423
|
+
if (typeof type !== "string") return marks(void 0);
|
|
424
|
+
if (VALIBOT_WRAPPERS.has(type)) return marks(fromValibot(schema.wrapped, inner));
|
|
425
|
+
if (type === "array") return marks({
|
|
426
|
+
item: fromValibot(schema.item, inner) ?? {},
|
|
427
|
+
list: true
|
|
428
|
+
});
|
|
429
|
+
if (type === "union" || type === "variant") return marks(mergeAll(asList(schema.options).map((option) => fromValibot(option, inner))));
|
|
430
|
+
if (type === "intersect") return marks(intersectAll(asList(schema.options).map((option) => fromValibot(option, inner))));
|
|
431
|
+
if (VALIBOT_OBJECTS.has(type) && isRecord(schema.entries)) {
|
|
432
|
+
const properties = {};
|
|
433
|
+
for (const [key, child] of Object.entries(schema.entries)) {
|
|
434
|
+
const shape = fromValibot(child, inner);
|
|
435
|
+
if (shape) properties[key] = shape;
|
|
436
|
+
}
|
|
437
|
+
return marks({ properties });
|
|
438
|
+
}
|
|
439
|
+
return marks(void 0);
|
|
440
|
+
}
|
|
441
|
+
function fromJsonSchema(node, root, refs) {
|
|
442
|
+
const marks = withMarks(false, node.sensitive === true);
|
|
443
|
+
const ref = node.$ref;
|
|
444
|
+
if (typeof ref === "string") {
|
|
445
|
+
if (refs.has(ref)) return marks(void 0);
|
|
446
|
+
const target = resolveRef(root, ref);
|
|
447
|
+
if (!target) return marks(void 0);
|
|
448
|
+
return marks(fromJsonSchema(target, root, new Set(refs).add(ref)));
|
|
449
|
+
}
|
|
450
|
+
const branches = node.anyOf ?? node.oneOf;
|
|
451
|
+
if (Array.isArray(branches)) return marks(mergeAll(branches.filter((b) => isRecord(b) && b.type !== "null").map((b) => fromJsonSchema(b, root, refs))));
|
|
452
|
+
if (Array.isArray(node.allOf)) return marks(intersectAll(node.allOf.filter(isRecord).map((part) => fromJsonSchema(part, root, refs))));
|
|
453
|
+
if ((Array.isArray(node.type) ? node.type : [node.type]).includes("array") && isRecord(node.items)) return marks({
|
|
454
|
+
item: fromJsonSchema(node.items, root, refs) ?? {},
|
|
455
|
+
list: true
|
|
456
|
+
});
|
|
457
|
+
if (isRecord(node.properties)) {
|
|
458
|
+
const required = new Set(asList(node.required));
|
|
459
|
+
const properties = {};
|
|
460
|
+
for (const [key, child] of Object.entries(node.properties)) {
|
|
461
|
+
const shape = isRecord(child) ? fromJsonSchema(child, root, refs) : void 0;
|
|
462
|
+
if (shape) properties[key] = required.has(key) ? shape : {
|
|
463
|
+
...shape,
|
|
464
|
+
optional: true
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
return marks({ properties });
|
|
468
|
+
}
|
|
469
|
+
return marks(void 0);
|
|
470
|
+
}
|
|
471
|
+
/** Resolve a local `#/$defs/...` or `#/definitions/...` reference. */
|
|
472
|
+
function resolveRef(root, ref) {
|
|
473
|
+
if (!ref.startsWith("#/")) return void 0;
|
|
474
|
+
let node = root;
|
|
475
|
+
for (const segment of ref.slice(2).split("/")) {
|
|
476
|
+
if (!isRecord(node)) return void 0;
|
|
477
|
+
node = node[segment.replaceAll("~1", "/").replaceAll("~0", "~")];
|
|
478
|
+
}
|
|
479
|
+
return isRecord(node) ? node : void 0;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* One shape for the branches of a union. A field is sensitive if any branch
|
|
483
|
+
* marks it, a list only if every branch declares it one, and optional if any
|
|
484
|
+
* branch lacks it. A branch with no shape makes nothing a list, but its
|
|
485
|
+
* siblings' marks still apply.
|
|
486
|
+
*/
|
|
487
|
+
function mergeAll(shapes) {
|
|
488
|
+
if (shapes.length === 0) return void 0;
|
|
489
|
+
return shapes.reduce((merged, shape, i) => i === 0 ? shape ?? {} : merge(merged ?? {}, shape ?? {}), void 0);
|
|
490
|
+
}
|
|
491
|
+
function merge(a, b) {
|
|
492
|
+
const out = {};
|
|
493
|
+
if (a.sensitive || b.sensitive) out.sensitive = true;
|
|
494
|
+
if (a.optional || b.optional) out.optional = true;
|
|
495
|
+
if (a.list && b.list) out.list = true;
|
|
496
|
+
if (a.item || b.item) out.item = merge(a.item ?? {}, b.item ?? {});
|
|
497
|
+
if (a.properties || b.properties) {
|
|
498
|
+
const properties = {};
|
|
499
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
|
|
500
|
+
for (const key of keys) {
|
|
501
|
+
const left = a.properties?.[key];
|
|
502
|
+
const right = b.properties?.[key];
|
|
503
|
+
properties[key] = left && right ? merge(left, right) : {
|
|
504
|
+
...left ?? right,
|
|
505
|
+
optional: true
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
out.properties = properties;
|
|
509
|
+
}
|
|
510
|
+
return out;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* One shape for the parts of an intersection, which all apply: a field is a
|
|
514
|
+
* list or sensitive if any part says so, and optional only if every part
|
|
515
|
+
* that declares it lets it be absent.
|
|
516
|
+
*/
|
|
517
|
+
function intersectAll(shapes) {
|
|
518
|
+
const present = shapes.filter((shape) => shape !== void 0);
|
|
519
|
+
if (present.length === 0) return void 0;
|
|
520
|
+
return present.reduce(intersect);
|
|
521
|
+
}
|
|
522
|
+
function intersect(a, b) {
|
|
523
|
+
const out = {};
|
|
524
|
+
if (a.sensitive || b.sensitive) out.sensitive = true;
|
|
525
|
+
if (a.optional && b.optional) out.optional = true;
|
|
526
|
+
if (a.list || b.list) out.list = true;
|
|
527
|
+
if (a.item || b.item) out.item = intersect(a.item ?? {}, b.item ?? {});
|
|
528
|
+
if (a.properties || b.properties) {
|
|
529
|
+
const properties = {};
|
|
530
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(a.properties ?? {}), ...Object.keys(b.properties ?? {})]);
|
|
531
|
+
for (const key of keys) {
|
|
532
|
+
const left = a.properties?.[key];
|
|
533
|
+
const right = b.properties?.[key];
|
|
534
|
+
properties[key] = left && right ? intersect(left, right) : left ?? right ?? {};
|
|
535
|
+
}
|
|
536
|
+
out.properties = properties;
|
|
537
|
+
}
|
|
538
|
+
return out;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Give every field the schema declares as a list the same shape whatever its
|
|
542
|
+
* count. `parseFormData` reads a repeated name as an array, a single value as
|
|
543
|
+
* a scalar, and an absent name not at all; here a scalar becomes `[value]`,
|
|
544
|
+
* and an absent or blank required list becomes `[]` (blanks are dropped from
|
|
545
|
+
* a list, as `parseFormData` drops them from a repeated name). An optional
|
|
546
|
+
* list that was not submitted (or was one blank) is absent, so `.optional()` still means
|
|
547
|
+
* "not sent". Lists inside lists and objects are normalized too. An object
|
|
548
|
+
* where a list is declared (an indexed list with a gap) is left for the
|
|
549
|
+
* schema to reject.
|
|
550
|
+
*
|
|
551
|
+
* Returns a copy; the input is not written to.
|
|
552
|
+
*/
|
|
553
|
+
function normalizeListFields(values, shape) {
|
|
554
|
+
if (!shape) return values;
|
|
555
|
+
return normalize(values, shape);
|
|
556
|
+
}
|
|
557
|
+
function normalize(value, shape) {
|
|
558
|
+
if (shape.list && shape.item) {
|
|
559
|
+
if (value === void 0 || value === "") return shape.optional ? void 0 : [];
|
|
560
|
+
if (isPlainObject(value)) return value;
|
|
561
|
+
const list = Array.isArray(value) ? value : [value];
|
|
562
|
+
const item = shape.item;
|
|
563
|
+
return list.map((v) => normalize(v, item));
|
|
564
|
+
}
|
|
565
|
+
if (shape.properties && isPlainObject(value)) {
|
|
566
|
+
const out = { ...value };
|
|
567
|
+
for (const [key, child] of Object.entries(shape.properties)) {
|
|
568
|
+
const current = Object.hasOwn(out, key) ? out[key] : void 0;
|
|
569
|
+
if (key === "__proto__") continue;
|
|
570
|
+
const normalized = normalize(current, child);
|
|
571
|
+
if (normalized === void 0) delete out[key];
|
|
572
|
+
else out[key] = normalized;
|
|
573
|
+
}
|
|
574
|
+
return out;
|
|
575
|
+
}
|
|
576
|
+
return value;
|
|
577
|
+
}
|
|
578
|
+
/** Apply a node's own marks to the shape read from what it wraps. */
|
|
579
|
+
function withMarks(optional, sensitive) {
|
|
580
|
+
return (shape) => {
|
|
581
|
+
if (!optional && !sensitive) return shape;
|
|
582
|
+
return {
|
|
583
|
+
...shape,
|
|
584
|
+
...optional ? { optional: true } : {},
|
|
585
|
+
...sensitive ? { sensitive: true } : {}
|
|
586
|
+
};
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function asList(value) {
|
|
590
|
+
return Array.isArray(value) ? value : [];
|
|
591
|
+
}
|
|
592
|
+
function isRecord(value) {
|
|
593
|
+
return typeof value === "object" && value !== null;
|
|
594
|
+
}
|
|
595
|
+
function isPlainObject(value) {
|
|
596
|
+
return isRecord(value) && !Array.isArray(value) && !(value instanceof Blob);
|
|
597
|
+
}
|
|
165
598
|
//#endregion
|
|
166
599
|
//#region src/server/action-client.ts
|
|
167
600
|
/**
|
|
@@ -174,6 +607,10 @@ function stripSensitiveFields(value, predicate) {
|
|
|
174
607
|
* 1. Direct call: action(input) → Promise<ActionResult>
|
|
175
608
|
* 2. React useActionState: (prevState, formData) => Promise<ActionResult>
|
|
176
609
|
*
|
|
610
|
+
* Types live in `action-types.ts`, schema handling in `action-schema.ts`, and
|
|
611
|
+
* the schema's declared shape (list fields, sensitive fields) in
|
|
612
|
+
* `schema-introspection.ts`.
|
|
613
|
+
*
|
|
177
614
|
* See design/08-forms-and-actions.md §"Middleware and Server Actions"
|
|
178
615
|
*/
|
|
179
616
|
/**
|
|
@@ -194,10 +631,6 @@ var ActionError = class extends Error {
|
|
|
194
631
|
this.data = data;
|
|
195
632
|
}
|
|
196
633
|
};
|
|
197
|
-
/** Check if a schema implements the Standard Schema protocol. */
|
|
198
|
-
function isStandardSchema(schema) {
|
|
199
|
-
return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"].validate === "function";
|
|
200
|
-
}
|
|
201
634
|
/**
|
|
202
635
|
* Run middleware array or single function. Returns merged context.
|
|
203
636
|
*/
|
|
@@ -217,38 +650,6 @@ async function runActionMiddleware(middleware) {
|
|
|
217
650
|
return await middleware();
|
|
218
651
|
}
|
|
219
652
|
/**
|
|
220
|
-
* Extract validation errors from a schema error.
|
|
221
|
-
* Supports Zod's flatten() and generic issues array.
|
|
222
|
-
*/
|
|
223
|
-
function extractValidationErrors(error) {
|
|
224
|
-
if (typeof error.flatten === "function") return error.flatten().fieldErrors;
|
|
225
|
-
if (error.issues) {
|
|
226
|
-
const errors = {};
|
|
227
|
-
for (const issue of error.issues) {
|
|
228
|
-
const path = issue.path?.join(".") ?? "_root";
|
|
229
|
-
if (!errors[path]) errors[path] = [];
|
|
230
|
-
errors[path].push(issue.message);
|
|
231
|
-
}
|
|
232
|
-
return errors;
|
|
233
|
-
}
|
|
234
|
-
return { _root: ["Validation failed"] };
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Extract validation errors from Standard Schema issues.
|
|
238
|
-
*/
|
|
239
|
-
function extractStandardSchemaErrors(issues) {
|
|
240
|
-
const errors = {};
|
|
241
|
-
for (const issue of issues) {
|
|
242
|
-
const path = issue.path?.map((p) => {
|
|
243
|
-
if (typeof p === "object" && p !== null && "key" in p) return String(p.key);
|
|
244
|
-
return String(p);
|
|
245
|
-
}).join(".") ?? "_root";
|
|
246
|
-
if (!errors[path]) errors[path] = [];
|
|
247
|
-
errors[path].push(issue.message);
|
|
248
|
-
}
|
|
249
|
-
return Object.keys(errors).length > 0 ? errors : { _root: ["Validation failed"] };
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
653
|
* Wrap unexpected errors into a safe server error result.
|
|
253
654
|
* ActionError → typed result. Other errors → INTERNAL_ERROR (no leak).
|
|
254
655
|
*
|
|
@@ -287,64 +688,47 @@ function handleActionError(error) {
|
|
|
287
688
|
*/
|
|
288
689
|
function createActionClient(config = {}) {
|
|
289
690
|
function buildAction(schema, fn) {
|
|
691
|
+
let shape;
|
|
692
|
+
let introspected = false;
|
|
693
|
+
const getShape = () => {
|
|
694
|
+
if (!introspected) {
|
|
695
|
+
shape = introspectSchema(schema);
|
|
696
|
+
introspected = true;
|
|
697
|
+
}
|
|
698
|
+
return shape;
|
|
699
|
+
};
|
|
290
700
|
async function actionHandler(...args) {
|
|
291
701
|
const last = args.at(-1);
|
|
292
|
-
const form = last instanceof FormData ? parseFormData(last) : void 0;
|
|
702
|
+
const form = last instanceof FormData ? normalizeListFields(parseFormData(last), getShape()) : void 0;
|
|
293
703
|
const sensitivePredicate = resolveSensitivePredicate(config.stripSensitiveFields, void 0);
|
|
294
704
|
const echo = (value) => {
|
|
295
705
|
const withoutFiles = stripFiles(value);
|
|
296
706
|
if (withoutFiles === void 0) return void 0;
|
|
297
|
-
return stripSensitiveFields(withoutFiles, sensitivePredicate);
|
|
707
|
+
return stripSensitiveFields(withoutFiles, sensitivePredicate, getShape());
|
|
298
708
|
};
|
|
299
709
|
try {
|
|
300
710
|
const ctx = await runActionMiddleware(config.middleware);
|
|
301
711
|
const rawInput = schema && form ? form : last;
|
|
302
712
|
const submitted = form ?? rawInput;
|
|
303
|
-
const buildSubmittedValues = () => echo(submitted);
|
|
304
713
|
if (config.fileSizeLimit !== void 0 && submitted && typeof submitted === "object") {
|
|
305
714
|
const fileSizeErrors = validateFileSizes(submitted, config.fileSizeLimit);
|
|
306
715
|
if (fileSizeErrors) return {
|
|
307
716
|
validationErrors: fileSizeErrors,
|
|
308
|
-
submittedValues:
|
|
717
|
+
submittedValues: echo(submitted)
|
|
309
718
|
};
|
|
310
719
|
}
|
|
311
|
-
|
|
312
|
-
let input;
|
|
720
|
+
let input = rawInput;
|
|
313
721
|
if (schema) {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
if (result.issues) {
|
|
318
|
-
const validationErrors = extractStandardSchemaErrors(result.issues);
|
|
319
|
-
logValidationFailure(validationErrors);
|
|
320
|
-
return {
|
|
321
|
-
validationErrors,
|
|
322
|
-
submittedValues
|
|
323
|
-
};
|
|
324
|
-
}
|
|
325
|
-
input = result.value;
|
|
326
|
-
} else if (typeof schema.safeParse === "function") {
|
|
327
|
-
const result = schema.safeParse(rawInput);
|
|
328
|
-
if (!result.success) {
|
|
329
|
-
const validationErrors = extractValidationErrors(result.error);
|
|
330
|
-
logValidationFailure(validationErrors);
|
|
331
|
-
return {
|
|
332
|
-
validationErrors,
|
|
333
|
-
submittedValues
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
input = result.data;
|
|
337
|
-
} else try {
|
|
338
|
-
input = schema.parse(rawInput);
|
|
339
|
-
} catch (parseError) {
|
|
340
|
-
const validationErrors = extractValidationErrors(parseError);
|
|
341
|
-
logValidationFailure(validationErrors);
|
|
722
|
+
const validation = validateWithSchema(schema, rawInput);
|
|
723
|
+
if (!validation.ok) {
|
|
724
|
+
logValidationFailure(validation.validationErrors);
|
|
342
725
|
return {
|
|
343
|
-
validationErrors,
|
|
344
|
-
submittedValues
|
|
726
|
+
validationErrors: validation.validationErrors,
|
|
727
|
+
submittedValues: echo(submitted)
|
|
345
728
|
};
|
|
346
729
|
}
|
|
347
|
-
|
|
730
|
+
input = validation.value;
|
|
731
|
+
}
|
|
348
732
|
return { data: await fn({
|
|
349
733
|
ctx,
|
|
350
734
|
input
|
|
@@ -373,40 +757,19 @@ function createActionClient(config = {}) {
|
|
|
373
757
|
};
|
|
374
758
|
}
|
|
375
759
|
/**
|
|
376
|
-
* Convenience wrapper for the common case: validate input, run handler.
|
|
377
|
-
* No middleware needed.
|
|
378
|
-
*
|
|
379
|
-
* @example
|
|
380
|
-
* ```ts
|
|
381
|
-
* 'use server'
|
|
382
|
-
* import { validated } from '@timber-js/app/server'
|
|
383
|
-
* import { z } from 'zod'
|
|
384
|
-
*
|
|
385
|
-
* export const createTodo = validated(
|
|
386
|
-
* z.object({ title: z.string().min(1) }),
|
|
387
|
-
* async (input) => {
|
|
388
|
-
* await db.todos.create(input)
|
|
389
|
-
* }
|
|
390
|
-
* )
|
|
391
|
-
* ```
|
|
392
|
-
*/
|
|
393
|
-
function validated(schema, handler) {
|
|
394
|
-
return createActionClient().schema(schema).action(async ({ input }) => handler(input));
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
760
|
* Log validation failures in dev mode so developers can see what went wrong.
|
|
398
761
|
* In production, validation errors are only returned to the client.
|
|
399
762
|
*/
|
|
400
763
|
function logValidationFailure(errors) {
|
|
401
764
|
if (!isDebug()) return;
|
|
402
|
-
const fields = Object.entries(errors).map(([field, messages]) => ` ${field}: ${messages.join(", ")}`).join("\n");
|
|
765
|
+
const fields = Object.entries(errors).map(([field, messages]) => ` ${field}: ${(messages ?? []).join(", ")}`).join("\n");
|
|
403
766
|
console.warn(`[timber] action schema validation failed:\n${fields}`);
|
|
404
767
|
}
|
|
405
768
|
/**
|
|
406
769
|
* Validate that all File objects in the input are within the size limit.
|
|
407
770
|
* Returns validation errors keyed by field name, or null if all files are ok.
|
|
408
771
|
* Keys are dot paths (`rows.0.file`), the form a field name and a Standard
|
|
409
|
-
* Schema error use, so `
|
|
772
|
+
* Schema error use, so `errors.field()` finds a file in a list.
|
|
410
773
|
*/
|
|
411
774
|
function validateFileSizes(input, limit) {
|
|
412
775
|
const limitKb = Math.round(limit / 1024);
|
|
@@ -449,6 +812,6 @@ function stripFilesFrom(value) {
|
|
|
449
812
|
return result;
|
|
450
813
|
}
|
|
451
814
|
//#endregion
|
|
452
|
-
export { ActionError, RedirectType, addSpanEvent, coerce, createActionClient, deny, getCookieJar, getHeaders, getSegmentParams, getSpanId, getTraceId, parseFormData, redirect, redirectExternal, revalidatePath, revalidateTag,
|
|
815
|
+
export { ActionError, RedirectType, addSpanEvent, coerce, createActionClient, deny, getCookieJar, getHeaders, getSegmentParams, getSpanId, getTraceId, parseFormData, redirect, redirectExternal, revalidatePath, revalidateTag, waitUntil, withSpan };
|
|
453
816
|
|
|
454
817
|
//# sourceMappingURL=index.js.map
|