Open History to see the last commit
1import { createOutput } from '../validationOutput.lib'
2import { createErrorMap } from '../validation.public'
3import { parseStandardSchemaIssues } from '../standardSchema.lib'
4import { isNotNil } from '../utils.lib'
5import { isErrorResult } from './errors.lib'
6import {
7 ABORTED_CALL,
8 THROWN_ERROR,
9 executeValidator,
10 isFieldValidateContext,
11 isServerValidateContext,
12 parseFieldIssues,
13 runMaybeDebouncedValidator,
14 shouldRunValidator,
15} from './execution.lib'
16import type { AnyInternalValidatorInstance } from '../ValidatorInstance.lib'
17import type { AnyInternalFieldApi } from '../FieldApi/FieldApi.lib'
18import type {
19 FieldValidateResult,
20 FormValidateResult,
21} from '../validation.public'
22import type {
23 AbortedCall,
24 AnyValidatorContext,
25 FieldInputContext,
26 FormInputContext,
27 InputContext,
28 ThrownError,
29 ValidateContext,
30 ValidateResult,
31 ValidatorExecutionResult,
32} from './execution.lib'
33β
34export interface PipelineResult<in out T> {
35 validatorInstance: AnyInternalValidatorInstance
36 result: T
37 output: any | null
38 hasOutput?: boolean
39}
40β
41interface PendingPipelineResult<in out T> {
42 validatorInstance: AnyInternalValidatorInstance
43 result: T
44}
45β
46interface ValidatorPipelineArgs<in out TResult extends ValidateResult> {
47 context: InputContext
48 pipeline: ReadonlyArray<AnyInternalValidatorInstance>
49 hasFailedBefore: boolean
50 getContext: (inputContext: ValidateContext) => AnyValidatorContext
51 scope: 'field' | 'form'
52 validatorInstancesToRun?: ReadonlySet<AnyInternalValidatorInstance> | null
53 onResult?: (result: PipelineResult<TResult>) => void
54}
55β
56type PendingPromises<TResult> = Array<
57 Promise<
58 PendingPipelineResult<
59 ValidatorExecutionResult<TResult> | AbortedCall | ThrownError
60 >
61 >
62>
63β
64/**
65 * Accepts a batch of pending results into the pipeline's instance-keyed map.
66 *
67 * Aborted and thrown results are excluded. Submit output is committed
68 * before `onResult` observes the accepted result.
69 */
70async function flushPendingResults<TResult extends ValidateResult>(
71 pending: PendingPromises<TResult>,
72 results: Map<AnyInternalValidatorInstance, PipelineResult<TResult>>,
73 shouldCommitOutput: boolean,
74 onResult?: (result: PipelineResult<TResult>) => void,
75): Promise<{ hasErrors: boolean; thrownError: unknown | null }> {
76 let hasErrors = false
77 let thrownError: unknown | null = null
78β
79 await Promise.all(
80 pending.map(async (promise) => {
81 const result = await promise
82β
83 const executionResult = result.result
84β
85 if (executionResult === ABORTED_CALL) {
86 return
87 }
88β
89 // Check if this is a thrown error from a validator
90 if (
91 isNotNil(executionResult) &&
92 typeof executionResult === 'object' &&
93 THROWN_ERROR in executionResult
94 ) {
95 thrownError = executionResult.error
96 return
97 }
98β
99 if (isErrorResult(executionResult.result)) {
100 hasErrors = true
101 }
102β
103 const publicResult: PipelineResult<TResult> = {
104 validatorInstance: result.validatorInstance,
105 result: executionResult.result,
106 output: executionResult.output,
107 hasOutput: executionResult.hasOutput,
108 }
109β
110 if (shouldCommitOutput) {
111 result.validatorInstance.setOutput(executionResult)
112 }
113 results.set(result.validatorInstance, publicResult)
114 onResult?.(publicResult)
115 }),
116 )
117β
118 return { hasErrors, thrownError }
119}
120β
121/**
122 * Runs eligible validator instances while preserving configured result order.
123 *
124 * Pending validators are flushed before `bailIfInvalid` decisions. Form and
125 * group submit pipelines first cancel prior executions and clear prior schema
126 * outputs so skipped validators cannot expose stale submit data.
127 */
128export async function runValidatorPipeline<TResult extends ValidateResult>({
129 pipeline,
130 context,
131 hasFailedBefore = false,
132 getContext,
133 onResult,
134 scope,
135 validatorInstancesToRun = null,
136}: ValidatorPipelineArgs<TResult>): Promise<{
137 results: Array<PipelineResult<TResult>>
138 hasErrors: boolean
139 thrownError: unknown | null
140}> {
141 let pending: PendingPromises<TResult> = []
142 const results = new Map<
143 AnyInternalValidatorInstance,
144 PipelineResult<TResult>
145 >()
146 const shouldCommitOutput =
147 context.event === 'submit' && context.scope !== 'field'
148β
149 if (shouldCommitOutput) {
150 pipeline.forEach((validatorInstance) => {
151 validatorInstance.cancelExecution()
152 validatorInstance.clearOutput()
153 })
154 }
155β
156 let hasErrors = hasFailedBefore
157 let thrownError: unknown | null = null
158β
159 const flush = async (): Promise<void> => {
160 const { hasErrors: didError, thrownError: flushedThrownError } =
161 await flushPendingResults(pending, results, shouldCommitOutput, onResult)
162β
163 pending = []
164 hasErrors ||= didError
165 if (flushedThrownError !== null) {
166 thrownError = flushedThrownError
167 }
168 }
169β
170 for (const validatorInstance of pipeline) {
171 const validator = validatorInstance.definition
172β
173 if (
174 validatorInstancesToRun &&
175 !validatorInstancesToRun.has(validatorInstance)
176 ) {
177 continue
178 }
179β
180 if (!shouldRunValidator(validator, context)) {
181 continue
182 }
183β
184 if (validator.bailIfInvalid) {
185 await flush()
186β
187 if (hasErrors || thrownError !== null) {
188 break
189 }
190 }
191β
192 const promise = runMaybeDebouncedValidator<TResult>({
193 validatorInstance,
194 context,
195 onExecute: (ctx) => {
196 return executeValidator<TResult>(validator, getContext(ctx), scope)
197 },
198 }).then<
199 PendingPipelineResult<
200 ValidatorExecutionResult<TResult> | AbortedCall | ThrownError
201 >
202 >((result) => ({
203 validatorInstance,
204 result,
205 }))
206β
207 pending.push(promise)
208 }
209β
210 await flush()
211β
212 return {
213 results: pipeline.flatMap((validatorInstance) => {
214 const result = results.get(validatorInstance)
215 return result ? [result] : []
216 }),
217 hasErrors,
218 thrownError,
219 }
220}
221β
222interface FormValidatorPipelineArgs {
223 pipeline: ReadonlyArray<AnyInternalValidatorInstance>
224 context: FormInputContext
225 /**
226 * @private
227 * Whether previous pipelines have reported an error or not.
228 */
229 hasFailedBefore: boolean
230 onResult?: (result: PipelineResult<FormValidateResult<any>>) => void
231}
232β
233export interface FormValidatorPipelineResult {
234 results: Array<PipelineResult<FormValidateResult<any>>>
235 hasErrors: boolean
236 thrownError: unknown | null
237}
238β
239/** Runs the shared pipeline with form-scoped values and issue parsing. */
240export function runFormValidatorPipeline({
241 pipeline,
242 context,
243 onResult,
244 hasFailedBefore,
245}: FormValidatorPipelineArgs): Promise<FormValidatorPipelineResult> {
246 return runValidatorPipeline<FormValidateResult<any>>({
247 pipeline,
248 context,
249 onResult,
250 hasFailedBefore,
251 getContext: (ctx) => {
252 if (isServerValidateContext(ctx)) {
253 throw new Error('Server validation cannot run through client pipeline')
254 }
255β
256 const formValidationContext = {
257 event: ctx.event,
258 formApi: ctx.formApi,
259 signal: ctx.signal,
260 value: ctx.formApi.state.values,
261 createErrorMap,
262 createOutput,
263 parseIssues: (
264 issues: Parameters<typeof parseStandardSchemaIssues>[0],
265 ) =>
266 parseStandardSchemaIssues(issues, ctx.formApi.state.values, 'form'),
267 }
268β
269 if (!isFieldValidateContext(ctx)) {
270 return {
271 ...formValidationContext,
272 triggerFieldApi: ctx.triggerFieldApi,
273 }
274 }
275β
276 return {
277 ...formValidationContext,
278 fieldApi: ctx.fieldApi,
279 }
280 },
281 scope: 'form',
282 })
283}
284β
285interface FieldValidatorPipelineArgs {
286 pipeline: ReadonlyArray<AnyInternalValidatorInstance>
287 context: FieldInputContext
288 onResult?: (result: PipelineResult<FieldValidateResult>) => void
289 /**
290 * @private
291 * When an incoming watched field notifies, we should only run validators
292 * that are actually interested in it.
293 */
294 validatorInstancesToRun?: ReadonlySet<AnyInternalValidatorInstance> | null
295}
296β
297export interface FieldValidatorPipelineResult {
298 results: Array<PipelineResult<FieldValidateResult>>
299 hasErrors: boolean
300 thrownError: unknown | null
301}
302β
303/**
304 * Runs the shared pipeline with field-scoped values and issue parsing.
305 *
306 * Killed fields resolve to an empty result without executing validators.
307 */
308export function runFieldValidatorPipeline({
309 pipeline,
310 context,
311 onResult,
312 validatorInstancesToRun = null,
313}: FieldValidatorPipelineArgs): Promise<FieldValidatorPipelineResult> {
314 const fieldApi = context.fieldApi as AnyInternalFieldApi
315β
316 if (fieldApi._isKilled)
317 return Promise.resolve({
318 results: [],
319 hasErrors: false,
320 thrownError: null,
321 })
322β
323 return runValidatorPipeline<FieldValidateResult>({
324 pipeline,
325 context,
326 onResult,
327 // No use case for configuring this outside of field pipeline yet
328 hasFailedBefore: false,
329 getContext: (ctx) => {
330 if (isServerValidateContext(ctx)) {
331 throw new Error('Server validation cannot run through field pipeline')
332 }
333β
334 return {
335 event: context.event,
336 formApi: context.formApi,
337 signal: ctx.signal,
338 fieldApi: context.fieldApi,
339 value: context.fieldApi.value,
340 parseIssues: parseFieldIssues,
341 }
342 },
343 scope: 'field',
344 validatorInstancesToRun,
345 })
346}