Open History to see the last commit
1import { LiteDebouncer } from '@tanstack/pacer-lite'
2import { InternalValidationSourceInstance } from './ValidationSourceInstance.lib'
3import type { StandardSchemaV1 } from './standardSchema.public'
4import type {
5 BaseValidator,
6 ValidatorFn,
7 ValidatorScope,
8} from './validation.public'
9β
10export type InternalValidatorDefinition = BaseValidator<
11 StandardSchemaV1 | ValidatorFn<any, any>
12>
13β
14export type ValidatorInstanceDebouncedFn = (...args: Array<any>) => any
15β
16export type AnyInternalValidatorInstance<
17 TDebouncedFn extends ValidatorInstanceDebouncedFn =
18 ValidatorInstanceDebouncedFn,
19> = InternalValidatorInstance<any, any, any, any, any, TDebouncedFn>
20β
21export interface InternalValidatorInstanceOptions<
22 out TDefinition extends InternalValidatorDefinition,
23 out TOwner,
24> {
25 definition: TDefinition
26 owner: TOwner
27 scope: ValidatorScope
28 index?: number
29}
30β
31/** Stable runtime instances correlated with validator definitions by slot. */
32export type InternalValidatorInstances<
33 TDefinition extends InternalValidatorDefinition,
34 TOwner,
35 TErrorTarget = unknown,
36 TWatchedField = unknown,
37 TOutput = unknown,
38> = Array<
39 InternalValidatorInstance<
40 TDefinition,
41 TOwner,
42 TErrorTarget,
43 TWatchedField,
44 TOutput
45 >
46> | null
47β
48export interface ReconcileValidatorInstancesOptions<
49 TDefinition extends InternalValidatorDefinition,
50 TOwner,
51 TErrorTarget = unknown,
52 TWatchedField = unknown,
53 TOutput = unknown,
54> {
55 /** The latest validator definitions installed on the owner. */
56 definitions: ReadonlyArray<TDefinition> | null | undefined
57 /**
58 * The definitions installed before an update.
59 *
60 * Omit during initialization. Pass `null` when updating an owner that
61 * previously had no validators.
62 */
63 previousDefinitions?: ReadonlyArray<TDefinition> | null
64 /** The owner's currently installed instances, if it has any. */
65 instances: InternalValidatorInstances<
66 TDefinition,
67 TOwner,
68 TErrorTarget,
69 TWatchedField,
70 TOutput
71 >
72 /** The validation boundary that owns every reconciled instance. */
73 owner: TOwner
74 /** The form, group, or field scope shared by the reconciled instances. */
75 scope: ValidatorScope
76 /** Cleans owner-specific state before an instance is permanently disposed. */
77 onBeforeDispose?: (
78 instance: InternalValidatorInstance<
79 TDefinition,
80 TOwner,
81 TErrorTarget,
82 TWatchedField,
83 TOutput
84 >,
85 ) => void
86}
87β
88/**
89 * Runtime state owned by one installed validator occurrence.
90 */
91export class InternalValidatorInstance<
92 TDefinition extends InternalValidatorDefinition,
93 TOwner,
94 TErrorTarget = unknown,
95 TWatchedField = unknown,
96 TOutput = unknown,
97 TDebouncedFn extends ValidatorInstanceDebouncedFn =
98 ValidatorInstanceDebouncedFn,
99> extends InternalValidationSourceInstance<TOwner, TErrorTarget> {
100 /** The current validator definition associated with this stable instance. */
101 definition: TDefinition
102 /** The controller for the active execution, or `null` when none is active. */
103 abortController: AbortController | null = null
104 /** The lazily created debouncer for this validator's pending execution. */
105 debouncer: LiteDebouncer<TDebouncedFn> | null = null
106 /**
107 * The schema output or branded payload assigned by the latest form or group submit.
108 *
109 * Submit pipelines cancel prior executions and clear this before evaluating
110 * their validators. Field and non-submit pipelines do not assign it. Consult
111 * `hasOutput` because `undefined` can itself be a stored output.
112 */
113 output: TOutput | undefined
114 /** Whether the current submit pipeline assigned `output`. */
115 hasOutput = false
116 /**
117 * Resolved fields referenced by this validator's `watchFields` definition.
118 *
119 * The map is allocated on first use and returns to `null` when empty.
120 */
121 resolvedWatchFields: Map<string, TWatchedField> | null = null
122 /** Whether this occurrence has already run its mount validation. */
123 didRunOnMount = false
124 /**
125 * Number of definition updates applied while preserving this instance.
126 *
127 * Assigning the same definition again still advances the revision.
128 */
129 revision = 0
130 /** Creates the runtime state for one installed validator occurrence. */
131 constructor({
132 definition,
133 owner,
134 scope,
135 index,
136 }: InternalValidatorInstanceOptions<TDefinition, TOwner>) {
137 super({ owner, scope, index })
138 this.definition = definition
139 }
140β
141 /**
142 * Replaces the definition while preserving this instance and its runtime state.
143 *
144 * Every update advances `revision`, including assignment of the same object.
145 * The operation is ignored after disposal.
146 */
147 updateDefinition(definition: TDefinition): void {
148 if (this.disposed) return
149β
150 this.definition = definition
151 this.revision++
152 }
153β
154 /**
155 * Installs the controller for the next active execution.
156 *
157 * A different previously installed controller is aborted before replacement.
158 * Reinstalling the same controller or calling this after disposal has no effect.
159 */
160 setAbortController(abortController: AbortController): void {
161 if (this.disposed) return
162 if (this.abortController === abortController) return
163β
164 this.abortController?.abort()
165 this.abortController = abortController
166 }
167β
168 /**
169 * Clears an active controller only if it is still the installed controller.
170 *
171 * The identity check prevents completion of an older execution from clearing
172 * the controller of a newer one. This method does not abort the controller.
173 */
174 clearAbortController(abortController: AbortController): void {
175 if (this.disposed) return
176 if (this.abortController !== abortController) return
177β
178 this.abortController = null
179 }
180β
181 /**
182 * Returns this validator's debouncer, creating it on first use.
183 *
184 * An existing debouncer is reused with its callback and wait duration updated.
185 * Returns `null` after disposal.
186 */
187 getOrCreateDebouncer(
188 fn: TDebouncedFn,
189 wait: number,
190 ): LiteDebouncer<TDebouncedFn> | null {
191 if (this.disposed) return null
192β
193 let debouncer = this.debouncer
194 if (!debouncer) {
195 debouncer = new LiteDebouncer(fn, { wait })
196 this.debouncer = debouncer
197 } else {
198 debouncer.fn = fn
199 debouncer.options.wait = wait
200 }
201β
202 return debouncer
203 }
204β
205 /**
206 * Stores a submit pipeline's schema output or branded payload when present.
207 *
208 * A result without an output leaves the current state unchanged. An
209 * explicit `undefined` is still considered a stored output. The operation is
210 * ignored after disposal.
211 *
212 * @param result - The accepted result produced by the validator pipeline.
213 */
214 setOutput(result: { output: TOutput | null; hasOutput: boolean }): void {
215 if (this.disposed || !result.hasOutput) return
216β
217 this.output = result.output as TOutput
218 this.hasOutput = true
219 }
220β
221 /** Clears the stored output and its presence marker. */
222 clearOutput(): void {
223 if (this.disposed) return
224β
225 this._clearOutput()
226 }
227β
228 /**
229 * Associates a configured watched-field name with its resolved field.
230 *
231 * The backing map is allocated lazily, and an existing entry for `name` is
232 * replaced. The operation is ignored after disposal.
233 */
234 setResolvedWatchField(name: string, field: TWatchedField): void {
235 if (this.disposed) return
236β
237 if (!this.resolvedWatchFields) {
238 this.resolvedWatchFields = new Map()
239 }
240 this.resolvedWatchFields.set(name, field)
241 }
242β
243 /**
244 * Removes a resolved watched field.
245 */
246 deleteResolvedWatchField(name: string): void {
247 if (this.disposed) return
248β
249 this.resolvedWatchFields?.delete(name)
250 if (this.resolvedWatchFields?.size === 0) {
251 this.resolvedWatchFields = null
252 }
253 }
254β
255 /** Marks mount validation as completed for this occurrence. */
256 markMountValidationRan(): void {
257 if (this.disposed) return
258β
259 this.didRunOnMount = true
260 }
261β
262 /** Allows a lifecycle owner to run mount validation again after remounting. */
263 resetMountValidation(): void {
264 if (this.disposed) return
265β
266 this.didRunOnMount = false
267 }
268β
269 /**
270 * Aborts the active execution and cancels any pending debounced execution.
271 *
272 * Both execution resources are released. The operation is ignored after
273 * disposal.
274 */
275 cancelExecution(): void {
276 if (this.disposed) return
277β
278 this._cancelExecution()
279 }
280β
281 /**
282 * Clears transient execution, schema-output, and error-target state.
283 *
284 * The definition, owner, scope, watched fields, mount marker, and revision are
285 * preserved. The operation is ignored after disposal.
286 */
287 resetRuntime(): void {
288 super.resetRuntime()
289 }
290β
291 /** Releases validator-specific runtime state during reset or disposal. */
292 protected override _resetRuntime(): void {
293 this._cancelExecution()
294 this._clearOutput()
295 }
296β
297 /** Releases validator-only collections and mount state during disposal. */
298 protected override _disposeRuntime(): void {
299 this._resetRuntime()
300 this.resolvedWatchFields = null
301 this.didRunOnMount = false
302 }
303β
304 /** Cancels and releases execution resources without checking disposal state. */
305 private _cancelExecution(): void {
306 this.abortController?.abort()
307 this.abortController = null
308 this.debouncer?.cancel()
309 this.debouncer = null
310 }
311β
312 /** Clears the schema-output value and presence marker as one operation. */
313 private _clearOutput(): void {
314 this.output = undefined
315 this.hasOutput = false
316 }
317}
318β
319/**
320 * Correlates validator definitions with their stable runtime instances by slot.
321 *
322 * Retained slots preserve their instance and receive the latest definition.
323 * Added slots create instances, while removed slots are permanently disposed.
324 * Missing and empty definition collections are normalized to `null`.
325 * Updates with a different definition count emit the shared invariant warning.
326 */
327export function reconcileValidatorInstances<
328 TDefinition extends InternalValidatorDefinition,
329 TOwner,
330 TErrorTarget = unknown,
331 TWatchedField = unknown,
332 TOutput = unknown,
333>({
334 definitions,
335 previousDefinitions,
336 instances,
337 owner,
338 scope,
339 onBeforeDispose,
340}: ReconcileValidatorInstancesOptions<
341 TDefinition,
342 TOwner,
343 TErrorTarget,
344 TWatchedField,
345 TOutput
346>): InternalValidatorInstances<
347 TDefinition,
348 TOwner,
349 TErrorTarget,
350 TWatchedField,
351 TOutput
352> {
353 if (
354 previousDefinitions !== undefined &&
355 (previousDefinitions?.length ?? 0) !== (definitions?.length ?? 0)
356 ) {
357 console.warn(
358 'TanStack Form: The length of the validator array should not change after initialization',
359 )
360 }
361β
362 if (!definitions || definitions.length === 0) {
363 instances?.forEach((instance) => {
364 instance.dispose(onBeforeDispose)
365 })
366 return null
367 }
368β
369 const nextInstances = instances ?? []
370β
371 definitions.forEach((definition, index) => {
372 const instance = nextInstances[index]
373β
374 if (instance) {
375 instance.updateDefinition(definition)
376 } else {
377 nextInstances[index] = new InternalValidatorInstance<
378 TDefinition,
379 TOwner,
380 TErrorTarget,
381 TWatchedField,
382 TOutput
383 >({ definition, owner, scope, index })
384 }
385 })
386β
387 for (let index = definitions.length; index < nextInstances.length; index++) {
388 const instance = nextInstances[index]
389 if (!instance) continue
390β
391 instance.dispose(onBeforeDispose)
392 }
393 nextInstances.length = definitions.length
394β
395 return nextInstances
396}