Open History to see the last commit
1import {
2 isStandardSchema,
3 parseStandardSchema,
4 parseStandardSchemaIssues,
5} from '../standardSchema.lib'
6import { VALIDATION_OUTPUT, isValidationOutput } from '../validationOutput.lib'
7import type { AnyInternalValidatorInstance } from '../ValidatorInstance.lib'
8import type { InternalFormApi } from '../FormApi/FormApi.lib'
9import type { AnyInternalFieldApi } from '../FieldApi/FieldApi.lib'
10import type {
11 FieldValidateResult,
12 FieldValidator,
13 FieldValidatorContext,
14 FormGroupValidateResult,
15 FormGroupValidator,
16 FormGroupValidatorContext,
17 FormValidateResult,
18 FormValidator,
19 FormValidatorContext,
20 ServerFormValidatorContext,
21 ValidationPredicateContext,
22 ValidationTriggerOption,
23 Validator,
24} from '../validation.public'
25β
26type FormValidateContext = {
27 scope: 'form'
28 event: Exclude<FormValidatorContext<any>['event'], 'server'>
29 signal: AbortSignal
30 formApi: InternalFormApi<any, any, any>
31 triggerFieldApi?: AnyInternalFieldApi
32}
33type ServerPipelineValidateContext = {
34 scope: 'server'
35 event: 'server'
36 signal: AbortSignal
37 formApi: undefined
38}
39type FieldValidateContext = Omit<
40 FieldValidatorContext<any, any, any>,
41 'value' | 'parseIssues'
42> & { scope: 'field' }
43type FormGroupValidateContext = Omit<
44 FormGroupValidatorContext<any>,
45 'value' | 'parseIssues' | 'createErrorMap' | 'createOutput'
46> & { scope: 'group' }
47export type FormInputContext = Omit<FormValidateContext, 'signal'>
48type ServerFormInputContext = Omit<ServerPipelineValidateContext, 'signal'>
49export type FieldInputContext = Omit<FieldValidateContext, 'signal'>
50type FormGroupInputContext = Omit<FormGroupValidateContext, 'signal'>
51β
52export type InputContext =
53 | FormInputContext
54 | ServerFormInputContext
55 | FieldInputContext
56 | FormGroupInputContext
57export type ValidateContext =
58 | FormValidateContext
59 | ServerPipelineValidateContext
60 | FieldValidateContext
61 | FormGroupValidateContext
62export type ValidateResult =
63 FormValidateResult<any> | FormGroupValidateResult<any> | FieldValidateResult
64type AnyPipelineValidator =
65 | FormValidator<any>
66 | FormGroupValidator<any>
67 | FieldValidator<any, any, any>
68 | Validator<any, any, any, any>
69export type AnyValidatorContext =
70 | FormValidatorContext<any>
71 | ServerFormValidatorContext<any>
72 | FormGroupValidatorContext<any>
73 | FieldValidatorContext<any, any, any>
74β
75function isServerContext(ctx: InputContext): ctx is ServerFormInputContext {
76 return ctx.event === 'server'
77}
78β
79/** Narrows an input context to a field-owned validation pipeline. */
80function isFieldContext(ctx: InputContext): ctx is FieldInputContext {
81 return ctx.scope === 'field'
82}
83β
84/** Narrows an input context to a form-group-owned validation pipeline. */
85function isGroupContext(ctx: InputContext): ctx is FormGroupInputContext {
86 return ctx.scope === 'group'
87}
88β
89/** Narrows an executing context to the server pipeline variant. */
90export function isServerValidateContext(
91 ctx: ValidateContext,
92): ctx is ServerPipelineValidateContext {
93 return ctx.event === 'server'
94}
95β
96/** Narrows an executing context to the field pipeline variant. */
97export function isFieldValidateContext(
98 ctx: ValidateContext,
99): ctx is FieldValidateContext {
100 return ctx.scope === 'field'
101}
102β
103/** Checks whether a configured trigger is the server-only trigger. */
104function isServerTrigger(
105 trigger: ValidationTriggerOption<any, any, any> | 'server',
106): boolean {
107 return trigger === 'server'
108}
109β
110/** Checks whether a validator participates in server validation. */
111function hasServerTrigger(validator: AnyPipelineValidator): boolean {
112 return validator.triggers.some(isServerTrigger)
113}
114β
115/**
116 * Creates the scope-specific context passed to predicate and debounce callbacks.
117 *
118 * Values are read when the callback is evaluated so it observes the owning
119 * form, group, or field's current state.
120 */
121function getPredicateContext(
122 context: Exclude<InputContext, ServerFormInputContext>,
123): ValidationPredicateContext<any, any> {
124 if (isFieldContext(context)) {
125 return {
126 scope: 'field',
127 formApi: context.formApi,
128 fieldApi: context.fieldApi,
129 value: context.fieldApi.value,
130 }
131 }
132β
133 if (isGroupContext(context)) {
134 return {
135 scope: 'group',
136 formApi: context.formApi,
137 fieldApi: context.triggerFieldApi,
138 groupApi: context.groupApi,
139 value: context.groupApi.value,
140 }
141 }
142β
143 return {
144 scope: 'form',
145 formApi: context.formApi,
146 fieldApi: context.triggerFieldApi,
147 value: context.formApi.state.values,
148 }
149}
150β
151/** Parses Standard Schema issues as errors owned directly by a field. */
152export function parseFieldIssues(
153 issues: Parameters<FieldValidatorContext<any, any, any>['parseIssues']>[0],
154) {
155 return parseStandardSchemaIssues(issues, undefined, 'field')
156}
157β
158export const ABORTED_CALL = Symbol('ABORTED_CALL')
159export const THROWN_ERROR = Symbol('THROWN_ERROR')
160β
161export type AbortedCall = typeof ABORTED_CALL
162export type ThrownError = { [THROWN_ERROR]: true; error: unknown }
163export interface ValidatorExecutionResult<in out TResult> {
164 result: TResult
165 output: any | null
166 hasOutput: boolean
167}
168β
169interface PendingDebouncedCall<in out TResult extends ValidateResult> {
170 context: ValidateContext
171 resolve: (
172 value: ValidatorExecutionResult<TResult> | AbortedCall | ThrownError,
173 ) => void
174 reject: (error: unknown) => void
175}
176β
177type PipelineValidatorInstance<TResult extends ValidateResult> =
178 AnyInternalValidatorInstance<(call: PendingDebouncedCall<TResult>) => void>
179β
180function getEnabledState(
181 booleanOrFn: boolean | ((context: any) => boolean),
182 context: InputContext,
183): boolean {
184 if (typeof booleanOrFn === 'boolean') return booleanOrFn
185 if (isServerContext(context)) return false
186β
187 return booleanOrFn(getPredicateContext(context))
188}
189β
190/** Resolves a static delay or evaluates its callback outside server context. */
191function getDebounceMs(
192 numberOrFn: number | ((context: any) => number),
193 context: InputContext,
194): number {
195 if (typeof numberOrFn === 'number') return numberOrFn
196 if (isServerContext(context)) return 0
197β
198 return numberOrFn(getPredicateContext(context))
199}
200β
201/**
202 * Checks whether a trigger matches the current event and passes its condition.
203 *
204 * String triggers match directly. Object triggers additionally evaluate their
205 * `when` predicate, which defaults to enabled.
206 */
207export function isValidationTriggerEnabled(
208 trigger: ValidationTriggerOption<any, any, any> | 'server',
209 context: InputContext,
210): boolean {
211 if (typeof trigger === 'string') {
212 return trigger === context.event
213 }
214β
215 if (trigger.trigger !== context.event) {
216 return false
217 }
218β
219 const { when: enabled = true } = trigger
220β
221 return getEnabledState(enabled, context)
222}
223β
224/** Selects a validator using server, submit, or configured event semantics. */
225export function shouldRunValidator(
226 validator: AnyPipelineValidator,
227 context: InputContext,
228): boolean {
229 if (isServerContext(context)) {
230 return hasServerTrigger(validator)
231 }
232β
233 const { skipOnSubmit = false } = validator
234β
235 if (context.event === 'submit') {
236 return !getEnabledState(skipOnSubmit, context)
237 }
238β
239 return validator.triggers.some((signal) =>
240 isValidationTriggerEnabled(signal, context),
241 )
242}
243β
244/**
245 * Executes a validator and normalizes its result for pipeline processing.
246 *
247 * Schema and branded function outputs retain their payload and presence marker.
248 */
249export async function executeValidator<TResult extends ValidateResult>(
250 validator: AnyPipelineValidator,
251 context: AnyValidatorContext,
252 scope: 'field' | 'form',
253): Promise<ValidatorExecutionResult<TResult>> {
254 const result = isStandardSchema(validator.run)
255 ? await parseStandardSchema(validator.run, context.value, scope)
256 : await validator.run(context)
257β
258 return normalizeValidatorResult(result as TResult)
259}
260β
261/** Separates explicitly branded outputs from ordinary validation returns. */
262export function normalizeValidatorResult<TResult extends ValidateResult>(
263 result: TResult,
264): ValidatorExecutionResult<TResult> {
265 if (isValidationOutput(result)) {
266 return {
267 result: null as TResult,
268 output: result[VALIDATION_OUTPUT],
269 hasOutput: true,
270 }
271 }
272β
273 return { result, output: null, hasOutput: false }
274}
275β
276interface RunMaybeDebouncedValidatorArgs<
277 in out TResult extends ValidateResult,
278> {
279 validatorInstance: PipelineValidatorInstance<TResult>
280 context: InputContext
281 onExecute: (
282 inputContext: ValidateContext,
283 ) => Promise<ValidatorExecutionResult<TResult>>
284}
285β
286/**
287 * Creates a promise that resolves with the internal sentinel when aborted.
288 *
289 * Call `cleanup` after the race settles to release the signal listener.
290 */
291function createAbortPromise(signal: AbortSignal): {
292 promise: Promise<AbortedCall>
293 cleanup: () => void
294} {
295 let onAbort = () => {}
296β
297 const promise = new Promise<AbortedCall>((resolve) => {
298 if (signal.aborted) {
299 resolve(ABORTED_CALL)
300 return
301 }
302β
303 onAbort = () => {
304 signal.removeEventListener('abort', onAbort)
305 resolve(ABORTED_CALL)
306 }
307β
308 signal.addEventListener('abort', onAbort)
309 })
310β
311 return {
312 promise,
313 cleanup: () => {
314 signal.removeEventListener('abort', onAbort)
315 },
316 }
317}
318β
319/**
320 * Races validator execution against its abort signal.
321 *
322 * Abortion suppresses the eventual execution result without requiring the
323 * underlying validator promise to support cancellation.
324 */
325async function executeWithAbort<TResult extends ValidateResult>(
326 context: ValidateContext,
327 onExecute: (
328 inputContext: ValidateContext,
329 ) => Promise<ValidatorExecutionResult<TResult>>,
330): Promise<ValidatorExecutionResult<TResult> | AbortedCall> {
331 if (context.signal.aborted) {
332 return ABORTED_CALL
333 }
334β
335 const { promise: abortPromise, cleanup } = createAbortPromise(context.signal)
336β
337 try {
338 return await Promise.race([
339 Promise.resolve(onExecute(context)),
340 abortPromise,
341 ])
342 } finally {
343 cleanup()
344 }
345}
346β
347/** Resolves debounce duration, forcing immediate submit and server execution. */
348function getValidatorDebounceMs(
349 validator: AnyPipelineValidator,
350 context: InputContext,
351): number {
352 if (context.event === 'submit' || context.event === 'server') return 0
353β
354 const { triggerDebounceMs = 0 } = validator
355β
356 return getDebounceMs(triggerDebounceMs, context)
357}
358β
359/**
360 * Installs the next abort controller on a stable validator instance.
361 *
362 * Installation aborts any previous execution. The returned cleanup clears the
363 * controller only if it is still the instance's active controller.
364 */
365export function createValidatorAbortContext(
366 validatorInstance: AnyInternalValidatorInstance,
367 opts?: { cancelDebouncer?: boolean },
368): {
369 abortController: AbortController
370 signal: AbortSignal
371 cleanup: () => void
372} {
373 if (opts?.cancelDebouncer) {
374 validatorInstance.debouncer?.cancel()
375 }
376β
377 const abortController = new AbortController()
378 const signal = abortController.signal
379β
380 validatorInstance.setAbortController(abortController)
381β
382 return {
383 abortController,
384 signal,
385 cleanup: () => {
386 validatorInstance.clearAbortController(abortController)
387 },
388 }
389}
390β
391/**
392 * Runs one validator immediately or through its instance-owned debouncer.
393 *
394 * Abort and thrown-error sentinels keep stale or exceptional executions out of
395 * normal result processing. Every settlement releases its abort resources.
396 */
397export function runMaybeDebouncedValidator<TResult extends ValidateResult>({
398 validatorInstance,
399 context,
400 onExecute,
401}: RunMaybeDebouncedValidatorArgs<TResult>): Promise<
402 ValidatorExecutionResult<TResult> | AbortedCall | ThrownError
403> {
404 const validator = validatorInstance.definition
405 const debounceMs = getValidatorDebounceMs(validator, context)
406β
407 const { signal, cleanup } = createValidatorAbortContext(validatorInstance)
408β
409 const validationContext: ValidateContext = {
410 ...context,
411 signal,
412 }
413β
414 return new Promise<
415 ValidatorExecutionResult<TResult> | AbortedCall | ThrownError
416 >((resolve) => {
417 let settled = false
418β
419 const settle = (
420 value: ValidatorExecutionResult<TResult> | AbortedCall | ThrownError,
421 ) => {
422 if (settled) return
423β
424 settled = true
425 cleanupAbortListener()
426 cleanup()
427 resolve(value)
428 }
429β
430 const fail = (error: unknown) => {
431 if (settled) return
432β
433 console.error('Validator threw an error:', error)
434 settle({ [THROWN_ERROR]: true, error })
435 }
436β
437 const onAbort = () => {
438 validatorInstance.debouncer?.cancel()
439 settle(ABORTED_CALL)
440 }
441β
442 const cleanupAbortListener = () => {
443 signal.removeEventListener('abort', onAbort)
444 }
445β
446 signal.addEventListener('abort', onAbort, { once: true })
447β
448 const run = (ctx: ValidateContext) => {
449 executeWithAbort(ctx, onExecute).then(settle, fail)
450 }
451β
452 if (debounceMs <= 0) {
453 validatorInstance.debouncer?.cancel()
454 run(validationContext)
455 return
456 }
457β
458 const debouncer = validatorInstance.getOrCreateDebouncer((call) => {
459 executeWithAbort(call.context, onExecute).then(call.resolve, (error) => {
460 console.error('Validator threw an error:', error)
461 const thrownError: ThrownError = { [THROWN_ERROR]: true, error }
462 call.resolve(thrownError)
463 })
464 }, debounceMs)
465β
466 if (!debouncer) {
467 settle(ABORTED_CALL)
468 return
469 }
470β
471 debouncer.maybeExecute({
472 context: validationContext,
473 resolve: settle,
474 // This should not be called anymore since we handle errors in the
475 // debouncer callback.
476 reject: () => {},
477 })
478 })
479}