{"version":3,"file":"_validation_errors-chunk.mjs","sources":["../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/resolution.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/util.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/util/type_guards.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/schema/logic.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/schema/logic_node.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/schema/path_node.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/schema/schema.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/api/rules/metadata.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/validation.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/debounce.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/context.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/metadata.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/proxy.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/util/deep_signal.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/structure.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/submit.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/node.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/state.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/field_adapter.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/field/manager.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/util/normalize_form_args.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/api/structure.ts","../../../../../darwin_arm64-fastbuild-ST-fdfa778d11ba/bin/packages/forms/signals/src/compat/validation_errors.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nlet boundPathDepth = 0;\n\n/**\n * The depth of the current path when evaluating a logic function.\n * Do not set this directly, it is a context variable managed by `setBoundPathDepthForResolution`.\n */\nexport function getBoundPathDepth() {\n  return boundPathDepth;\n}\n\n/**\n * Sets the bound path depth for the duration of the given logic function.\n * This is used to ensure that the field resolution algorithm walks far enough up the field tree to\n * reach the point where the root of the path we're bound to is applied. This normally isn't a big\n * concern, but matters when we're dealing with recursive structures.\n *\n * Consider this example:\n *\n * ```ts\n * const s = schema(p => {\n *   disabled(p.next, ({valueOf}) => valueOf(p.data));\n *   apply(p.next, s);\n * });\n * ```\n *\n * Here we need to know that the `disabled` logic was bound to a path of depth 1. Otherwise we'd\n * attempt to resolve `p.data` in the context of the field corresponding to `p.next`.\n * The resolution algorithm would start with the field for `p.next` and see that it *does* contain\n * the logic for `s` (due to the fact that its recursively applied.) It would then decide not to\n * walk up the field tree at all, and to immediately start walking down the keys for the target path\n * `p.data`, leading it to grab the field corresponding to `p.next.data`.\n *\n * We avoid the problem described above by keeping track of the depth (relative to Schema root) of\n * the path we were bound to. We then require the resolution algorithm to walk at least that far up\n * the tree before finding a node that contains the logic for `s`.\n *\n * @param fn A logic function that is bound to a particular path\n * @param depth The depth in the field tree of the field the logic is bound to\n * @returns A version of the logic function that is aware of its depth.\n */\nexport function setBoundPathDepthForResolution<A extends any[], R>(\n  fn: (...args: A) => R,\n  depth: number,\n): (...args: A) => R {\n  return (...args: A) => {\n    try {\n      boundPathDepth = depth;\n      return fn(...args);\n    } finally {\n      boundPathDepth = 0;\n    }\n  };\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type {FieldNodeOptions} from './structure';\n\n/** A shortCircuit function for reduceChildren that short-circuits if the value is false. */\nexport function shortCircuitFalse(value: boolean): boolean {\n  return !value;\n}\n\n/** A shortCircuit function for reduceChildren that short-circuits if the value is true. */\nexport function shortCircuitTrue(value: boolean): boolean {\n  return value;\n}\n\n/** Recasts the given value as a new type. */\nexport function cast<T>(value: unknown): asserts value is T {}\n\n/**\n * A helper method allowing to get injector regardless of the options type.\n * @param options\n */\nexport function getInjectorFromOptions(options: FieldNodeOptions) {\n  if (options.kind === 'root') {\n    return options.fieldManager.injector;\n  }\n\n  return options.parent.structure.root.structure.injector;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\n/**\n * A version of `Array.isArray` that handles narrowing of readonly arrays properly.\n */\nexport function isArray(value: unknown): value is any[] | readonly any[] {\n  return Array.isArray(value);\n}\n\n/**\n * Checks if a value is an object.\n */\nexport function isObject(value: unknown): value is Record<PropertyKey, unknown> {\n  return (typeof value === 'object' || typeof value === 'function') && value != null;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {untracked} from '@angular/core';\nimport type {MetadataKey} from '../api/rules/metadata';\nimport type {ValidationError} from '../api/rules/validation/validation_errors';\nimport {DisabledReason, type FieldContext, type LogicFn, type SchemaPath} from '../api/types';\nimport type {FieldNode} from '../field/node';\nimport {cast} from '../field/util';\nimport {isArray} from '../util/type_guards';\n\n/**\n * Special key which is used to represent a dynamic logic property in a `FieldPathNode` path.\n * This property is used to represent logic that applies to every element of some dynamic form data\n * (i.e. an array).\n *\n * For example, a rule like `applyEach(p.myArray, () => { ... })` will add logic to the `DYNAMIC`\n * property of `p.myArray`.\n */\nexport const DYNAMIC: unique symbol = Symbol();\n\n/** Represents a result that should be ignored because its predicate indicates it is not active. */\nconst IGNORED = Symbol();\n\n/**\n * A predicate that indicates whether an `AbstractLogic` instance is currently active, or should be\n * ignored.\n */\nexport interface Predicate {\n  /** A boolean logic function that returns true if the logic is considered active. */\n  readonly fn: LogicFn<any, boolean>;\n  /**\n   * The path which this predicate was created for. This is used to determine the correct\n   * `FieldContext` to pass to the predicate function.\n   */\n  readonly path: SchemaPath<any>;\n}\n\n/**\n * Represents a predicate that is bound to a particular depth in the field tree. This is needed for\n * recursively applied logic to ensure that the predicate is evaluated against the correct\n * application of that logic.\n *\n * Consider the following example:\n *\n * ```ts\n * const s = schema(p => {\n *   disabled(p.data);\n *   applyWhen(p.next, ({valueOf}) => valueOf(p.data) === 1, s);\n * });\n *\n * const f = form(signal({data: 0, next: {data: 1, next: {data: 2, next: undefined}}}), s);\n *\n * const isDisabled = f.next.next.data().disabled();\n * ```\n *\n * In order to determine `isDisabled` we need to evaluate the predicate from `applyWhen` *twice*.\n * Once to see if the schema should be applied to `f.next` and again to see if it should be applied\n * to `f.next.next`. The `depth` tells us which field we should be evaluating against each time.\n */\nexport interface BoundPredicate extends Predicate {\n  /** The depth in the field tree at which this predicate is bound. */\n  readonly depth: number;\n}\n\n/**\n * Base class for all logic. It is responsible for combining the results from multiple individual\n * logic functions registered in the schema, and using them to derive the value for some associated\n * piece of field state.\n */\nexport abstract class AbstractLogic<TReturn, TValue = TReturn> {\n  /** The set of logic functions that contribute to the value of the associated state. */\n  protected readonly fns: Array<LogicFn<any, TValue | typeof IGNORED>> = [];\n\n  constructor(\n    /**\n     * A list of predicates that conditionally enable all logic in this logic instance.\n     * The logic is only enabled when *all* of the predicates evaluate to true.\n     */\n    private predicates: ReadonlyArray<BoundPredicate>,\n  ) {}\n\n  /**\n   * Computes the value of the associated field state based on the logic functions and predicates\n   * registered with this logic instance.\n   */\n  abstract compute(arg: FieldContext<any>): TReturn;\n\n  /**\n   * The default value that the associated field state should assume if there are no logic functions\n   * registered by the schema (or if the logic is disabled by a predicate).\n   */\n  abstract get defaultValue(): TReturn;\n\n  /** Registers a logic function with this logic instance. */\n  push(logicFn: LogicFn<any, TValue>) {\n    this.fns.push(wrapWithPredicates(this.predicates, logicFn));\n  }\n\n  /**\n   * Merges in the logic from another logic instance, subject to the predicates of both the other\n   * instance and this instance.\n   */\n  mergeIn(other: AbstractLogic<TReturn, TValue>) {\n    const fns = this.predicates\n      ? other.fns.map((fn) => wrapWithPredicates(this.predicates, fn))\n      : other.fns;\n    this.fns.push(...fns);\n  }\n}\n\n/** Logic that combines its individual logic function results with logical OR. */\nexport class BooleanOrLogic extends AbstractLogic<boolean> {\n  override get defaultValue() {\n    return false;\n  }\n\n  override compute(arg: FieldContext<any>): boolean {\n    return this.fns.some((f) => {\n      const result = f(arg);\n      return result && result !== IGNORED;\n    });\n  }\n}\n\n/**\n * Logic that combines its individual logic function results by aggregating them in an array.\n * Depending on its `ignore` function it may ignore certain values, omitting them from the array.\n */\nexport class ArrayMergeIgnoreLogic<TElement, TIgnore = never> extends AbstractLogic<\n  readonly TElement[],\n  TElement | readonly (TElement | TIgnore)[] | TIgnore | undefined | void\n> {\n  /** Creates an instance of this class that ignores `null` values. */\n  static ignoreNull<TElement>(predicates: ReadonlyArray<BoundPredicate>) {\n    return new ArrayMergeIgnoreLogic<TElement, null>(predicates, (e: unknown) => e === null);\n  }\n\n  constructor(\n    predicates: ReadonlyArray<BoundPredicate>,\n    private ignore: undefined | ((e: TElement | undefined | TIgnore) => e is TIgnore),\n  ) {\n    super(predicates);\n  }\n\n  override get defaultValue() {\n    return [];\n  }\n\n  override compute(arg: FieldContext<any>): readonly TElement[] {\n    return this.fns.reduce((prev, f) => {\n      const value = f(arg);\n\n      if (value === undefined || value === IGNORED) {\n        return prev;\n      } else if (isArray(value)) {\n        return [...prev, ...(this.ignore ? value.filter((e) => !this.ignore!(e)) : value)];\n      } else {\n        if (this.ignore && this.ignore(value as TElement | TIgnore | undefined)) {\n          return prev;\n        }\n        return [...prev, value];\n      }\n    }, [] as TElement[]);\n  }\n}\n\n/** Logic that combines its individual logic function results by aggregating them in an array. */\nexport class ArrayMergeLogic<TElement> extends ArrayMergeIgnoreLogic<TElement, never> {\n  constructor(predicates: ReadonlyArray<BoundPredicate>) {\n    super(predicates, undefined);\n  }\n}\n\n/** Logic that combines metadata according to the keys's reduce function. */\nexport class MetadataMergeLogic<TAcc, TItem> extends AbstractLogic<TAcc, TItem> {\n  override get defaultValue() {\n    return this.key.reducer.getInitial();\n  }\n\n  constructor(\n    predicates: ReadonlyArray<BoundPredicate>,\n    private key: MetadataKey<any, TItem, TAcc>,\n  ) {\n    super(predicates);\n  }\n\n  override compute(ctx: FieldContext<any>): TAcc {\n    if (this.fns.length === 0) {\n      return this.key.reducer.getInitial();\n    }\n    let acc: TAcc = this.key.reducer.getInitial();\n    for (let i = 0; i < this.fns.length; i++) {\n      const item = this.fns[i](ctx);\n      if (item !== IGNORED) {\n        acc = this.key.reducer.reduce(acc, item);\n      }\n    }\n    return acc;\n  }\n}\n\n/**\n * Wraps a logic function such that it returns the special `IGNORED` sentinel value if any of the\n * given predicates evaluates to false.\n *\n * @param predicates A list of bound predicates to apply to the logic function\n * @param logicFn The logic function to wrap\n * @returns A wrapped version of the logic function that may return `IGNORED`.\n */\nfunction wrapWithPredicates<TValue, TReturn>(\n  predicates: ReadonlyArray<BoundPredicate>,\n  logicFn: LogicFn<TValue, TReturn>,\n): LogicFn<TValue, TReturn | typeof IGNORED> {\n  if (predicates.length === 0) {\n    return logicFn;\n  }\n  return (arg: FieldContext<any>): TReturn | typeof IGNORED => {\n    for (const predicate of predicates) {\n      let predicateField = arg.stateOf(predicate.path) as FieldNode;\n      // Check the depth of the current field vs the depth this predicate is supposed to be\n      // evaluated at. If necessary, walk up the field tree to grab the correct context field.\n      // We can check the pathKeys as an untracked read since we know the structure of our fields\n      // doesn't change.\n      const depthDiff = untracked(predicateField.structure.pathKeys).length - predicate.depth;\n      for (let i = 0; i < depthDiff; i++) {\n        predicateField = predicateField.structure.parent!;\n      }\n      // If any of the predicates don't match, don't actually run the logic function, just return\n      // the default value.\n      if (!predicate.fn(predicateField.context)) {\n        return IGNORED;\n      }\n    }\n    return logicFn(arg);\n  };\n}\n\n/**\n * Container for all the different types of logic that can be applied to a field\n * (disabled, hidden, errors, etc.)\n */\n\nexport class LogicContainer {\n  /** Logic that determines if the field is hidden. */\n  readonly hidden: BooleanOrLogic;\n  /** Logic that determines reasons for the field being disabled. */\n  readonly disabledReasons: ArrayMergeLogic<DisabledReason>;\n  /** Logic that determines if the field is read-only. */\n  readonly readonly: BooleanOrLogic;\n  /** Logic that produces synchronous validation errors for the field. */\n  readonly syncErrors: ArrayMergeIgnoreLogic<ValidationError.WithFieldTree, null>;\n  /** Logic that produces synchronous validation errors for the field's subtree. */\n  readonly syncTreeErrors: ArrayMergeIgnoreLogic<ValidationError.WithFieldTree, null>;\n  /** Logic that produces asynchronous validation results (errors or 'pending'). */\n  readonly asyncErrors: ArrayMergeIgnoreLogic<ValidationError.WithFieldTree | 'pending', null>;\n  /** A map of metadata keys to the `AbstractLogic` instances that compute their values. */\n  private readonly metadata = new Map<\n    MetadataKey<unknown, unknown, unknown>,\n    AbstractLogic<unknown>\n  >();\n\n  /**\n   * Constructs a new `Logic` container.\n   * @param predicates An array of predicates that must all be true for the logic\n   *   functions within this container to be active.\n   */\n  constructor(private predicates: ReadonlyArray<BoundPredicate>) {\n    this.hidden = new BooleanOrLogic(predicates);\n    this.disabledReasons = new ArrayMergeLogic(predicates);\n    this.readonly = new BooleanOrLogic(predicates);\n    this.syncErrors = ArrayMergeIgnoreLogic.ignoreNull<ValidationError.WithFieldTree>(predicates);\n    this.syncTreeErrors =\n      ArrayMergeIgnoreLogic.ignoreNull<ValidationError.WithFieldTree>(predicates);\n    this.asyncErrors = ArrayMergeIgnoreLogic.ignoreNull<ValidationError.WithFieldTree | 'pending'>(\n      predicates,\n    );\n  }\n\n  /** Checks whether there is logic for the given metadata key. */\n  hasMetadata(key: MetadataKey<any, any, any>) {\n    return this.metadata.has(key);\n  }\n\n  /**\n   * Gets an iterable of [metadata key, logic function] pairs.\n   * @returns An iterable of metadata keys.\n   */\n  getMetadataKeys() {\n    return this.metadata.keys();\n  }\n\n  /**\n   * Retrieves or creates the `AbstractLogic` for a given metadata key.\n   * @param key The `MetadataKey` for which to get the logic.\n   * @returns The `AbstractLogic` associated with the key.\n   */\n  getMetadata<T>(key: MetadataKey<any, T, any>): AbstractLogic<T> {\n    cast<MetadataKey<unknown, unknown, unknown>>(key);\n    if (!this.metadata.has(key)) {\n      this.metadata.set(key, new MetadataMergeLogic(this.predicates, key));\n    }\n    return this.metadata.get(key)! as AbstractLogic<T>;\n  }\n\n  /**\n   * Merges logic from another `Logic` instance into this one.\n   * @param other The `Logic` instance to merge from.\n   */\n  mergeIn(other: LogicContainer) {\n    this.hidden.mergeIn(other.hidden);\n    this.disabledReasons.mergeIn(other.disabledReasons);\n    this.readonly.mergeIn(other.readonly);\n    this.syncErrors.mergeIn(other.syncErrors);\n    this.syncTreeErrors.mergeIn(other.syncTreeErrors);\n    this.asyncErrors.mergeIn(other.asyncErrors);\n    for (const key of other.getMetadataKeys()) {\n      const metadataLogic = other.metadata.get(key)!;\n      this.getMetadata(key).mergeIn(metadataLogic);\n    }\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {ɵRuntimeError as RuntimeError} from '@angular/core';\nimport {RuntimeErrorCode} from '../errors';\n\nimport type {MetadataKey, ValidationError} from '../api/rules';\nimport type {AsyncValidationResult, DisabledReason, LogicFn, ValidationResult} from '../api/types';\nimport {setBoundPathDepthForResolution} from '../field/resolution';\nimport {type BoundPredicate, DYNAMIC, LogicContainer, type Predicate} from './logic';\n\n/**\n * Abstract base class for building a `LogicNode`.\n * This class defines the interface for adding various logic rules (e.g., hidden, disabled)\n * and data factories to a node in the logic tree.\n * LogicNodeBuilders are 1:1 with nodes in the Schema tree.\n */\nexport abstract class AbstractLogicNodeBuilder {\n  constructor(\n    /** The depth of this node in the schema tree. */\n    protected readonly depth: number,\n  ) {}\n\n  /** Adds a rule to determine if a field should be hidden. */\n  abstract addHiddenRule(logic: LogicFn<any, boolean>): void;\n\n  /** Adds a rule to determine if a field should be disabled, and for what reason. */\n  abstract addDisabledReasonRule(logic: LogicFn<any, DisabledReason | undefined>): void;\n\n  /** Adds a rule to determine if a field should be read-only. */\n  abstract addReadonlyRule(logic: LogicFn<any, boolean>): void;\n\n  /** Adds a rule for synchronous validation errors for a field. */\n  abstract addSyncErrorRule(logic: LogicFn<any, ValidationResult>): void;\n\n  /** Adds a rule for synchronous validation errors that apply to a subtree. */\n  abstract addSyncTreeErrorRule(logic: LogicFn<any, ValidationResult>): void;\n\n  /** Adds a rule for asynchronous validation errors for a field. */\n  abstract addAsyncErrorRule(logic: LogicFn<any, AsyncValidationResult>): void;\n\n  /** Adds a rule to compute metadata for a field. */\n  abstract addMetadataRule<M>(key: MetadataKey<unknown, M, unknown>, logic: LogicFn<any, M>): void;\n\n  /**\n   * Gets a builder for a child node associated with the given property key.\n   * @param key The property key of the child.\n   * @returns A `LogicNodeBuilder` for the child.\n   */\n  abstract getChild(key: PropertyKey): LogicNodeBuilder;\n\n  /**\n   * Checks whether a particular `AbstractLogicNodeBuilder` has been merged into this one.\n   * @param builder The builder to check for.\n   * @returns True if the builder has been merged, false otherwise.\n   */\n  abstract hasLogic(builder: AbstractLogicNodeBuilder): boolean;\n\n  /**\n   * Builds the `LogicNode` from the accumulated rules and child builders.\n   * @returns The constructed `LogicNode`.\n   */\n  build(): LogicNode {\n    return new LeafLogicNode(this, [], 0);\n  }\n}\n\n/**\n * A builder for `LogicNode`. Used to add logic to the final `LogicNode` tree.\n * This builder supports merging multiple sources of logic, potentially with predicates,\n * preserving the order of rule application.\n */\nexport class LogicNodeBuilder extends AbstractLogicNodeBuilder {\n  constructor(depth: number) {\n    super(depth);\n  }\n\n  /**\n   * The current `NonMergeableLogicNodeBuilder` being used to add rules directly to this\n   * `LogicNodeBuilder`. Do not use this directly, call `getCurrent()` which will create a current\n   * builder if there is none.\n   */\n  private current: NonMergeableLogicNodeBuilder | undefined;\n  /**\n   * Stores all builders that contribute to this node, along with any predicates\n   * that gate their application.\n   */\n  readonly all: {builder: AbstractLogicNodeBuilder; predicate?: Predicate}[] = [];\n\n  override addHiddenRule(logic: LogicFn<any, boolean>): void {\n    this.getCurrent().addHiddenRule(logic);\n  }\n\n  override addDisabledReasonRule(logic: LogicFn<any, DisabledReason | undefined>): void {\n    this.getCurrent().addDisabledReasonRule(logic);\n  }\n\n  override addReadonlyRule(logic: LogicFn<any, boolean>): void {\n    this.getCurrent().addReadonlyRule(logic);\n  }\n\n  override addSyncErrorRule(\n    logic: LogicFn<any, ValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.getCurrent().addSyncErrorRule(logic);\n  }\n\n  override addSyncTreeErrorRule(\n    logic: LogicFn<any, ValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.getCurrent().addSyncTreeErrorRule(logic);\n  }\n\n  override addAsyncErrorRule(\n    logic: LogicFn<any, AsyncValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.getCurrent().addAsyncErrorRule(logic);\n  }\n\n  override addMetadataRule<T>(key: MetadataKey<unknown, T, any>, logic: LogicFn<any, T>): void {\n    this.getCurrent().addMetadataRule(key, logic);\n  }\n\n  override getChild(key: PropertyKey): LogicNodeBuilder {\n    // Close off the current builder if the key is DYNAMIC and the current builder already has logic\n    // for some non-DYNAMIC key. This guarantees that all of the DYNAMIC logic always comes before\n    // all of the specific-key logic for any given instance of `NonMergeableLogicNodeBuilder`.\n    // We rely on this fact in `getAllChildBuilder` to know that we can return the DYNAMIC logic,\n    // followed by the property-specific logic, in that order.\n    if (key === DYNAMIC) {\n      const children = this.getCurrent().children;\n      // Use the children size to determine if there is logic registered for a property other than\n      // the DYNAMIC property.\n      // - If the children map doesn't have DYNAMIC logic, but the size is still >0 then we know it\n      //   has logic for some other property.\n      // - If the children map does have DYNAMIC logic then its size is going to be at least 1,\n      //   because it has the DYNAMIC key. However if it is >1, then we again know it contains other\n      //   keys.\n      if (children.size > (children.has(DYNAMIC) ? 1 : 0)) {\n        this.current = undefined;\n      }\n    }\n    return this.getCurrent().getChild(key);\n  }\n\n  override hasLogic(builder: AbstractLogicNodeBuilder): boolean {\n    if (this === builder) {\n      return true;\n    }\n    return this.all.some(({builder: subBuilder}) => subBuilder.hasLogic(builder));\n  }\n\n  /**\n   * Merges logic from another `LogicNodeBuilder` into this one.\n   * If a `predicate` is provided, all logic from the `other` builder will only apply\n   * when the predicate evaluates to true.\n   * @param other The `LogicNodeBuilder` to merge in.\n   * @param predicate An optional predicate to gate the merged logic.\n   */\n  mergeIn(other: LogicNodeBuilder, predicate?: Predicate): void {\n    // Add the other builder to our collection, we'll defer the actual merging of the logic until\n    // the logic node is requested to be created. In order to preserve the original ordering of the\n    // rules, we close off the current builder to any further edits. If additional logic is added,\n    // a new current builder will be created to capture it.\n    if (predicate) {\n      this.all.push({\n        builder: other,\n        predicate: {\n          fn: setBoundPathDepthForResolution(predicate.fn, this.depth),\n          path: predicate.path,\n        },\n      });\n    } else {\n      this.all.push({builder: other});\n    }\n    this.current = undefined;\n  }\n\n  /**\n   * Gets the current `NonMergeableLogicNodeBuilder` for adding rules directly to this\n   * `LogicNodeBuilder`. If no current builder exists, a new one is created.\n   * The current builder is cleared whenever `mergeIn` is called to preserve the order\n   * of rules when merging separate builder trees.\n   * @returns The current `NonMergeableLogicNodeBuilder`.\n   */\n  private getCurrent(): NonMergeableLogicNodeBuilder {\n    if (this.current === undefined) {\n      this.current = new NonMergeableLogicNodeBuilder(this.depth);\n      this.all.push({builder: this.current});\n    }\n    return this.current;\n  }\n\n  /**\n   * Creates a new root `LogicNodeBuilder`.\n   * @returns A new instance of `LogicNodeBuilder`.\n   */\n  static newRoot(): LogicNodeBuilder {\n    return new LogicNodeBuilder(0);\n  }\n}\n\n/**\n * A type of `AbstractLogicNodeBuilder` used internally by the `LogicNodeBuilder` to record \"pure\"\n * chunks of logic that do not require merging in other builders.\n */\nclass NonMergeableLogicNodeBuilder extends AbstractLogicNodeBuilder {\n  /** The collection of logic rules directly added to this builder. */\n  readonly logic = new LogicContainer([]);\n  /**\n   * A map of child property keys to their corresponding `LogicNodeBuilder` instances.\n   * This allows for building a tree of logic.\n   */\n  readonly children = new Map<PropertyKey, LogicNodeBuilder>();\n\n  constructor(depth: number) {\n    super(depth);\n  }\n\n  override addHiddenRule(logic: LogicFn<any, boolean>): void {\n    this.logic.hidden.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addDisabledReasonRule(logic: LogicFn<any, DisabledReason | undefined>): void {\n    this.logic.disabledReasons.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addReadonlyRule(logic: LogicFn<any, boolean>): void {\n    this.logic.readonly.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addSyncErrorRule(\n    logic: LogicFn<any, ValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.logic.syncErrors.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addSyncTreeErrorRule(\n    logic: LogicFn<any, ValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.logic.syncTreeErrors.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addAsyncErrorRule(\n    logic: LogicFn<any, AsyncValidationResult<ValidationError.WithFieldTree>>,\n  ): void {\n    this.logic.asyncErrors.push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override addMetadataRule<T>(key: MetadataKey<unknown, T, unknown>, logic: LogicFn<any, T>): void {\n    this.logic.getMetadata(key).push(setBoundPathDepthForResolution(logic, this.depth));\n  }\n\n  override getChild(key: PropertyKey): LogicNodeBuilder {\n    if (!this.children.has(key)) {\n      this.children.set(key, new LogicNodeBuilder(this.depth + 1));\n    }\n    return this.children.get(key)!;\n  }\n\n  override hasLogic(builder: AbstractLogicNodeBuilder): boolean {\n    return this === builder;\n  }\n}\n\n/**\n * Represents a node in the logic tree, containing all logic applicable\n * to a specific field or path in the form structure.\n * LogicNodes are 1:1 with nodes in the Field tree.\n */\nexport interface LogicNode {\n  /** The collection of logic rules (hidden, disabled, errors, etc.) for this node. */\n  readonly logic: LogicContainer;\n\n  /**\n   * Retrieves the `LogicNode` for a child identified by the given property key.\n   * @param key The property key of the child.\n   * @returns The `LogicNode` for the specified child.\n   */\n  getChild(key: PropertyKey): LogicNode;\n\n  /**\n   * Checks whether the logic from a particular `AbstractLogicNodeBuilder` has been merged into this\n   * node.\n   * @param builder The builder to check for.\n   * @returns True if the builder has been merged, false otherwise.\n   */\n  hasLogic(builder: AbstractLogicNodeBuilder): boolean;\n}\n\n/**\n * A tree structure of `Logic` corresponding to a tree of fields.\n * This implementation represents a leaf in the sense that its logic is derived\n * from a single builder.\n */\nclass LeafLogicNode implements LogicNode {\n  /** The computed logic for this node. */\n  readonly logic: LogicContainer;\n\n  /**\n   * Constructs a `LeafLogicNode`.\n   * @param builder The `AbstractLogicNodeBuilder` from which to derive the logic.\n   *   If undefined, an empty `Logic` instance is created.\n   * @param predicates An array of predicates that gate the logic from the builder.\n   */\n  constructor(\n    private builder: AbstractLogicNodeBuilder | undefined,\n    private predicates: BoundPredicate[],\n    /** The depth of this node in the field tree. */\n    private depth: number,\n  ) {\n    this.logic = builder ? createLogic(builder, predicates, depth) : new LogicContainer([]);\n  }\n\n  // TODO: cache here, or just rely on the user of this API to do caching?\n  /**\n   * Retrieves the `LogicNode` for a child identified by the given property key.\n   * @param key The property key of the child.\n   * @returns The `LogicNode` for the specified child.\n   */\n  getChild(key: PropertyKey): LogicNode {\n    // The logic for a particular child may be spread across multiple builders. We lazily combine\n    // this logic at the time the child logic node is requested to be created.\n    const childBuilders = this.builder ? getAllChildBuilders(this.builder, key) : [];\n    if (childBuilders.length === 0) {\n      return new LeafLogicNode(undefined, [], this.depth + 1);\n    } else if (childBuilders.length === 1) {\n      const {builder, predicates} = childBuilders[0];\n      return new LeafLogicNode(\n        builder,\n        [...this.predicates, ...predicates.map((p) => bindLevel(p, this.depth))],\n        this.depth + 1,\n      );\n    } else {\n      const builtNodes = childBuilders.map(\n        ({builder, predicates}) =>\n          new LeafLogicNode(\n            builder,\n            [...this.predicates, ...predicates.map((p) => bindLevel(p, this.depth))],\n            this.depth + 1,\n          ),\n      );\n      return new CompositeLogicNode(builtNodes);\n    }\n  }\n\n  /**\n   * Checks whether the logic from a particular `AbstractLogicNodeBuilder` has been merged into this\n   * node.\n   * @param builder The builder to check for.\n   * @returns True if the builder has been merged, false otherwise.\n   */\n  hasLogic(builder: AbstractLogicNodeBuilder): boolean {\n    return this.builder?.hasLogic(builder) ?? false;\n  }\n}\n\n/**\n * A `LogicNode` that represents the composition of multiple `LogicNode` instances.\n * This is used when logic for a particular path is contributed by several distinct\n * builder branches that need to be merged.\n */\nclass CompositeLogicNode implements LogicNode {\n  /** The merged logic from all composed nodes. */\n  readonly logic: LogicContainer;\n\n  /**\n   * Constructs a `CompositeLogicNode`.\n   * @param all An array of `LogicNode` instances to compose.\n   */\n  constructor(private all: LogicNode[]) {\n    this.logic = new LogicContainer([]);\n    for (const node of all) {\n      this.logic.mergeIn(node.logic);\n    }\n  }\n\n  /**\n   * Retrieves the child `LogicNode` by composing the results of `getChild` from all\n   * underlying `LogicNode` instances.\n   * @param key The property key of the child.\n   * @returns A `CompositeLogicNode` representing the composed child.\n   */\n  getChild(key: PropertyKey): LogicNode {\n    return new CompositeLogicNode(this.all.flatMap((child) => child.getChild(key)));\n  }\n\n  /**\n   * Checks whether the logic from a particular `AbstractLogicNodeBuilder` has been merged into this\n   * node.\n   * @param builder The builder to check for.\n   * @returns True if the builder has been merged, false otherwise.\n   */\n  hasLogic(builder: AbstractLogicNodeBuilder): boolean {\n    return this.all.some((node) => node.hasLogic(builder));\n  }\n}\n\n/**\n * Gets all of the builders that contribute logic to the given child of the parent builder.\n * This function recursively traverses the builder hierarchy.\n * @param builder The parent `AbstractLogicNodeBuilder`.\n * @param key The property key of the child.\n * @returns An array of objects, each containing a `LogicNodeBuilder` for the child and any associated predicates.\n */\nfunction getAllChildBuilders(\n  builder: AbstractLogicNodeBuilder,\n  key: PropertyKey,\n): {builder: LogicNodeBuilder; predicates: Predicate[]}[] {\n  if (builder instanceof LogicNodeBuilder) {\n    return builder.all.flatMap(({builder, predicate}) => {\n      const children = getAllChildBuilders(builder, key);\n      if (predicate) {\n        return children.map(({builder, predicates}) => ({\n          builder,\n          predicates: [...predicates, predicate],\n        }));\n      }\n      return children;\n    });\n  } else if (builder instanceof NonMergeableLogicNodeBuilder) {\n    return [\n      // DYNAMIC logic always comes first for any individual `NonMergeableLogicNodeBuilder`.\n      // This assumption is guaranteed by the behavior of `LogicNodeBuilder.getChild`.\n      // Therefore we can return all of the DYNAMIC logic, followed by all of the property-specific\n      // logic.\n      ...(key !== DYNAMIC && builder.children.has(DYNAMIC)\n        ? [{builder: builder.getChild(DYNAMIC), predicates: []}]\n        : []),\n      ...(builder.children.has(key) ? [{builder: builder.getChild(key), predicates: []}] : []),\n    ];\n  } else {\n    throw new RuntimeError(\n      RuntimeErrorCode.UNKNOWN_BUILDER_TYPE,\n      ngDevMode && 'Unknown LogicNodeBuilder type',\n    );\n  }\n}\n\n/**\n * Creates the full `Logic` for a given builder.\n * This function handles different types of builders (`LogicNodeBuilder`, `NonMergeableLogicNodeBuilder`)\n * and applies the provided predicates.\n * @param builder The `AbstractLogicNodeBuilder` to process.\n * @param predicates Predicates to apply to the logic derived from the builder.\n * @param depth The depth in the field tree of the field which this logic applies to.\n * @returns The `Logic` instance.\n */\nfunction createLogic(\n  builder: AbstractLogicNodeBuilder,\n  predicates: BoundPredicate[],\n  depth: number,\n): LogicContainer {\n  const logic = new LogicContainer(predicates);\n  if (builder instanceof LogicNodeBuilder) {\n    const builtNodes = builder.all.map(\n      ({builder, predicate}) =>\n        new LeafLogicNode(\n          builder,\n          predicate ? [...predicates, bindLevel(predicate, depth)] : predicates,\n          depth,\n        ),\n    );\n    for (const node of builtNodes) {\n      logic.mergeIn(node.logic);\n    }\n  } else if (builder instanceof NonMergeableLogicNodeBuilder) {\n    logic.mergeIn(builder.logic);\n  } else {\n    throw new RuntimeError(\n      RuntimeErrorCode.UNKNOWN_BUILDER_TYPE,\n      ngDevMode && 'Unknown LogicNodeBuilder type',\n    );\n  }\n  return logic;\n}\n\n/**\n * Create a bound version of the given predicate to a specific depth in the field tree.\n * This allows us to unambiguously know which `FieldContext` the predicate function should receive.\n *\n * This is of particular concern when a schema is applied recursively to itself. Since the schema is\n * only compiled once, each nested application adds the same predicate instance. We differentiate\n * these by recording the depth of the field they're bound to.\n *\n * @param predicate The unbound predicate\n * @param depth The depth of the field the predicate is bound to\n * @returns A bound predicate\n */\nfunction bindLevel(predicate: Predicate, depth: number): BoundPredicate {\n  return {...predicate, depth: depth};\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\nimport type {SchemaPath, SchemaPathRules} from '../api/types';\nimport type {Predicate} from './logic';\nimport {LogicNodeBuilder} from './logic_node';\nimport type {SchemaImpl} from './schema';\n\n/**\n * Special key which is used to retrieve the `FieldPathNode` instance from its `FieldPath` proxy wrapper.\n */\nconst PATH = Symbol('PATH');\n\n/**\n * A path in the schema on which logic is stored so that it can be added to the corresponding field\n * when the field is created.\n */\nexport class FieldPathNode {\n  /** The root path node from which this path node is descended. */\n  readonly root: FieldPathNode;\n\n  /**\n   * A map containing all child path nodes that have been created on this path.\n   * Child path nodes are created automatically on first access if they do not exist already.\n   */\n  private readonly children = new Map<PropertyKey, FieldPathNode>();\n\n  /**\n   * A proxy that wraps the path node, allowing navigation to its child paths via property access.\n   */\n  readonly fieldPathProxy: SchemaPath<any> = new Proxy(\n    this,\n    FIELD_PATH_PROXY_HANDLER,\n  ) as unknown as SchemaPath<any>;\n\n  /**\n   * For a root path node this will contain the root logic builder. For non-root nodes,\n   * they determine their logic builder from their parent so this is undefined.\n   */\n  private readonly logicBuilder: LogicNodeBuilder | undefined;\n\n  protected constructor(\n    /** The property keys used to navigate from the root path to this path. */\n    readonly keys: PropertyKey[],\n    root: FieldPathNode | undefined,\n    /** The parent of this path node. */\n    private readonly parent: FieldPathNode | undefined,\n    /** The key of this node in its parent. */\n    private readonly keyInParent: PropertyKey | undefined,\n  ) {\n    this.root = root ?? this;\n    if (!parent) {\n      this.logicBuilder = LogicNodeBuilder.newRoot();\n    }\n  }\n\n  /** The logic builder used to accumulate logic on this path node. */\n  get builder(): LogicNodeBuilder {\n    if (this.logicBuilder) {\n      return this.logicBuilder;\n    }\n    return this.parent!.builder.getChild(this.keyInParent!);\n  }\n\n  /**\n   * Gets the path node for the given child property key.\n   * Child paths are created automatically on first access if they do not exist already.\n   */\n  getChild(key: PropertyKey): FieldPathNode {\n    if (!this.children.has(key)) {\n      this.children.set(key, new FieldPathNode([...this.keys, key], this.root, this, key));\n    }\n    return this.children.get(key)!;\n  }\n\n  /**\n   * Merges in logic from another schema to this one.\n   * @param other The other schema to merge in the logic from\n   * @param predicate A predicate indicating when the merged in logic should be active.\n   */\n  mergeIn(other: SchemaImpl, predicate?: Predicate) {\n    const path = other.compile();\n    this.builder.mergeIn(path.builder, predicate);\n  }\n\n  /** Extracts the underlying path node from the given path proxy. */\n  static unwrapFieldPath(formPath: SchemaPath<unknown, SchemaPathRules>): FieldPathNode {\n    return (formPath as any)[PATH] as FieldPathNode;\n  }\n\n  /** Creates a new root path node to be passed in to a schema function. */\n  static newRoot() {\n    return new FieldPathNode([], undefined, undefined, undefined);\n  }\n}\n\n/** Proxy handler which implements `FieldPath` on top of a `FieldPathNode`. */\nexport const FIELD_PATH_PROXY_HANDLER: ProxyHandler<FieldPathNode> = {\n  get(node: FieldPathNode, property: string | symbol) {\n    if (property === PATH) {\n      return node;\n    }\n\n    return node.getChild(property).fieldPathProxy;\n  },\n};\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {ɵRuntimeError as RuntimeError} from '@angular/core';\nimport {RuntimeErrorCode} from '../errors';\n\nimport {SchemaPath, SchemaFn, SchemaOrSchemaFn} from '../api/types';\nimport {FieldPathNode} from './path_node';\n\n/**\n * Keeps track of the path node for the schema function that is currently being compiled. This is\n * used to detect erroneous references to a path node outside of the context of its schema function.\n * Do not set this directly, it is a context variable managed by `SchemaImpl.compile`.\n */\nlet currentCompilingNode: FieldPathNode | undefined = undefined;\n\n/**\n * A cache of all schemas compiled under the current root compilation. This is used to avoid doing\n * extra work when compiling a schema that reuses references to the same sub-schema. For example:\n *\n * ```ts\n * const sub = schema(p => ...);\n * const s = schema(p => {\n *   apply(p.a, sub);\n *   apply(p.b, sub);\n * });\n * ```\n *\n * This also ensures that we don't go into an infinite loop when compiling a schema that references\n * itself.\n *\n * Do not directly add or remove entries from this map, it is a context variable managed by\n * `SchemaImpl.compile` and `SchemaImpl.rootCompile`.\n */\nconst compiledSchemas = new Map<SchemaImpl, FieldPathNode>();\n\n/**\n * Implements the `Schema` concept.\n */\nexport class SchemaImpl {\n  constructor(private schemaFn: SchemaFn<unknown>) {}\n\n  /**\n   * Compiles this schema within the current root compilation context. If the schema was previously\n   * compiled within this context, we reuse the cached FieldPathNode, otherwise we create a new one\n   * and cache it in the compilation context.\n   */\n  compile(): FieldPathNode {\n    if (compiledSchemas.has(this)) {\n      return compiledSchemas.get(this)!;\n    }\n    const path = FieldPathNode.newRoot();\n    compiledSchemas.set(this, path);\n    let prevCompilingNode = currentCompilingNode;\n    try {\n      currentCompilingNode = path;\n      this.schemaFn(path.fieldPathProxy);\n    } finally {\n      // Use a try/finally to ensure we restore the previous root upon completion,\n      // even if there are errors while compiling the schema.\n      currentCompilingNode = prevCompilingNode;\n    }\n    return path;\n  }\n\n  /**\n   * Creates a SchemaImpl from the given SchemaOrSchemaFn.\n   */\n  static create(schema: SchemaImpl | SchemaOrSchemaFn<any>) {\n    if (schema instanceof SchemaImpl) {\n      return schema;\n    }\n    return new SchemaImpl(schema as SchemaFn<unknown>);\n  }\n\n  /**\n   * Compiles the given schema in a fresh compilation context. This clears the cached results of any\n   * previous compilations.\n   */\n  static rootCompile(schema: SchemaImpl | SchemaOrSchemaFn<any> | undefined): FieldPathNode {\n    try {\n      compiledSchemas.clear();\n      if (schema === undefined) {\n        return FieldPathNode.newRoot();\n      }\n      if (schema instanceof SchemaImpl) {\n        return schema.compile();\n      }\n      return new SchemaImpl(schema as SchemaFn<unknown>).compile();\n    } finally {\n      // Use a try/finally to ensure we properly reset the compilation context upon completion,\n      // even if there are errors while compiling the schema.\n      compiledSchemas.clear();\n    }\n  }\n}\n\n/** Checks if the given value is a schema or schema function. */\nexport function isSchemaOrSchemaFn(value: unknown): value is SchemaOrSchemaFn<unknown> {\n  return value instanceof SchemaImpl || typeof value === 'function';\n}\n\n/** Checks that a path node belongs to the schema function currently being compiled. */\nexport function assertPathIsCurrent(path: SchemaPath<unknown>): void {\n  if (currentCompilingNode !== FieldPathNode.unwrapFieldPath(path).root) {\n    throw new RuntimeError(\n      RuntimeErrorCode.PATH_OUTSIDE_SCHEMA,\n      ngDevMode &&\n        `A FieldPath can only be used directly within the Schema that owns it, **not** outside of it or within a sub-schema.`,\n    );\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {type Signal} from '@angular/core';\nimport {FieldPathNode} from '../../schema/path_node';\nimport {assertPathIsCurrent} from '../../schema/schema';\nimport type {LogicFn, PathKind, SchemaPath, SchemaPathRules} from '../types';\n\n/**\n * Sets a value for the {@link MetadataKey} for this field.\n *\n * This value is combined via a reduce operation defined by the particular key,\n * since multiple rules in the schema might set values for it.\n *\n * @param path The target path to set the metadata for.\n * @param key The metadata key\n * @param logic A function that receives the `FieldContext` and returns a value for the metadata.\n * @template TValue The type of value stored in the field the logic is bound to.\n * @template TKey The type of metadata key.\n * @template TPathKind The kind of path the logic is bound to (a root path, child path, or item of an array)\n *\n * @category logic\n * @experimental 21.0.0\n */\nexport function metadata<\n  TValue,\n  TKey extends MetadataKey<any, any, any>,\n  TPathKind extends PathKind = PathKind.Root,\n>(\n  path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>,\n  key: TKey,\n  logic: NoInfer<LogicFn<TValue, MetadataSetterType<TKey>, TPathKind>>,\n): TKey {\n  assertPathIsCurrent(path);\n\n  const pathNode = FieldPathNode.unwrapFieldPath(path);\n  pathNode.builder.addMetadataRule(key, logic);\n  return key;\n}\n\n/**\n * A reducer that determines the accumulated value for a metadata key by reducing the individual\n * values contributed from `metadata()` rules.\n *\n * @template TAcc The accumulated type of the reduce operation.\n * @template TItem The type of the individual items that are reduced over.\n * @experimental 21.0.2\n */\nexport interface MetadataReducer<TAcc, TItem> {\n  /** The reduce function. */\n  reduce: (acc: TAcc, item: TItem) => TAcc;\n  /** Gets the initial accumulated value. */\n  getInitial: () => TAcc;\n}\nexport const MetadataReducer = {\n  /** Creates a reducer that accumulates a list of its individual item values. */\n  list<TItem>(): MetadataReducer<TItem[], TItem | undefined> {\n    return {\n      reduce: (acc, item) => (item === undefined ? acc : [...acc, item]),\n      getInitial: () => [],\n    };\n  },\n\n  /** Creates a reducer that accumulates the min of its individual item values. */\n  min(): MetadataReducer<number | undefined, number | undefined> {\n    return {\n      reduce: (acc, item) => {\n        if (acc === undefined || item === undefined) {\n          return acc ?? item;\n        }\n        return Math.min(acc, item);\n      },\n      getInitial: () => undefined,\n    };\n  },\n\n  /** Creates a reducer that accumulates a the max of its individual item values. */\n  max(): MetadataReducer<number | undefined, number | undefined> {\n    return {\n      reduce: (prev, next) => {\n        if (prev === undefined || next === undefined) {\n          return prev ?? next;\n        }\n        return Math.max(prev, next);\n      },\n      getInitial: () => undefined,\n    };\n  },\n\n  /** Creates a reducer that logically or's its accumulated value with each individual item value. */\n  or(): MetadataReducer<boolean, boolean> {\n    return {\n      reduce: (prev, next) => prev || next,\n      getInitial: () => false,\n    };\n  },\n\n  /** Creates a reducer that logically and's its accumulated value with each individual item value. */\n  and(): MetadataReducer<boolean, boolean> {\n    return {\n      reduce: (prev, next) => prev && next,\n      getInitial: () => true,\n    };\n  },\n\n  /** Creates a reducer that always takes the next individual item value as the accumulated value. */\n  override,\n} as const;\n\nfunction override<T>(): MetadataReducer<T | undefined, T>;\nfunction override<T>(getInitial: () => T): MetadataReducer<T, T>;\nfunction override<T>(getInitial?: () => T): MetadataReducer<T | undefined, T> {\n  return {\n    reduce: (_, item) => item,\n    getInitial: () => getInitial?.(),\n  };\n}\n\n/**\n * Represents metadata that is aggregated from multiple parts according to the key's reducer\n * function. A value can be contributed to the aggregated value for a field using an\n * `metadata` rule in the schema. There may be multiple rules in a schema that contribute\n * values to the same `MetadataKey` of the same field.\n *\n * @template TRead The type read from the `FieldState` for this key\n * @template TWrite The type written to this key using the `metadata()` rule\n * @template TAcc The type of the reducer's accumulated value.\n *\n * @experimental 21.0.0\n */\nexport class MetadataKey<TRead, TWrite, TAcc> {\n  private brand!: [TRead, TWrite, TAcc];\n\n  /** Use {@link reducedMetadataKey}. */\n  protected constructor(\n    readonly reducer: MetadataReducer<TAcc, TWrite>,\n    readonly create: ((s: Signal<TAcc>) => TRead) | undefined,\n  ) {}\n}\n\n/**\n * Extracts the the type that can be set into the given metadata key type using the `metadata()` rule.\n *\n * @template TKey The `MetadataKey` type\n *\n * @experimental 21.0.0\n */\nexport type MetadataSetterType<TKey> =\n  TKey extends MetadataKey<any, infer TWrite, any> ? TWrite : never;\n\n/**\n * Creates a metadata key used to contain a computed value.\n * The last value set on a given field tree node overrides any previously set values.\n *\n * @template TWrite The type written to this key using the `metadata()` rule\n *\n * @experimental 21.0.0\n */\nexport function createMetadataKey<TWrite>(): MetadataKey<\n  Signal<TWrite | undefined>,\n  TWrite,\n  TWrite | undefined\n>;\n/**\n * Creates a metadata key used to contain a computed value.\n *\n * @param reducer The reducer used to combine individually set values into the final computed value.\n * @template TWrite The type written to this key using the `metadata()` rule\n * @template TAcc The type of the reducer's accumulated value.\n *\n * @experimental 21.0.0\n */\nexport function createMetadataKey<TWrite, TAcc>(\n  reducer: MetadataReducer<TAcc, TWrite>,\n): MetadataKey<Signal<TAcc>, TWrite, TAcc>;\nexport function createMetadataKey<TWrite, TAcc>(\n  reducer?: MetadataReducer<TAcc, TWrite>,\n): MetadataKey<Signal<TAcc>, TWrite, TAcc> {\n  return new (MetadataKey as new (\n    reducer: MetadataReducer<TAcc, TWrite>,\n  ) => MetadataKey<Signal<TAcc>, TWrite, TAcc>)(reducer ?? MetadataReducer.override<any>());\n}\n\n/**\n * Creates a metadata key that exposes a managed value based on the accumulated result of the values\n * written to the key. The accumulated value takes the last value set on a given field tree node,\n * overriding any previously set values.\n *\n * @param create A function that receives a signal of the accumulated value and returns the managed\n *   value based on it. This function runs during the construction of the `FieldTree` node,\n *   and runs in the injection context of that node.\n * @template TRead The type read from the `FieldState` for this key\n * @template TWrite The type written to this key using the `metadata()` rule\n *\n * @experimental 21.0.0\n */\nexport function createManagedMetadataKey<TRead, TWrite>(\n  create: (s: Signal<TWrite | undefined>) => TRead,\n): MetadataKey<TRead, TWrite, TWrite | undefined>;\n/**\n * Creates a metadata key that exposes a managed value based on the accumulated result of the values\n * written to the key.\n *\n * @param create A function that receives a signal of the accumulated value and returns the managed\n *   value based on it. This function runs during the construction of the `FieldTree` node,\n *   and runs in the injection context of that node.\n * @param reducer The reducer used to combine individual value written to the key,\n *   this will determine the accumulated value that the create function receives.\n * @template TRead The type read from the `FieldState` for this key\n * @template TWrite The type written to this key using the `metadata()` rule\n * @template TAcc The type of the reducer's accumulated value.\n *\n * @experimental 21.0.0\n */\nexport function createManagedMetadataKey<TRead, TWrite, TAcc>(\n  create: (s: Signal<TAcc>) => TRead,\n  reducer: MetadataReducer<TAcc, TWrite>,\n): MetadataKey<TRead, TWrite, TAcc>;\nexport function createManagedMetadataKey<TRead, TWrite, TAcc>(\n  create: (s: Signal<TAcc>) => TRead,\n  reducer?: MetadataReducer<TAcc, TWrite>,\n): MetadataKey<TRead, TWrite, TAcc> {\n  return new (MetadataKey as new (\n    reducer: MetadataReducer<TAcc, TWrite>,\n    create: (s: Signal<TAcc>) => TRead,\n  ) => MetadataKey<TRead, TWrite, TAcc>)(reducer ?? MetadataReducer.override<any>(), create);\n}\n\n/**\n * A {@link MetadataKey} representing whether the field is required.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const REQUIRED: MetadataKey<Signal<boolean>, boolean, boolean> = createMetadataKey(\n  MetadataReducer.or(),\n);\n\n/**\n * A {@link MetadataKey} representing the min value of the field.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const MIN: MetadataKey<\n  Signal<number | undefined>,\n  number | undefined,\n  number | undefined\n> = createMetadataKey(MetadataReducer.max());\n\n/**\n * A {@link MetadataKey} representing the max value of the field.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const MAX: MetadataKey<\n  Signal<number | undefined>,\n  number | undefined,\n  number | undefined\n> = createMetadataKey(MetadataReducer.min());\n\n/**\n * A {@link MetadataKey} representing the min length of the field.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const MIN_LENGTH: MetadataKey<\n  Signal<number | undefined>,\n  number | undefined,\n  number | undefined\n> = createMetadataKey(MetadataReducer.max());\n\n/**\n * A {@link MetadataKey} representing the max length of the field.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const MAX_LENGTH: MetadataKey<\n  Signal<number | undefined>,\n  number | undefined,\n  number | undefined\n> = createMetadataKey(MetadataReducer.min());\n\n/**\n * A {@link MetadataKey} representing the patterns the field must match.\n *\n * @category validation\n * @experimental 21.0.0\n */\nexport const PATTERN: MetadataKey<\n  Signal<RegExp[]>,\n  RegExp | undefined,\n  RegExp[]\n> = createMetadataKey(MetadataReducer.list<RegExp>());\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {computed, Signal, untracked, ɵWritable} from '@angular/core';\nimport type {ValidationError} from '../api/rules/validation/validation_errors';\nimport type {FieldTree, TreeValidationResult, ValidationResult} from '../api/types';\nimport {isArray} from '../util/type_guards';\nimport type {FieldNode} from './node';\nimport {shortCircuitFalse} from './util';\n\n/**\n * Helper function taking validation state, and returning own state of the node.\n * @param state\n */\nexport function calculateValidationSelfStatus(\n  state: ValidationState,\n): 'invalid' | 'unknown' | 'valid' {\n  if (state.errors().length > 0) {\n    return 'invalid';\n  }\n  if (state.pending()) {\n    return 'unknown';\n  }\n\n  return 'valid';\n}\n\nexport interface ValidationState {\n  /**\n   * The full set of synchronous tree errors visible to this field. This includes ones that are\n   * targeted at a descendant field rather than at this field.\n   */\n  rawSyncTreeErrors: Signal<ValidationError.WithFieldTree[]>;\n\n  /**\n   * The full set of synchronous errors for this field, including synchronous tree errors and submission\n   * errors. Submission errors are considered \"synchronous\" because they are imperatively added. From\n   * the perspective of the field state they are either there or not, they are never in a pending\n   * state.\n   */\n  syncErrors: Signal<ValidationError.WithFieldTree[]>;\n\n  /**\n   * Whether the field is considered valid according solely to its synchronous validators.\n   * Errors resulting from a previous submit attempt are also considered for this state.\n   */\n  syncValid: Signal<boolean>;\n\n  /**\n   * The full set of asynchronous tree errors visible to this field. This includes ones that are\n   * targeted at a descendant field rather than at this field, as well as sentinel 'pending' values\n   * indicating that the validator is still running and an error could still occur.\n   */\n  rawAsyncErrors: Signal<(ValidationError.WithFieldTree | 'pending')[]>;\n\n  /**\n   * The asynchronous tree errors visible to this field that are specifically targeted at this field\n   * rather than a descendant. This also includes all 'pending' sentinel values, since those could\n   * theoretically result in errors for this field.\n   */\n  asyncErrors: Signal<(ValidationError.WithFieldTree | 'pending')[]>;\n\n  /**\n   * The combined set of all errors that currently apply to this field.\n   */\n  errors: Signal<ValidationError.WithFieldTree[]>;\n\n  parseErrors: Signal<ValidationError.WithFormField[]>;\n\n  /**\n   * The combined set of all errors that currently apply to this field and its descendants.\n   */\n  errorSummary: Signal<ValidationError.WithFieldTree[]>;\n\n  /**\n   * Whether this field has any asynchronous validators still pending.\n   */\n  pending: Signal<boolean>;\n\n  /**\n   * The validation status of the field.\n   * - The status is 'valid' if neither the field nor any of its children has any errors or pending\n   *   validators.\n   * - The status is 'invalid' if the field or any of its children has an error\n   *   (regardless of pending validators)\n   * - The status is 'unknown' if neither the field nor any of its children has any errors,\n   *   but the field or any of its children does have a pending validator.\n   *\n   * A field is considered valid if *all* of the following are true:\n   *  - It has no errors or pending validators\n   *  - All of its children are considered valid\n   * A field is considered invalid if *any* of the following are true:\n   *  - It has an error\n   *  - Any of its children is considered invalid\n   * A field is considered to have unknown validity status if it is not valid or invalid.\n   */\n  status: Signal<'valid' | 'invalid' | 'unknown'>;\n  /**\n   * Whether the field is considered valid.\n   *\n   * A field is considered valid if *all* of the following are true:\n   *  - It has no errors or pending validators\n   *  - All of its children are considered valid\n   *\n   * Note: `!valid()` is *not* the same as `invalid()`. Both `valid()` and `invalid()` can be false\n   * if there are currently no errors, but validators are still pending.\n   */\n  valid: Signal<boolean>;\n\n  /**\n   * Whether the field is considered invalid.\n   *\n   * A field is considered invalid if *any* of the following are true:\n   *  - It has an error\n   *  - Any of its children is considered invalid\n   *\n   * Note: `!invalid()` is *not* the same as `valid()`. Both `valid()` and `invalid()` can be false\n   * if there are currently no errors, but validators are still pending.\n   */\n  invalid: Signal<boolean>;\n\n  /**\n   * Indicates whether validation should be skipped for this field because it is hidden, disabled,\n   * or readonly.\n   */\n  shouldSkipValidation: Signal<boolean>;\n}\n\n/**\n * The validation state associated with a `FieldNode`.\n *\n * This class collects together various types of errors to represent the full validation state of\n * the field. There are 4 types of errors that need to be combined to determine validity:\n * 1. The synchronous errors produced by the schema logic.\n * 2. The synchronous tree errors produced by the schema logic. Tree errors may apply to a different\n *    field than the one that the logic that produced them is bound to. They support targeting the\n *    error at an arbitrary descendant field.\n * 3. The asynchronous tree errors produced by the schema logic. These work like synchronous tree\n *    errors, except the error list may also contain a special sentinel value indicating that a\n *    validator is still running.\n * 4. Server errors are not produced by the schema logic, but instead get imperatively added when a\n *    form submit fails with errors.\n */\nexport class FieldValidationState implements ValidationState {\n  constructor(readonly node: FieldNode) {}\n\n  /**\n   * The full set of synchronous tree errors visible to this field. This includes ones that are\n   * targeted at a descendant field rather than at this field.\n   */\n  readonly rawSyncTreeErrors: Signal<ValidationError.WithFieldTree[]> = computed(() => {\n    if (this.shouldSkipValidation()) {\n      return [];\n    }\n\n    return [\n      ...this.node.logicNode.logic.syncTreeErrors.compute(this.node.context),\n      ...(this.node.structure.parent?.validationState.rawSyncTreeErrors() ?? []),\n    ];\n  });\n\n  /**\n   * The full set of synchronous errors for this field, including synchronous tree errors and\n   * submission errors. Submission errors are considered \"synchronous\" because they are imperatively\n   * added. From the perspective of the field state they are either there or not, they are never in a\n   * pending state.\n   */\n  readonly syncErrors: Signal<ValidationError.WithFieldTree[]> = computed(() => {\n    // Short-circuit running validators if validation doesn't apply to this field.\n    if (this.shouldSkipValidation()) {\n      return [];\n    }\n\n    return [\n      ...this.node.logicNode.logic.syncErrors.compute(this.node.context),\n      ...this.syncTreeErrors(),\n      ...normalizeErrors(this.node.submitState.submissionErrors()),\n    ];\n  });\n\n  /**\n   * Whether the field is considered valid according solely to its synchronous validators.\n   * Errors resulting from a previous submit attempt are also considered for this state.\n   */\n  readonly syncValid: Signal<boolean> = computed(() => {\n    // Short-circuit checking children if validation doesn't apply to this field.\n    if (this.shouldSkipValidation()) {\n      return true;\n    }\n\n    return this.node.structure.reduceChildren(\n      this.syncErrors().length === 0,\n      (child, value) => value && child.validationState.syncValid(),\n      shortCircuitFalse,\n    );\n  });\n\n  /**\n   * The synchronous tree errors visible to this field that are specifically targeted at this field\n   * rather than a descendant.\n   */\n  readonly syncTreeErrors: Signal<ValidationError.WithFieldTree[]> = computed(() =>\n    this.rawSyncTreeErrors().filter((err) => err.fieldTree === this.node.fieldTree),\n  );\n\n  /**\n   * The full set of asynchronous tree errors visible to this field. This includes ones that are\n   * targeted at a descendant field rather than at this field, as well as sentinel 'pending' values\n   * indicating that the validator is still running and an error could still occur.\n   */\n  readonly rawAsyncErrors: Signal<(ValidationError.WithFieldTree | 'pending')[]> = computed(() => {\n    // Short-circuit running validators if validation doesn't apply to this field.\n    if (this.shouldSkipValidation()) {\n      return [];\n    }\n\n    return [\n      // TODO: add field in `validateAsync` and remove this map\n      ...this.node.logicNode.logic.asyncErrors.compute(this.node.context),\n      // TODO: does it make sense to filter this to errors in this subtree?\n      ...(this.node.structure.parent?.validationState.rawAsyncErrors() ?? []),\n    ];\n  });\n\n  /**\n   * The asynchronous tree errors visible to this field that are specifically targeted at this field\n   * rather than a descendant. This also includes all 'pending' sentinel values, since those could\n   * theoretically result in errors for this field.\n   */\n  readonly asyncErrors: Signal<(ValidationError.WithFieldTree | 'pending')[]> = computed(() => {\n    if (this.shouldSkipValidation()) {\n      return [];\n    }\n    return this.rawAsyncErrors().filter(\n      (err) => err === 'pending' || err.fieldTree === this.node.fieldTree,\n    );\n  });\n\n  readonly parseErrors: Signal<ValidationError.WithFormField[]> = computed(() =>\n    this.node.formFieldBindings().flatMap((field) => field.parseErrors()),\n  );\n\n  /**\n   * The combined set of all errors that currently apply to this field.\n   */\n  readonly errors = computed(() => [\n    ...this.parseErrors(),\n    ...this.syncErrors(),\n    ...this.asyncErrors().filter((err) => err !== 'pending'),\n  ]);\n\n  readonly errorSummary = computed(() => {\n    const errors = this.node.structure.reduceChildren(this.errors(), (child, result) => [\n      ...result,\n      ...child.errorSummary(),\n    ]);\n    // Sort by DOM order on client-side only.\n    if (typeof ngServerMode === 'undefined' || !ngServerMode) {\n      untracked(() => errors.sort(compareErrorPosition));\n    }\n    return errors;\n  });\n\n  /**\n   * Whether this field has any asynchronous validators still pending.\n   */\n  readonly pending = computed(() =>\n    this.node.structure.reduceChildren(\n      this.asyncErrors().includes('pending'),\n      (child, value) => value || child.validationState.asyncErrors().includes('pending'),\n    ),\n  );\n\n  /**\n   * The validation status of the field.\n   * - The status is 'valid' if neither the field nor any of its children has any errors or pending\n   *   validators.\n   * - The status is 'invalid' if the field or any of its children has an error\n   *   (regardless of pending validators)\n   * - The status is 'unknown' if neither the field nor any of its children has any errors,\n   *   but the field or any of its children does have a pending validator.\n   *\n   * A field is considered valid if *all* of the following are true:\n   *  - It has no errors or pending validators\n   *  - All of its children are considered valid\n   * A field is considered invalid if *any* of the following are true:\n   *  - It has an error\n   *  - Any of its children is considered invalid\n   * A field is considered to have unknown validity status if it is not valid or invalid.\n   */\n  readonly status: Signal<'valid' | 'invalid' | 'unknown'> = computed(() => {\n    // Short-circuit checking children if validation doesn't apply to this field.\n    if (this.shouldSkipValidation()) {\n      return 'valid';\n    }\n    let ownStatus = calculateValidationSelfStatus(this);\n\n    return this.node.structure.reduceChildren<'valid' | 'invalid' | 'unknown'>(\n      ownStatus,\n      (child, value) => {\n        if (value === 'invalid' || child.validationState.status() === 'invalid') {\n          return 'invalid';\n        } else if (value === 'unknown' || child.validationState.status() === 'unknown') {\n          return 'unknown';\n        }\n        return 'valid';\n      },\n      (v) => v === 'invalid', // short-circuit on 'invalid'\n    );\n  });\n\n  /**\n   * Whether the field is considered valid.\n   *\n   * A field is considered valid if *all* of the following are true:\n   *  - It has no errors or pending validators\n   *  - All of its children are considered valid\n   *\n   * Note: `!valid()` is *not* the same as `invalid()`. Both `valid()` and `invalid()` can be false\n   * if there are currently no errors, but validators are still pending.\n   */\n  readonly valid = computed(() => this.status() === 'valid');\n\n  /**\n   * Whether the field is considered invalid.\n   *\n   * A field is considered invalid if *any* of the following are true:\n   *  - It has an error\n   *  - Any of its children is considered invalid\n   *\n   * Note: `!invalid()` is *not* the same as `valid()`. Both `valid()` and `invalid()` can be false\n   * if there are currently no errors, but validators are still pending.\n   */\n  readonly invalid = computed(() => this.status() === 'invalid');\n\n  /**\n   * Indicates whether validation should be skipped for this field because it is hidden, disabled,\n   * or readonly.\n   */\n  readonly shouldSkipValidation = computed(\n    () => this.node.hidden() || this.node.disabled() || this.node.readonly(),\n  );\n}\n\n/** Normalizes a validation result to a list of validation errors. */\nfunction normalizeErrors<T extends ValidationResult>(error: T | readonly T[]): readonly T[] {\n  if (error === undefined) {\n    return [];\n  }\n\n  if (isArray(error)) {\n    return error as readonly T[];\n  }\n\n  return [error as T];\n}\n\n/**\n * Sets the given field on the given error(s) if it does not already have a field.\n * @param error The error(s) to add the field to\n * @param fieldTree The default field to add\n * @returns The passed in error(s), with its field set.\n */\nexport function addDefaultField<E extends ValidationError.WithOptionalFieldTree>(\n  error: E,\n  fieldTree: FieldTree<unknown>,\n): E & {fieldTree: FieldTree<unknown>};\nexport function addDefaultField<E extends ValidationError>(\n  errors: TreeValidationResult<E>,\n  fieldTree: FieldTree<unknown>,\n): ValidationResult<E & {fieldTree: FieldTree<unknown>}>;\nexport function addDefaultField<E extends ValidationError>(\n  errors: TreeValidationResult<E>,\n  fieldTree: FieldTree<unknown>,\n): ValidationResult<E & {fieldTree: FieldTree<unknown>}> {\n  if (isArray(errors)) {\n    for (const error of errors) {\n      (error as ɵWritable<ValidationError.WithOptionalFieldTree>).fieldTree ??= fieldTree;\n    }\n  } else if (errors) {\n    (errors as ɵWritable<ValidationError.WithOptionalFieldTree>).fieldTree ??= fieldTree;\n  }\n  return errors as ValidationResult<E & {fieldTree: FieldTree<unknown>}>;\n}\n\nfunction getFirstBoundElement(error: ValidationError.WithFieldTree) {\n  if (error.formField) return error.formField.element;\n  return error\n    .fieldTree()\n    .formFieldBindings()\n    .reduce<HTMLElement | undefined>((el: HTMLElement | undefined, binding) => {\n      if (!el || !binding.element) return el ?? binding.element;\n      return el.compareDocumentPosition(binding.element) & Node.DOCUMENT_POSITION_PRECEDING\n        ? binding.element\n        : el;\n    }, undefined);\n}\n\n/**\n * Compares the position of two validation errors by the position of their corresponding field\n * binding directive in the DOM.\n * - For errors with multiple field bindings, the earliest one in the DOM will be used for comparison.\n * - For errors that have no field bindings, they will be considered to come after all other errors.\n */\nfunction compareErrorPosition(\n  a: ValidationError.WithFieldTree,\n  b: ValidationError.WithFieldTree,\n): number {\n  const aEl = getFirstBoundElement(a);\n  const bEl = getFirstBoundElement(b);\n  if (aEl === bEl) return 0;\n  if (aEl === undefined || bEl === undefined) return aEl === undefined ? 1 : -1;\n  return aEl.compareDocumentPosition(bEl) & Node.DOCUMENT_POSITION_PRECEDING ? 1 : -1;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type {Signal} from '@angular/core';\nimport {createMetadataKey, MetadataKey} from '../api/rules/metadata';\nimport {Debouncer} from '../api/types';\n\n/**\n * A private {@link MetadataKey} used to aggregate `debounce()` rules.\n *\n * This will pick the last `debounce()` rule on a field that is currently applied, if conditional.\n */\nexport const DEBOUNCER: MetadataKey<\n  Signal<Debouncer<any> | undefined> | undefined,\n  Debouncer<any> | undefined,\n  Debouncer<any> | undefined\n> = createMetadataKey();\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {\n  computed,\n  Signal,\n  untracked,\n  WritableSignal,\n  ɵRuntimeError as RuntimeError,\n} from '@angular/core';\nimport {RuntimeErrorCode} from '../errors';\nimport {AbstractControl} from '@angular/forms';\nimport {\n  FieldContext,\n  FieldState,\n  FieldTree,\n  SchemaPath,\n  SchemaPathRules,\n  SchemaPathTree,\n} from '../api/types';\nimport {FieldPathNode} from '../schema/path_node';\nimport {isArray} from '../util/type_guards';\nimport type {FieldNode} from './node';\nimport {getBoundPathDepth} from './resolution';\n\n/**\n * `FieldContext` implementation, backed by a `FieldNode`.\n */\nexport class FieldNodeContext implements FieldContext<unknown> {\n  /**\n   * Cache of paths that have been resolved for this context.\n   *\n   * For each resolved path we keep track of a signal of field that it maps to rather than a static\n   * field, since it theoretically could change. In practice for the current system it should not\n   * actually change, as they only place we currently track fields moving within the parent\n   * structure is for arrays, and paths do not currently support array indexing.\n   */\n  private readonly cache = new WeakMap<\n    SchemaPath<unknown, SchemaPathRules>,\n    Signal<FieldTree<unknown>>\n  >();\n\n  constructor(\n    /** The field node this context corresponds to. */\n    private readonly node: FieldNode,\n  ) {}\n\n  /**\n   * Resolves a target path relative to this context.\n   * @param target The path to resolve\n   * @returns The field corresponding to the target path.\n   */\n  private resolve<U>(target: SchemaPath<U, SchemaPathRules>): FieldTree<U> {\n    if (!this.cache.has(target)) {\n      const resolver = computed<FieldTree<unknown>>(() => {\n        const targetPathNode = FieldPathNode.unwrapFieldPath(target);\n\n        // First, find the field where the root our target path was merged in.\n        // We determine this by walking up the field tree from the current field and looking for\n        // the place where the LogicNodeBuilder from the target path's root was merged in.\n        // We always make sure to walk up at least as far as the depth of the path we were bound to.\n        // This ensures that we do not accidentally match on the wrong application of a recursively\n        // applied schema.\n        let field: FieldNode | undefined = this.node;\n        let stepsRemaining = getBoundPathDepth();\n        while (stepsRemaining > 0 || !field.structure.logic.hasLogic(targetPathNode.root.builder)) {\n          stepsRemaining--;\n          field = field.structure.parent;\n          if (field === undefined) {\n            throw new RuntimeError(\n              RuntimeErrorCode.PATH_NOT_IN_FIELD_TREE,\n              ngDevMode && 'Path is not part of this field tree.',\n            );\n          }\n        }\n\n        // Now, we can navigate to the target field using the relative path in the target path node\n        // to traverse down from the field we just found.\n        for (let key of targetPathNode.keys) {\n          field = field.structure.getChild(key);\n          if (field === undefined) {\n            throw new RuntimeError(\n              RuntimeErrorCode.PATH_RESOLUTION_FAILED,\n              ngDevMode &&\n                `Cannot resolve path .${targetPathNode.keys.join('.')} relative to field ${[\n                  '<root>',\n                  ...this.node.structure.pathKeys(),\n                ].join('.')}.`,\n            );\n          }\n        }\n\n        return field.fieldTree;\n      });\n\n      this.cache.set(target, resolver);\n    }\n    return this.cache.get(target)!() as FieldTree<U>;\n  }\n\n  get fieldTree(): FieldTree<unknown> {\n    return this.node.fieldProxy;\n  }\n\n  get state(): FieldState<unknown> {\n    return this.node;\n  }\n\n  get value(): WritableSignal<unknown> {\n    return this.node.structure.value;\n  }\n\n  get key(): Signal<string> {\n    return this.node.structure.keyInParent;\n  }\n\n  get pathKeys(): Signal<readonly string[]> {\n    return this.node.structure.pathKeys;\n  }\n\n  readonly index = computed(() => {\n    // Attempt to read the key first, this will throw an error if we're on a root field.\n    const key = this.key();\n    // Assert that the parent is actually an array.\n    if (!isArray(untracked(this.node.structure.parent!.value))) {\n      throw new RuntimeError(\n        RuntimeErrorCode.PARENT_NOT_ARRAY,\n        ngDevMode && 'Cannot access index, parent field is not an array.',\n      );\n    }\n    // Return the key as a number if we are indeed inside an array field.\n    return Number(key);\n  });\n\n  readonly fieldTreeOf = <TModel>(p: SchemaPathTree<TModel>) => this.resolve<TModel>(p);\n  readonly stateOf = <TModel>(p: SchemaPath<TModel, SchemaPathRules>) => this.resolve<TModel>(p)();\n  readonly valueOf = <TValue>(p: SchemaPath<TValue, SchemaPathRules>) => {\n    const result = this.resolve(p)().value();\n\n    if (result instanceof AbstractControl) {\n      throw new RuntimeError(\n        RuntimeErrorCode.ABSTRACT_CONTROL_IN_FORM,\n        ngDevMode &&\n          `Tried to read an 'AbstractControl' value from a 'form()'. Did you mean to use 'compatForm()' instead?`,\n      );\n    }\n    return result;\n  };\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {\n  computed,\n  runInInjectionContext,\n  untracked,\n  ɵRuntimeError as RuntimeError,\n} from '@angular/core';\nimport {MetadataKey} from '../api/rules/metadata';\nimport {RuntimeErrorCode} from '../errors';\nimport type {FieldNode} from './node';\n\n/**\n * Tracks custom metadata associated with a `FieldNode`.\n */\nexport class FieldMetadataState {\n  /** A map of all `MetadataKey` that have been defined for this field. */\n  private readonly metadata = new Map<MetadataKey<unknown, unknown, unknown>, unknown>();\n\n  constructor(private readonly node: FieldNode) {\n    // Force eager creation of managed keys,\n    // as managed keys have a `create` function that needs to run during construction.\n    for (const key of this.node.logicNode.logic.getMetadataKeys()) {\n      if (key.create) {\n        const logic = this.node.logicNode.logic.getMetadata(key);\n        const result = untracked(() =>\n          runInInjectionContext(this.node.structure.injector, () =>\n            key.create!(computed(() => logic.compute(this.node.context))),\n          ),\n        );\n        this.metadata.set(key, result);\n      }\n    }\n  }\n\n  /** Gets the value of an `MetadataKey` for the field. */\n  get<T>(key: MetadataKey<T, unknown, unknown>): T | undefined {\n    // We create non-managed metadata lazily, the first time they are accessed.\n    if (this.has(key)) {\n      if (!this.metadata.has(key)) {\n        if (key.create) {\n          throw new RuntimeError(\n            RuntimeErrorCode.MANAGED_METADATA_LAZY_CREATION,\n            ngDevMode && 'Managed metadata cannot be created lazily',\n          );\n        }\n        const logic = this.node.logicNode.logic.getMetadata(key);\n        this.metadata.set(\n          key,\n          computed(() => logic.compute(this.node.context)),\n        );\n      }\n    }\n    return this.metadata.get(key) as T | undefined;\n  }\n\n  /** Checks whether the current metadata state has the given metadata key. */\n  has(key: MetadataKey<any, any, any>): boolean {\n    // Metadata keys get added to the map lazily, on first access,\n    // so we can't rely on checking presence in the metadata map.\n    // Instead we check if there is any logic for the given metadata key.\n    return this.node.logicNode.logic.hasMetadata(key);\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {untracked} from '@angular/core';\nimport {isArray, isObject} from '../util/type_guards';\nimport type {FieldNode} from './node';\n\n/**\n * Proxy handler which implements `FieldTree<T>` on top of `FieldNode`.\n */\nexport const FIELD_PROXY_HANDLER: ProxyHandler<() => FieldNode> = {\n  get(getTgt: () => FieldNode, p: string | symbol, receiver: {[key: string]: unknown}) {\n    const tgt = getTgt();\n\n    // First, check whether the requested property is a defined child node of this node.\n    const child = tgt.structure.getChild(p);\n    if (child !== undefined) {\n      // If so, return the child node's `FieldTree` proxy, allowing the developer to continue\n      // navigating the form structure.\n      return child.fieldTree;\n    }\n\n    // Otherwise, we need to consider whether the properties they're accessing are related to array\n    // iteration. We're specifically interested in `length`, but we only want to pass this through\n    // if the value is actually an array.\n    //\n    // We untrack the value here to avoid spurious reactive notifications. In reality, we've already\n    // incurred a dependency on the value via `tgt.getChild()` above.\n    const value = untracked(tgt.value);\n\n    if (isArray(value)) {\n      // Allow access to the length for field arrays, it should be the same as the length of the data.\n      if (p === 'length') {\n        return (tgt.value() as Array<unknown>).length;\n      }\n      // Allow access to the iterator. This allows the user to spread the field array into a\n      // standard array in order to call methods like `filter`, `map`, etc.\n      if (p === Symbol.iterator) {\n        return () => {\n          // When creating an iterator, we need to account for reactivity. The iterator itself will\n          // read things each time `.next()` is called, but that may happen outside of the context\n          // where the iterator was created (e.g. with `@for`, actual diffing happens outside the\n          // reactive context of the template).\n          //\n          // Instead, side-effectfully read the value here to ensure iterator creation is reactive.\n          tgt.value();\n          return Array.prototype[Symbol.iterator].apply(tgt.fieldTree);\n        };\n      }\n      // Note: We can consider supporting additional array methods if we want in the future,\n      // but they should be thoroughly tested. Just forwarding the method directly from the\n      // `Array` prototype results in broken behavior for some methods like `map`.\n    }\n\n    if (isObject(value)) {\n      // For object fields, allow iteration over their entries for convenience of use with `@for`.\n      if (p === Symbol.iterator) {\n        return function* () {\n          for (const key in receiver) {\n            yield [key, receiver[key]];\n          }\n        };\n      }\n    }\n\n    // Otherwise, this property doesn't exist.\n    return undefined;\n  },\n\n  getOwnPropertyDescriptor(getTgt, prop) {\n    const value = untracked(getTgt().value) as Object;\n    const desc = Reflect.getOwnPropertyDescriptor(value, prop);\n    // In order for `Object.keys` to function properly, keys must be reported as configurable.\n    if (desc && !desc.configurable) {\n      desc.configurable = true;\n    }\n    return desc;\n  },\n\n  ownKeys(getTgt: () => FieldNode) {\n    const value = untracked(getTgt().value);\n    return typeof value === 'object' && value !== null ? Reflect.ownKeys(value) : [];\n  },\n};\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {computed, Signal, untracked, WritableSignal} from '@angular/core';\nimport {SIGNAL} from '@angular/core/primitives/signals';\nimport {isArray} from './type_guards';\n\n/**\n * Creates a writable signal for a specific property on a source writeable signal.\n * @param source A writeable signal to derive from\n * @param prop A signal of a property key of the source value\n * @returns A writeable signal for the given property of the source value.\n * @template S The source value type\n * @template K The key type for S\n */\nexport function deepSignal<S, K extends keyof S>(\n  source: WritableSignal<S>,\n  prop: Signal<K>,\n): WritableSignal<S[K]> {\n  // Memoize the property.\n  const read = computed(() => source()[prop()]) as WritableSignal<S[K]>;\n\n  read[SIGNAL] = source[SIGNAL];\n  read.set = (value: S[K]) => {\n    source.update((current) => valueForWrite(current, value, prop()) as S);\n  };\n\n  read.update = (fn: (current: S[K]) => S[K]) => {\n    read.set(fn(untracked(read)));\n  };\n  read.asReadonly = () => read;\n\n  return read;\n}\n\n/**\n * Gets an updated root value to use when setting a value on a deepSignal with the given path.\n * @param sourceValue The current value of the deepSignal's source.\n * @param newPropValue The value being written to the deepSignal's property\n * @param prop The deepSignal's property key\n * @returns An updated value for the deepSignal's source\n */\nfunction valueForWrite(sourceValue: unknown, newPropValue: unknown, prop: PropertyKey): unknown {\n  if (isArray(sourceValue)) {\n    const newValue = [...sourceValue];\n    newValue[prop as number] = newPropValue;\n    return newValue;\n  } else {\n    return {...(sourceValue as object), [prop]: newPropValue};\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {\n  computed,\n  DestroyableInjector,\n  Injector,\n  linkedSignal,\n  ɵRuntimeError as RuntimeError,\n  Signal,\n  untracked,\n  WritableSignal,\n} from '@angular/core';\n\nimport {RuntimeErrorCode} from '../errors';\n\nimport {LogicNode} from '../schema/logic_node';\nimport type {FieldPathNode} from '../schema/path_node';\nimport {deepSignal} from '../util/deep_signal';\nimport {isArray, isObject} from '../util/type_guards';\nimport type {FieldAdapter} from './field_adapter';\nimport type {FormFieldManager} from './manager';\nimport type {FieldNode, ParentFieldNode} from './node';\n\n/**\n * Key by which a parent `FieldNode` tracks its children.\n *\n * Often this is the actual property key of the child, but in the case of arrays it could be a\n * tracking key allocated for the object.\n */\nexport type TrackingKey = PropertyKey & {__brand: 'FieldIdentity'};\nexport type ChildNodeCtor = (\n  key: string,\n  trackingKey: TrackingKey | undefined,\n  isArray: boolean,\n) => FieldNode;\n\n/** Structural component of a `FieldNode` which tracks its path, parent, and children. */\nexport abstract class FieldNodeStructure {\n  /**\n   * Computed map of child fields, based on the current value of this field.\n   *\n   * This structure reacts to `this.value` and produces a new `ChildrenData` when the\n   * value changes structurally (fields added/removed/moved).\n   */\n  protected abstract readonly childrenMap: Signal<ChildrenData | undefined>;\n\n  /** The field's value. */\n  abstract readonly value: WritableSignal<unknown>;\n\n  /**\n   * The key of this field in its parent field.\n   * Attempting to read this for the root field will result in an error being thrown.\n   */\n  abstract readonly keyInParent: Signal<string>;\n\n  /** The field manager responsible for managing this field. */\n  abstract readonly fieldManager: FormFieldManager;\n\n  /** The root field that this field descends from. */\n  abstract readonly root: FieldNode;\n\n  /** The list of property keys to follow to get from the `root` to this field. */\n  abstract readonly pathKeys: Signal<readonly string[]>;\n\n  /** The parent field of this field. */\n  abstract readonly parent: FieldNode | undefined;\n\n  readonly logic: LogicNode;\n  readonly node: FieldNode;\n\n  readonly createChildNode: ChildNodeCtor;\n\n  /** Added to array elements for tracking purposes. */\n  // TODO: given that we don't ever let a field move between parents, is it safe to just extract\n  // this to a shared symbol for all fields, rather than having a separate one per parent?\n  readonly identitySymbol = Symbol();\n\n  /** Lazily initialized injector. Do not access directly, access via `injector` getter instead. */\n  private _injector: DestroyableInjector | undefined = undefined;\n\n  /** Lazily initialized injector. */\n  get injector(): DestroyableInjector {\n    this._injector ??= Injector.create({\n      providers: [],\n      parent: this.fieldManager.injector,\n    }) as DestroyableInjector;\n    return this._injector;\n  }\n\n  constructor(logic: LogicNode, node: FieldNode, createChildNode: ChildNodeCtor) {\n    this.logic = logic;\n    this.node = node;\n    this.createChildNode = createChildNode;\n  }\n\n  /** Gets the child fields of this field. */\n  children(): readonly FieldNode[] {\n    const map = this.childrenMap();\n    if (map === undefined) {\n      return [];\n    }\n    return Array.from(map.byPropertyKey.values()).map((child) => untracked(child.reader)!);\n  }\n\n  /** Retrieve a child `FieldNode` of this node by property key. */\n  getChild(key: PropertyKey): FieldNode | undefined {\n    const strKey = key.toString();\n\n    // Lookup the computed reader for this key in `childrenMap`. This lookup doesn't need to be\n    // reactive since `childrenMap` guarantees it will always return the same `reader` for the same\n    // `key`, so long as that key exists.\n    let reader = untracked(this.childrenMap)?.byPropertyKey.get(strKey)?.reader;\n\n    if (!reader) {\n      // The key doesn't exist / doesn't have a child field associated with it. In this case, we\n      // need to be clever. We want to return `undefined`, but also be notified by reactivity if the\n      // field _does_ pop into existence later. Basically, we want to depend on a reader for a key\n      // that doesn't exist.\n      //\n      // We do precisely that by creating an ephemeral reader which will be read and then dropped.\n      // If we're in a reactive context, the ephemeral reader will live on in the dependencies of\n      // that context and notify it if the field is later created. When the reactive context reruns,\n      // it will again attempt the read which will call `getChild()`, which will then find the real\n      // reader for that key.\n      reader = this.createReader(strKey);\n    }\n\n    return reader();\n  }\n\n  /**\n   * Perform a reduction over a field's children (if any) and return the result.\n   *\n   * Optionally, the reduction is short circuited based on the provided `shortCircuit` function.\n   */\n  reduceChildren<T>(\n    initialValue: T,\n    fn: (child: FieldNode, value: T) => T,\n    shortCircuit?: (value: T) => boolean,\n  ): T {\n    const map = this.childrenMap();\n    if (!map) {\n      return initialValue;\n    }\n\n    let value = initialValue;\n    for (const child of map.byPropertyKey.values()) {\n      if (shortCircuit?.(value)) {\n        break;\n      }\n      value = fn(untracked(child.reader)!, value);\n    }\n    return value;\n  }\n\n  /** Destroys the field when it is no longer needed. */\n  destroy(): void {\n    this.injector.destroy();\n  }\n\n  /**\n   * Creates a keyInParent signal for a field node.\n   *\n   * For root nodes, returns ROOT_KEY_IN_PARENT which throws when accessed.\n   * For child nodes, creates a computed that tracks the field's current key in its parent,\n   * with special handling for tracked array elements.\n   *\n   * @param options The field node options\n   * @param identityInParent The tracking identity (only for tracked array children)\n   * @param initialKeyInParent The initial key in parent (only for child nodes)\n   * @returns A signal representing the field's key in its parent\n   */\n  protected createKeyInParent(\n    options: FieldNodeOptions,\n    identityInParent: TrackingKey | undefined,\n    initialKeyInParent: string | undefined,\n  ): Signal<string> {\n    if (options.kind === 'root') {\n      return ROOT_KEY_IN_PARENT;\n    }\n\n    if (identityInParent === undefined) {\n      const key = initialKeyInParent!;\n      return computed(() => {\n        if (this.parent!.structure.getChild(key) !== this.node) {\n          throw new RuntimeError(\n            RuntimeErrorCode.ORPHAN_FIELD_PROPERTY,\n            ngDevMode &&\n              `Orphan field, looking for property '${key}' of ${getDebugName(this.parent!)}`,\n          );\n        }\n        return key;\n      });\n    } else {\n      let lastKnownKey = initialKeyInParent!;\n      return computed(() => {\n        // TODO(alxhub): future perf optimization: here we depend on the parent's value, but most\n        // changes to the value aren't structural - they aren't moving around objects and thus\n        // shouldn't affect `keyInParent`. We currently mitigate this issue via `lastKnownKey`\n        // which avoids a search.\n        const parentValue = this.parent!.structure.value();\n        if (!isArray(parentValue)) {\n          // It should not be possible to encounter this error. It would require the parent to\n          // change from an array field to non-array field. However, in the current implementation\n          // a field's parent can never change.\n          throw new RuntimeError(\n            RuntimeErrorCode.ORPHAN_FIELD_ARRAY,\n            ngDevMode && `Orphan field, expected ${getDebugName(this.parent!)} to be an array`,\n          );\n        }\n\n        // Check the parent value at the last known key to avoid a scan.\n        // Note: lastKnownKey is a string, but we pretend to typescript like its a number,\n        // since accessing someArray['1'] is the same as accessing someArray[1]\n        const data = parentValue[lastKnownKey as unknown as number];\n        if (\n          isObject(data) &&\n          data.hasOwnProperty(this.parent!.structure.identitySymbol) &&\n          data[this.parent!.structure.identitySymbol] === identityInParent\n        ) {\n          return lastKnownKey;\n        }\n\n        // Otherwise, we need to check all the keys in the parent.\n        for (let i = 0; i < parentValue.length; i++) {\n          const data = parentValue[i];\n          if (\n            isObject(data) &&\n            data.hasOwnProperty(this.parent!.structure.identitySymbol) &&\n            data[this.parent!.structure.identitySymbol] === identityInParent\n          ) {\n            return (lastKnownKey = i.toString());\n          }\n        }\n\n        throw new RuntimeError(\n          RuntimeErrorCode.ORPHAN_FIELD_NOT_FOUND,\n          ngDevMode && `Orphan field, can't find element in array ${getDebugName(this.parent!)}`,\n        );\n      });\n    }\n  }\n\n  protected createChildrenMap(): Signal<ChildrenData | undefined> {\n    return linkedSignal({\n      source: this.value,\n      computation: (\n        value: unknown,\n        previous: {source: unknown; value: ChildrenData | undefined} | undefined,\n      ): ChildrenData | undefined => {\n        if (!isObject(value)) {\n          // Non-object values have no children. This short-circuit path makes `childrenMap` fast\n          // for primitive-valued fields.\n          return undefined;\n        }\n\n        // Previous `ChildrenData` (immutable). This is also where we first initialize our map if\n        // needed.\n        const prevData: ChildrenData = previous?.value ?? {\n          byPropertyKey: new Map(),\n        };\n\n        // The next `ChildrenData` object to be returned. Initialized lazily when we know there's\n        // been a structural change to the model.\n        let data: MutableChildrenData | undefined;\n\n        const parentIsArray = isArray(value);\n\n        // Remove fields that have disappeared since the last time this map was computed.\n        if (prevData !== undefined) {\n          if (parentIsArray) {\n            data = maybeRemoveStaleArrayFields(prevData, value, this.identitySymbol);\n          } else {\n            data = maybeRemoveStaleObjectFields(prevData, value);\n          }\n        }\n\n        // Now, go through the values and add any new ones.\n        for (const key of Object.keys(value)) {\n          let trackingKey: TrackingKey | undefined = undefined;\n          const childValue = value[key] as unknown;\n\n          // Fields explicitly set to `undefined` are treated as if they don't exist.\n          // This ensures that `{value: undefined}` and `{}` have the same behavior for their `value`\n          // field.\n          if (childValue === undefined) {\n            // The value might have _become_ `undefined`, so we need to delete it here.\n            if (prevData.byPropertyKey.has(key)) {\n              data ??= {...(prevData as MutableChildrenData)};\n              data.byPropertyKey.delete(key);\n            }\n            continue;\n          }\n\n          if (parentIsArray && isObject(childValue) && !isArray(childValue)) {\n            // For object values in arrays, assign a synthetic identity. This will be used to\n            // preserve the field instance even as this object moves around in the parent array.\n            trackingKey = (childValue[this.identitySymbol] as TrackingKey) ??= Symbol(\n              ngDevMode ? `id:${globalId++}` : '',\n            ) as TrackingKey;\n          }\n\n          let childNode: FieldNode | undefined;\n\n          if (trackingKey) {\n            // If tracking is in use, then the `FieldNode` instance is always managed via its\n            // tracking key. Create the instance if needed, or look it up otherwise.\n            if (!prevData.byTrackingKey?.has(trackingKey)) {\n              data ??= {...(prevData as MutableChildrenData)};\n              data.byTrackingKey ??= new Map();\n\n              data.byTrackingKey.set(\n                trackingKey,\n                this.createChildNode(key, trackingKey, parentIsArray),\n              );\n            }\n\n            // Note: data ?? prevData is needed because we might have freshly instantiated\n            // `byTrackingKey` only in `data` above.\n            childNode = (data ?? prevData).byTrackingKey!.get(trackingKey)!;\n          }\n\n          // Next, make sure the `ChildData` for this key in `byPropertyKey` is up to date. We need\n          // to consider two cases:\n          //\n          // 1. No record exists for this field (yet).\n          // 2. A record does exist, but the field identity at this key has changed (only possible\n          //    when fields are tracked).\n          const child = prevData.byPropertyKey.get(key);\n          if (child === undefined) {\n            // No record exists yet - create one.\n            data ??= {...(prevData as MutableChildrenData)};\n\n            data.byPropertyKey.set(key, {\n              // TODO: creating a computed per-key is overkill when the field at a key can't change\n              // (e.g. the value is not an array). Maybe this can be optimized?\n              reader: this.createReader(key),\n              // If tracking is in use, then it already created/found the `childNode` for this key.\n              // Otherwise we create the child field here.\n              node: childNode ?? this.createChildNode(key, trackingKey, parentIsArray),\n            });\n          } else if (childNode && childNode !== child.node) {\n            // A record exists, but records the wrong `FieldNode`. Update it.\n            data ??= {...(prevData as MutableChildrenData)};\n            child.node = childNode;\n          }\n        }\n\n        return data ?? prevData;\n      },\n    });\n  }\n\n  /**\n   * Creates a \"reader\" computed for the given key.\n   *\n   * A reader is a computed signal that memoizes the access of the `FieldNode` stored at this key\n   * (or returns `undefined` if no such field exists). Accessing fields via the reader ensures that\n   * reactive consumers aren't notified unless the field at a key actually changes.\n   */\n  private createReader(key: string): Signal<FieldNode | undefined> {\n    return computed(() => this.childrenMap()?.byPropertyKey.get(key)?.node);\n  }\n}\n\n/** The structural component of a `FieldNode` that is the root of its field tree. */\nexport class RootFieldNodeStructure extends FieldNodeStructure {\n  override get parent(): undefined {\n    return undefined;\n  }\n\n  override get root(): FieldNode {\n    return this.node;\n  }\n\n  override get pathKeys(): Signal<readonly string[]> {\n    return ROOT_PATH_KEYS;\n  }\n\n  override get keyInParent(): Signal<string> {\n    return ROOT_KEY_IN_PARENT;\n  }\n\n  protected override readonly childrenMap: Signal<ChildrenData | undefined>;\n\n  /**\n   * Creates the structure for the root node of a field tree.\n   *\n   * @param node The full field node that this structure belongs to\n   * @param pathNode The path corresponding to this node in the schema\n   * @param logic The logic to apply to this field\n   * @param fieldManager The field manager for this field\n   * @param value The value signal for this field\n   * @param adapter Adapter that knows how to create new fields and appropriate state.\n   * @param createChildNode A factory function to create child nodes for this field.\n   */\n  constructor(\n    /** The full field node that corresponds to this structure. */\n    node: FieldNode,\n    logic: LogicNode,\n    override readonly fieldManager: FormFieldManager,\n    override readonly value: WritableSignal<unknown>,\n    createChildNode: ChildNodeCtor,\n  ) {\n    super(logic, node, createChildNode);\n    this.childrenMap = this.createChildrenMap();\n  }\n}\n\n/** The structural component of a child `FieldNode` within a field tree. */\nexport class ChildFieldNodeStructure extends FieldNodeStructure {\n  override readonly root: FieldNode;\n  override readonly pathKeys: Signal<readonly string[]>;\n  override readonly keyInParent: Signal<string>;\n  override readonly value: WritableSignal<unknown>;\n  override readonly childrenMap: Signal<ChildrenData | undefined>;\n\n  override get fieldManager(): FormFieldManager {\n    return this.root.structure.fieldManager;\n  }\n\n  /**\n   * Creates the structure for a child field node in a field tree.\n   *\n   * @param node The full field node that this structure belongs to\n   * @param pathNode The path corresponding to this node in the schema\n   * @param logic The logic to apply to this field\n   * @param parent The parent field node for this node\n   * @param identityInParent The identity used to track this field in its parent\n   * @param initialKeyInParent The key of this field in its parent at the time of creation\n   * @param adapter Adapter that knows how to create new fields and appropriate state.\n   * @param createChildNode A factory function to create child nodes for this field.\n   */\n  constructor(\n    node: FieldNode,\n    override readonly logic: LogicNode,\n    override readonly parent: ParentFieldNode,\n    identityInParent: TrackingKey | undefined,\n    initialKeyInParent: string,\n    createChildNode: ChildNodeCtor,\n  ) {\n    super(logic, node, createChildNode);\n\n    this.root = this.parent.structure.root;\n\n    this.keyInParent = this.createKeyInParent(\n      {\n        kind: 'child',\n        parent,\n        pathNode: undefined!,\n        logic,\n        initialKeyInParent,\n        identityInParent,\n        fieldAdapter: undefined!,\n      },\n      identityInParent,\n      initialKeyInParent,\n    );\n\n    this.pathKeys = computed(() => [...parent.structure.pathKeys(), this.keyInParent()]);\n\n    this.value = deepSignal(this.parent.structure.value, this.keyInParent);\n    this.childrenMap = this.createChildrenMap();\n    this.fieldManager.structures.add(this);\n  }\n}\n\n/** Global id used for tracking keys. */\nlet globalId = 0;\n\n/** Options passed when constructing a root field node. */\nexport interface RootFieldNodeOptions {\n  /** Kind of node, used to differentiate root node options from child node options. */\n  readonly kind: 'root';\n  /** The path node corresponding to this field in the schema. */\n  readonly pathNode: FieldPathNode;\n  /** The logic to apply to this field. */\n  readonly logic: LogicNode;\n  /** The value signal for this field. */\n  readonly value: WritableSignal<unknown>;\n  /** The field manager for this field. */\n  readonly fieldManager: FormFieldManager;\n  /** This allows for more granular field and state management, and is currently used for compat. */\n  readonly fieldAdapter: FieldAdapter;\n}\n\n/** Options passed when constructing a child field node. */\nexport interface ChildFieldNodeOptions {\n  /** Kind of node, used to differentiate root node options from child node options. */\n  readonly kind: 'child';\n  /** The parent field node of this field. */\n  readonly parent: ParentFieldNode;\n  /** The path node corresponding to this field in the schema. */\n  readonly pathNode: FieldPathNode;\n  /** The logic to apply to this field. */\n  readonly logic: LogicNode;\n  /** The key of this field in its parent at the time of creation. */\n  readonly initialKeyInParent: string;\n  /** The identity used to track this field in its parent. */\n  readonly identityInParent: TrackingKey | undefined;\n  /** This allows for more granular field and state management, and is currently used for compat. */\n  readonly fieldAdapter: FieldAdapter;\n}\n\n/** Options passed when constructing a field node. */\nexport type FieldNodeOptions = RootFieldNodeOptions | ChildFieldNodeOptions;\n\n/** A signal representing an empty list of path keys, used for root fields. */\nconst ROOT_PATH_KEYS = computed<readonly string[]>(() => []);\n\n/**\n * A signal representing a non-existent key of the field in its parent, used for root fields which\n * do not have a parent. This signal will throw if it is read.\n */\nconst ROOT_KEY_IN_PARENT = computed(() => {\n  throw new RuntimeError(\n    RuntimeErrorCode.ROOT_FIELD_NO_PARENT,\n    ngDevMode && 'The top-level field in the form has no parent.',\n  );\n});\n\n/** Gets a human readable name for a field node for use in error messages. */\nfunction getDebugName(node: FieldNode) {\n  return `<root>.${node.structure.pathKeys().join('.')}`;\n}\n\ninterface MutableChildrenData {\n  readonly byPropertyKey: Map<string, ChildData>;\n  byTrackingKey?: Map<TrackingKey, FieldNode>;\n}\n\n/**\n * Derived data regarding child fields for a specific parent field.\n */\ninterface ChildrenData {\n  /**\n   * Tracks `ChildData` for each property key within the parent.\n   */\n  readonly byPropertyKey: ReadonlyMap<string, ChildData>;\n\n  /**\n   * Tracks the instance of child `FieldNode`s by their tracking key, which is always 1:1 with the\n   * fields, even if they move around in the parent.\n   */\n  readonly byTrackingKey?: ReadonlyMap<TrackingKey, FieldNode>;\n}\n\n/**\n * Data for a specific child within a parent.\n */\ninterface ChildData {\n  /**\n   * A computed signal to access the `FieldNode` currently stored at a specific key.\n   *\n   * Because this is a computed, it only updates whenever the `FieldNode` at that key changes.\n   * Because `ChildData` is always associated with a specific key via `ChildrenData.byPropertyKey`,\n   * this computed gives a stable way to watch the field stored for a given property and only\n   * receives notifications when that field changes.\n   */\n  readonly reader: Signal<FieldNode | undefined>;\n\n  /**\n   * The child `FieldNode` currently stored at this key.\n   */\n  node: FieldNode;\n}\n\nfunction maybeRemoveStaleArrayFields(\n  prevData: ChildrenData,\n  value: ReadonlyArray<unknown>,\n  identitySymbol: PropertyKey,\n): MutableChildrenData | undefined {\n  let data: MutableChildrenData | undefined;\n\n  // TODO: we should be able to optimize this diff away in the fast case where nothing has\n  // actually changed structurally.\n  const oldKeys = new Set(prevData.byPropertyKey.keys());\n  const oldTracking = new Set(prevData.byTrackingKey?.keys());\n\n  for (let i = 0; i < value.length; i++) {\n    const childValue = value[i];\n    oldKeys.delete(i.toString());\n    if (isObject(childValue) && childValue.hasOwnProperty(identitySymbol)) {\n      oldTracking.delete(childValue[identitySymbol] as TrackingKey);\n    }\n  }\n\n  // `oldKeys` and `oldTracking` now contain stale keys and tracking keys, respectively.\n  // Remove them from their corresponding maps.\n\n  if (oldKeys.size > 0) {\n    data ??= {...(prevData as MutableChildrenData)};\n    for (const key of oldKeys) {\n      data.byPropertyKey.delete(key);\n    }\n  }\n  if (oldTracking.size > 0) {\n    data ??= {...(prevData as MutableChildrenData)};\n    for (const id of oldTracking) {\n      data.byTrackingKey?.delete(id);\n    }\n  }\n\n  return data;\n}\n\nfunction maybeRemoveStaleObjectFields(\n  prevData: ChildrenData,\n  value: Record<PropertyKey, unknown>,\n): MutableChildrenData | undefined {\n  let data: MutableChildrenData | undefined;\n\n  // For objects, we diff a bit differently, and use the value to check whether an old\n  // property still exists on the object value.\n  for (const key of prevData.byPropertyKey.keys()) {\n    if (!value.hasOwnProperty(key)) {\n      data ??= {...(prevData as MutableChildrenData)};\n      data.byPropertyKey.delete(key);\n    }\n  }\n\n  return data;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {computed, linkedSignal, Signal, signal, WritableSignal} from '@angular/core';\nimport {ValidationError} from '../api/rules/validation/validation_errors';\nimport type {FieldNode} from './node';\n\n/**\n * State of a `FieldNode` that's associated with form submission.\n */\nexport class FieldSubmitState {\n  /**\n   * Whether this field was directly submitted (as opposed to indirectly by a parent field being submitted)\n   * and is still in the process of submitting.\n   */\n  readonly selfSubmitting = signal<boolean>(false);\n\n  /** Submission errors that are associated with this field. */\n  readonly submissionErrors: WritableSignal<readonly ValidationError.WithFieldTree[]>;\n\n  constructor(private readonly node: FieldNode) {\n    this.submissionErrors = linkedSignal({\n      source: this.node.structure.value,\n      computation: () => [] as readonly ValidationError.WithFieldTree[],\n    });\n  }\n\n  /**\n   * Whether this form is currently in the process of being submitted.\n   * Either because the field was submitted directly, or because a parent field was submitted.\n   */\n  readonly submitting: Signal<boolean> = computed(() => {\n    return this.selfSubmitting() || (this.node.structure.parent?.submitting() ?? false);\n  });\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {computed, linkedSignal, type Signal, untracked, type WritableSignal} from '@angular/core';\nimport {\n  MAX,\n  MAX_LENGTH,\n  type MetadataKey,\n  MIN,\n  MIN_LENGTH,\n  PATTERN,\n  REQUIRED,\n} from '../api/rules/metadata';\nimport type {ValidationError} from '../api/rules/validation/validation_errors';\nimport type {DisabledReason, FieldContext, FieldState, FieldTree} from '../api/types';\nimport type {FormField} from '../directive/form_field_directive';\nimport {DYNAMIC} from '../schema/logic';\nimport {LogicNode} from '../schema/logic_node';\nimport {FieldPathNode} from '../schema/path_node';\nimport {FieldNodeContext} from './context';\nimport type {FieldAdapter} from './field_adapter';\nimport type {FormFieldManager} from './manager';\nimport {FieldMetadataState} from './metadata';\nimport {FIELD_PROXY_HANDLER} from './proxy';\nimport {FieldNodeState} from './state';\nimport {\n  ChildFieldNodeStructure,\n  type FieldNodeOptions,\n  type FieldNodeStructure,\n  RootFieldNodeStructure,\n  type TrackingKey,\n} from './structure';\nimport {FieldSubmitState} from './submit';\nimport {ValidationState} from './validation';\n\n/**\n * Internal node in the form tree for a given field.\n *\n * Field nodes have several responsibilities:\n *  - They track instance state for the particular field (touched)\n *  - They compute signals for derived state (valid, disabled, etc) based on their associated\n *    `LogicNode`\n *  - They act as the public API for the field (they implement the `FieldState` interface)\n *  - They implement navigation of the form tree via `.parent` and `.getChild()`.\n *\n * This class is largely a wrapper that aggregates several smaller pieces that each manage a subset of\n * the responsibilities.\n */\nexport class FieldNode implements FieldState<unknown> {\n  readonly structure: FieldNodeStructure;\n  readonly validationState: ValidationState;\n  readonly metadataState: FieldMetadataState;\n  readonly nodeState: FieldNodeState;\n  readonly submitState: FieldSubmitState;\n  readonly fieldAdapter: FieldAdapter;\n  readonly controlValue: WritableSignal<unknown>;\n\n  private _context: FieldContext<unknown> | undefined = undefined;\n  get context(): FieldContext<unknown> {\n    return (this._context ??= new FieldNodeContext(this));\n  }\n\n  /**\n   * Proxy to this node which allows navigation of the form graph below it.\n   */\n  readonly fieldProxy = new Proxy(() => this, FIELD_PROXY_HANDLER) as unknown as FieldTree<any>;\n  private readonly pathNode: FieldPathNode;\n\n  constructor(options: FieldNodeOptions) {\n    this.pathNode = options.pathNode;\n    this.fieldAdapter = options.fieldAdapter;\n    this.structure = this.fieldAdapter.createStructure(this, options);\n    this.validationState = this.fieldAdapter.createValidationState(this, options);\n    this.nodeState = this.fieldAdapter.createNodeState(this, options);\n    this.metadataState = new FieldMetadataState(this);\n    this.submitState = new FieldSubmitState(this);\n    this.controlValue = this.controlValueSignal();\n  }\n\n  focusBoundControl(options?: FocusOptions): void {\n    this.getBindingForFocus()?.focus(options);\n  }\n\n  /**\n   * Gets the Field directive binding that should be focused when the developer calls\n   * `focusBoundControl` on this node.\n   *\n   * This will prioritize focusable bindings to this node, and if multiple exist, it will return\n   * the first one in the DOM. If no focusable bindings exist on this node, it will return the\n   * first focusable binding in the DOM for any descendant node of this one.\n   */\n  private getBindingForFocus():\n    | (FormField<unknown> & {focus: (options?: FocusOptions) => void})\n    | undefined {\n    // First try to focus one of our own bindings.\n    const own = this.formFieldBindings()\n      .filter(\n        (b): b is FormField<unknown> & {focus: (options?: FocusOptions) => void} =>\n          b.focus !== undefined,\n      )\n      .reduce(\n        firstInDom<FormField<unknown> & {focus: (options?: FocusOptions) => void}>,\n        undefined,\n      );\n    if (own) return own;\n    // Fallback to focusing the bound control for one of our children.\n    return this.structure\n      .children()\n      .map((child) => child.getBindingForFocus())\n      .reduce(firstInDom, undefined);\n  }\n\n  /**\n   * The `AbortController` for the currently debounced sync, or `undefined` if there is none.\n   *\n   * This is used to cancel a pending debounced sync when {@link setControlValue} is called again\n   * before the pending debounced sync resolves. It will also cancel any pending debounced sync\n   * automatically when recomputed due to `value` being set directly from others sources.\n   */\n  private readonly pendingSync: WritableSignal<AbortController | undefined> = linkedSignal({\n    source: () => this.value(),\n    computation: (_source, previous) => {\n      previous?.value?.abort();\n      return undefined;\n    },\n  });\n\n  get fieldTree(): FieldTree<unknown> {\n    return this.fieldProxy;\n  }\n\n  get logicNode(): LogicNode {\n    return this.structure.logic;\n  }\n\n  get value(): WritableSignal<unknown> {\n    return this.structure.value;\n  }\n\n  get keyInParent(): Signal<string | number> {\n    return this.structure.keyInParent;\n  }\n\n  get errors(): Signal<ValidationError.WithFieldTree[]> {\n    return this.validationState.errors;\n  }\n\n  get parseErrors(): Signal<ValidationError.WithFormField[]> {\n    return this.validationState.parseErrors;\n  }\n\n  get errorSummary(): Signal<ValidationError.WithFieldTree[]> {\n    return this.validationState.errorSummary;\n  }\n\n  get pending(): Signal<boolean> {\n    return this.validationState.pending;\n  }\n\n  get valid(): Signal<boolean> {\n    return this.validationState.valid;\n  }\n\n  get invalid(): Signal<boolean> {\n    return this.validationState.invalid;\n  }\n\n  get dirty(): Signal<boolean> {\n    return this.nodeState.dirty;\n  }\n\n  get touched(): Signal<boolean> {\n    return this.nodeState.touched;\n  }\n\n  get disabled(): Signal<boolean> {\n    return this.nodeState.disabled;\n  }\n\n  get disabledReasons(): Signal<readonly DisabledReason[]> {\n    return this.nodeState.disabledReasons;\n  }\n\n  get hidden(): Signal<boolean> {\n    return this.nodeState.hidden;\n  }\n\n  get readonly(): Signal<boolean> {\n    return this.nodeState.readonly;\n  }\n\n  get formFieldBindings(): Signal<readonly FormField<unknown>[]> {\n    return this.nodeState.formFieldBindings;\n  }\n\n  get submitting(): Signal<boolean> {\n    return this.submitState.submitting;\n  }\n\n  get name(): Signal<string> {\n    return this.nodeState.name;\n  }\n\n  get max(): Signal<number | undefined> | undefined {\n    return this.metadata(MAX);\n  }\n\n  get maxLength(): Signal<number | undefined> | undefined {\n    return this.metadata(MAX_LENGTH);\n  }\n\n  get min(): Signal<number | undefined> | undefined {\n    return this.metadata(MIN);\n  }\n\n  get minLength(): Signal<number | undefined> | undefined {\n    return this.metadata(MIN_LENGTH);\n  }\n\n  get pattern(): Signal<readonly RegExp[]> {\n    return this.metadata(PATTERN) ?? EMPTY;\n  }\n\n  get required(): Signal<boolean> {\n    return this.metadata(REQUIRED) ?? FALSE;\n  }\n\n  metadata<M>(key: MetadataKey<M, any, any>): M | undefined {\n    return this.metadataState.get(key);\n  }\n\n  hasMetadata(key: MetadataKey<any, any, any>): boolean {\n    return this.metadataState.has(key);\n  }\n\n  /**\n   * Marks this specific field as touched.\n   */\n  markAsTouched(): void {\n    untracked(() => {\n      this.nodeState.markAsTouched();\n      this.flushSync();\n    });\n  }\n\n  /**\n   * Marks this specific field as dirty.\n   */\n  markAsDirty(): void {\n    this.nodeState.markAsDirty();\n  }\n\n  /**\n   * Marks this specific field as pristine.\n   */\n  markAsPristine(): void {\n    this.nodeState.markAsPristine();\n  }\n\n  /**\n   * Marks this specific field as untouched.\n   */\n  markAsUntouched(): void {\n    this.nodeState.markAsUntouched();\n  }\n\n  /**\n   * Resets the {@link touched} and {@link dirty} state of the field and its descendants.\n   *\n   * Note this does not change the data model, which can be reset directly if desired.\n   *\n   * @param value Optional value to set to the form. If not passed, the value will not be changed.\n   */\n  reset(value?: unknown): void {\n    untracked(() => this._reset(value));\n  }\n\n  private _reset(value?: unknown) {\n    if (value !== undefined) {\n      this.value.set(value);\n    }\n\n    this.nodeState.markAsUntouched();\n    this.nodeState.markAsPristine();\n\n    for (const child of this.structure.children()) {\n      child._reset();\n    }\n  }\n\n  /**\n   * Creates a linked signal that initiates a {@link debounceSync} when set.\n   */\n  private controlValueSignal(): WritableSignal<unknown> {\n    const controlValue = linkedSignal(this.value);\n    const {set, update} = controlValue;\n\n    controlValue.set = (newValue) => {\n      set(newValue);\n      this.markAsDirty();\n      this.debounceSync();\n    };\n    controlValue.update = (updateFn) => {\n      update(updateFn);\n      this.markAsDirty();\n      this.debounceSync();\n    };\n\n    return controlValue;\n  }\n\n  /**\n   * Synchronizes the {@link controlValue} with the {@link value} signal immediately.\n   */\n  private sync() {\n    this.value.set(this.controlValue());\n  }\n\n  /**\n   * If there is a pending sync, abort it and sync immediately.\n   */\n  private flushSync() {\n    const pending = this.pendingSync();\n    if (pending && !pending.signal.aborted) {\n      pending.abort();\n      this.sync();\n    }\n  }\n\n  /**\n   * Initiates a debounced {@link sync}.\n   *\n   * If a debouncer is configured, the synchronization will occur after the debouncer resolves. If\n   * no debouncer is configured, the synchronization happens immediately. If {@link controlValue} is\n   * updated again while a debounce is pending, the previous debounce operation is aborted in favor\n   * of the new one.\n   */\n  private async debounceSync() {\n    const debouncer = untracked(() => {\n      this.pendingSync()?.abort();\n      return this.nodeState.debouncer();\n    });\n\n    if (debouncer) {\n      const controller = new AbortController();\n      const promise = debouncer(controller.signal);\n      if (promise) {\n        this.pendingSync.set(controller);\n        await promise;\n        if (controller.signal.aborted) {\n          return; // Do not sync if the debounce was aborted.\n        }\n      }\n    }\n\n    this.sync();\n  }\n\n  /**\n   * Creates a new root field node for a new form.\n   */\n  static newRoot<T>(\n    fieldManager: FormFieldManager,\n    value: WritableSignal<T>,\n    pathNode: FieldPathNode,\n    adapter: FieldAdapter,\n  ): FieldNode {\n    return adapter.newRoot(fieldManager, value, pathNode, adapter);\n  }\n\n  createStructure(options: FieldNodeOptions) {\n    return options.kind === 'root'\n      ? new RootFieldNodeStructure(\n          this,\n          options.logic,\n          options.fieldManager,\n          options.value,\n          this.newChild.bind(this),\n        )\n      : new ChildFieldNodeStructure(\n          this,\n          options.logic,\n          options.parent,\n          options.identityInParent,\n          options.initialKeyInParent,\n          this.newChild.bind(this),\n        );\n  }\n\n  private newChild(key: string, trackingId: TrackingKey | undefined, isArray: boolean): FieldNode {\n    // Determine the logic for the field that we're defining.\n    let childPath: FieldPathNode | undefined;\n    let childLogic: LogicNode;\n    if (isArray) {\n      // Fields for array elements have their logic defined by the `element` mechanism.\n      // TODO: other dynamic data\n      childPath = this.pathNode.getChild(DYNAMIC);\n      childLogic = this.structure.logic.getChild(DYNAMIC);\n    } else {\n      // Fields for plain properties exist in our logic node's child map.\n      childPath = this.pathNode.getChild(key);\n      childLogic = this.structure.logic.getChild(key);\n    }\n\n    return this.fieldAdapter.newChild({\n      kind: 'child',\n      parent: this as ParentFieldNode,\n      pathNode: childPath,\n      logic: childLogic,\n      initialKeyInParent: key,\n      identityInParent: trackingId,\n      fieldAdapter: this.fieldAdapter,\n    });\n  }\n}\n\nconst EMPTY = computed(() => []);\nconst FALSE = computed(() => false);\n\n/**\n * Field node of a field that has children.\n * This simplifies and makes certain types cleaner.\n */\nexport interface ParentFieldNode extends FieldNode {\n  readonly value: WritableSignal<Record<string, unknown>>;\n  readonly structure: FieldNodeStructure & {value: WritableSignal<Record<string, unknown>>};\n}\n\n/** Given two elements, returns the one that appears earlier in the DOM. */\nfunction firstInDom<T extends FormField<unknown>>(\n  a: T | undefined,\n  b: T | undefined,\n): T | undefined {\n  if (!a) return b;\n  if (!b) return a;\n  const position = a.element.compareDocumentPosition(b.element);\n  return position & Node.DOCUMENT_POSITION_PRECEDING ? b : a;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {computed, signal, Signal} from '@angular/core';\nimport type {FormField} from '../directive/form_field_directive';\nimport type {Debouncer, DisabledReason} from '../api/types';\nimport {DEBOUNCER} from './debounce';\nimport type {FieldNode} from './node';\nimport {shortCircuitTrue} from './util';\n\n/**\n * The non-validation and non-submit state associated with a `FieldNode`, such as touched and dirty\n * status, as well as derived logical state.\n */\nexport class FieldNodeState {\n  /**\n   * Indicates whether this field has been touched directly by the user (as opposed to indirectly by\n   * touching a child field).\n   *\n   * A field is considered directly touched when a user stops editing it for the first time (i.e. on blur)\n   */\n  private readonly selfTouched = signal(false);\n\n  /**\n   * Indicates whether this field has been dirtied directly by the user (as opposed to indirectly by\n   * dirtying a child field).\n   *\n   * A field is considered directly dirtied if a user changed the value of the field at least once.\n   */\n  private readonly selfDirty = signal(false);\n\n  /**\n   * Marks this specific field as touched.\n   */\n  markAsTouched(): void {\n    this.selfTouched.set(true);\n  }\n\n  /**\n   * Marks this specific field as dirty.\n   */\n  markAsDirty(): void {\n    this.selfDirty.set(true);\n  }\n\n  /**\n   * Marks this specific field as not dirty.\n   */\n  markAsPristine(): void {\n    this.selfDirty.set(false);\n  }\n\n  /**\n   * Marks this specific field as not touched.\n   */\n  markAsUntouched(): void {\n    this.selfTouched.set(false);\n  }\n\n  /** The {@link FormField} directives that bind this field to a UI control. */\n  readonly formFieldBindings = signal<readonly FormField<unknown>[]>([]);\n\n  constructor(private readonly node: FieldNode) {}\n\n  /**\n   * Whether this field is considered dirty.\n   *\n   * A field is considered dirty if one of the following is true:\n   *  - It was directly dirtied and is interactive\n   *  - One of its children is considered dirty\n   */\n  readonly dirty: Signal<boolean> = computed(() => {\n    const selfDirtyValue = this.selfDirty() && !this.isNonInteractive();\n    return this.node.structure.reduceChildren(\n      selfDirtyValue,\n      (child, value) => value || child.nodeState.dirty(),\n      shortCircuitTrue,\n    );\n  });\n\n  /**\n   * Whether this field is considered touched.\n   *\n   * A field is considered touched if one of the following is true:\n   *  - It was directly touched and is interactive\n   *  - One of its children is considered touched\n   */\n  readonly touched: Signal<boolean> = computed(() => {\n    const selfTouchedValue = this.selfTouched() && !this.isNonInteractive();\n    return this.node.structure.reduceChildren(\n      selfTouchedValue,\n      (child, value) => value || child.nodeState.touched(),\n      shortCircuitTrue,\n    );\n  });\n\n  /**\n   * The reasons for this field's disablement. This includes disabled reasons for any parent field\n   * that may have been disabled, indirectly causing this field to be disabled as well.\n   * The `field` property of the `DisabledReason` can be used to determine which field ultimately\n   * caused the disablement.\n   */\n  readonly disabledReasons: Signal<readonly DisabledReason[]> = computed(() => [\n    ...(this.node.structure.parent?.nodeState.disabledReasons() ?? []),\n    ...this.node.logicNode.logic.disabledReasons.compute(this.node.context),\n  ]);\n\n  /**\n   * Whether this field is considered disabled.\n   *\n   * A field is considered disabled if one of the following is true:\n   * - The schema contains logic that directly disabled it\n   * - Its parent field is considered disabled\n   */\n  readonly disabled: Signal<boolean> = computed(() => !!this.disabledReasons().length);\n\n  /**\n   * Whether this field is considered readonly.\n   *\n   * A field is considered readonly if one of the following is true:\n   * - The schema contains logic that directly made it readonly\n   * - Its parent field is considered readonly\n   */\n  readonly readonly: Signal<boolean> = computed(\n    () =>\n      (this.node.structure.parent?.nodeState.readonly() ||\n        this.node.logicNode.logic.readonly.compute(this.node.context)) ??\n      false,\n  );\n\n  /**\n   * Whether this field is considered hidden.\n   *\n   * A field is considered hidden if one of the following is true:\n   * - The schema contains logic that directly hides it\n   * - Its parent field is considered hidden\n   */\n  readonly hidden: Signal<boolean> = computed(\n    () =>\n      (this.node.structure.parent?.nodeState.hidden() ||\n        this.node.logicNode.logic.hidden.compute(this.node.context)) ??\n      false,\n  );\n\n  readonly name: Signal<string> = computed(() => {\n    const parent = this.node.structure.parent;\n    if (!parent) {\n      return this.node.structure.fieldManager.rootName;\n    }\n\n    return `${parent.name()}.${this.node.structure.keyInParent()}`;\n  });\n\n  /**\n   * An optional {@link Debouncer} factory for this field.\n   */\n  readonly debouncer: Signal<((signal: AbortSignal) => Promise<void> | void) | undefined> =\n    computed(() => {\n      if (this.node.logicNode.logic.hasMetadata(DEBOUNCER)) {\n        const debouncerLogic = this.node.logicNode.logic.getMetadata(DEBOUNCER);\n        const debouncer = debouncerLogic.compute(this.node.context);\n\n        // Even if this field has a `debounce()` rule, it could be applied conditionally and currently\n        // inactive, in which case `compute()` will return undefined.\n        if (debouncer) {\n          return (signal) => debouncer(this.node.context, signal);\n        }\n      }\n\n      // Fallback to the parent's debouncer, if any. If there is no debouncer configured all the way\n      // up to the root field, this simply returns `undefined` indicating that the operation should\n      // not be debounced.\n      return this.node.structure.parent?.nodeState.debouncer?.();\n    });\n\n  /** Whether this field is considered non-interactive.\n   *\n   * A field is considered non-interactive if one of the following is true:\n   * - It is hidden\n   * - It is disabled\n   * - It is readonly\n   */\n  private readonly isNonInteractive = computed(\n    () => this.hidden() || this.disabled() || this.readonly(),\n  );\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {FieldPathNode} from '../schema/path_node';\n\nimport {WritableSignal} from '@angular/core';\nimport {FormFieldManager} from './manager';\nimport {FieldNode} from './node';\nimport {FieldNodeState} from './state';\nimport {ChildFieldNodeOptions, FieldNodeOptions, FieldNodeStructure} from './structure';\nimport {FieldValidationState, ValidationState} from './validation';\n\n/**\n * Adapter allowing customization of the creation logic for a field and its associated\n * structure and state.\n */\nexport interface FieldAdapter {\n  /**\n   * Creates a node structure.\n   * @param node\n   * @param options\n   */\n  createStructure(node: FieldNode, options: FieldNodeOptions): FieldNodeStructure;\n\n  /**\n   * Creates node validation state\n   * @param param\n   * @param options\n   */\n  createValidationState(param: FieldNode, options: FieldNodeOptions): ValidationState;\n\n  /**\n   * Creates node state.\n   * @param param\n   * @param options\n   */\n  createNodeState(param: FieldNode, options: FieldNodeOptions): FieldNodeState;\n\n  /**\n   * Creates a custom child node.\n   * @param options\n   */\n  newChild(options: ChildFieldNodeOptions): FieldNode;\n\n  /**\n   * Creates a custom root node.\n   * @param fieldManager\n   * @param model\n   * @param pathNode\n   * @param adapter\n   */\n  newRoot<TValue>(\n    fieldManager: FormFieldManager,\n    model: WritableSignal<TValue>,\n    pathNode: FieldPathNode,\n    adapter: FieldAdapter,\n  ): FieldNode;\n}\n\n/**\n * Basic adapter supporting standard form behavior.\n */\nexport class BasicFieldAdapter implements FieldAdapter {\n  /**\n   * Creates a new Root field node.\n   * @param fieldManager\n   * @param value\n   * @param pathNode\n   * @param adapter\n   */\n  newRoot<TValue>(\n    fieldManager: FormFieldManager,\n    value: WritableSignal<TValue>,\n    pathNode: FieldPathNode,\n    adapter: FieldAdapter,\n  ): FieldNode {\n    return new FieldNode({\n      kind: 'root',\n      fieldManager,\n      value,\n      pathNode,\n      logic: pathNode.builder.build(),\n      fieldAdapter: adapter,\n    });\n  }\n\n  /**\n   * Creates a new child field node.\n   * @param options\n   */\n  newChild(options: ChildFieldNodeOptions): FieldNode {\n    return new FieldNode(options);\n  }\n\n  /**\n   * Creates a node state.\n   * @param node\n   */\n  createNodeState(node: FieldNode): FieldNodeState {\n    return new FieldNodeState(node);\n  }\n\n  /**\n   * Creates a validation state.\n   * @param node\n   */\n  createValidationState(node: FieldNode): ValidationState {\n    return new FieldValidationState(node);\n  }\n\n  /**\n   * Creates a node structure.\n   * @param node\n   * @param options\n   */\n  createStructure(node: FieldNode, options: FieldNodeOptions): FieldNodeStructure {\n    return node.createStructure(options);\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {APP_ID, effect, Injector, untracked} from '@angular/core';\nimport type {FormSubmitOptions} from '../api/types';\nimport type {FieldNodeStructure} from './structure';\n\n/**\n * Manages the collection of fields associated with a given `form`.\n *\n * Fields are created implicitly, through reactivity, and may create \"owned\" entities like effects\n * or resources. When a field is no longer connected to the form, these owned entities should be\n * destroyed, which is the job of the `FormFieldManager`.\n */\nexport class FormFieldManager {\n  readonly injector: Injector;\n  readonly rootName: string;\n  readonly submitOptions: FormSubmitOptions<unknown, unknown> | undefined;\n\n  constructor(\n    injector: Injector,\n    rootName: string | undefined,\n    submitOptions: FormSubmitOptions<unknown, unknown> | undefined,\n  ) {\n    this.injector = injector;\n    this.rootName = rootName ?? `${this.injector.get(APP_ID)}.form${nextFormId++}`;\n    this.submitOptions = submitOptions;\n  }\n\n  /**\n   * Contains all child field structures that have been created as part of the current form.\n   * New child structures are automatically added when they are created.\n   * Structures are destroyed and removed when they are no longer reachable from the root.\n   */\n  readonly structures = new Set<FieldNodeStructure>();\n\n  /**\n   * Creates an effect that runs when the form's structure changes and checks for structures that\n   * have become unreachable to clean up.\n   *\n   * For example, consider a form wrapped around the following model: `signal([0, 1, 2])`.\n   * This form would have 4 nodes as part of its structure tree.\n   * One structure for the root array, and one structure for each element of the array.\n   * Now imagine the data is updated: `model.set([0])`. In this case the structure for the first\n   * element can still be reached from the root, but the structures for the second and third\n   * elements are now orphaned and not connected to the root. Thus they will be destroyed.\n   *\n   * @param root The root field structure.\n   */\n  createFieldManagementEffect(root: FieldNodeStructure): void {\n    effect(\n      () => {\n        const liveStructures = new Set<FieldNodeStructure>();\n        this.markStructuresLive(root, liveStructures);\n\n        // Destroy all nodes that are no longer live.\n        for (const structure of this.structures) {\n          if (!liveStructures.has(structure)) {\n            this.structures.delete(structure);\n            untracked(() => structure.destroy());\n          }\n        }\n      },\n      {injector: this.injector},\n    );\n  }\n\n  /**\n   * Collects all structures reachable from the given structure into the given set.\n   *\n   * @param structure The root structure\n   * @param liveStructures The set of reachable structures to populate\n   */\n  private markStructuresLive(\n    structure: FieldNodeStructure,\n    liveStructures: Set<FieldNodeStructure>,\n  ): void {\n    liveStructures.add(structure);\n    for (const child of structure.children()) {\n      this.markStructuresLive(child.structure, liveStructures);\n    }\n  }\n}\n\nlet nextFormId = 0;\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport type {WritableSignal} from '@angular/core';\nimport type {FormOptions} from '../api/structure';\nimport type {SchemaOrSchemaFn} from '../api/types';\nimport {FieldAdapter} from '../field/field_adapter';\nimport {isSchemaOrSchemaFn} from '../schema/schema';\n\n/**\n * Extracts the model, schema, and options from the arguments passed to `form()`.\n */\nexport function normalizeFormArgs<TModel>(\n  args: any[],\n): [\n  WritableSignal<TModel>,\n  SchemaOrSchemaFn<TModel> | undefined,\n  (FormOptions<TModel> & {adapter?: FieldAdapter}) | undefined,\n] {\n  let model: WritableSignal<TModel>;\n  let schema: SchemaOrSchemaFn<TModel> | undefined;\n  let options: (FormOptions<TModel> & {adapter?: FieldAdapter}) | undefined;\n\n  if (args.length === 3) {\n    [model, schema, options] = args;\n  } else if (args.length === 2) {\n    if (isSchemaOrSchemaFn(args[1])) {\n      [model, schema] = args;\n    } else {\n      [model, options] = args;\n    }\n  } else {\n    [model] = args;\n  }\n\n  return [model, schema, options];\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {\n  inject,\n  Injector,\n  runInInjectionContext,\n  ɵRuntimeError as RuntimeError,\n  untracked,\n  WritableSignal,\n} from '@angular/core';\nimport {RuntimeErrorCode} from '../errors';\nimport {BasicFieldAdapter, FieldAdapter} from '../field/field_adapter';\nimport {FormFieldManager} from '../field/manager';\nimport {FieldNode} from '../field/node';\nimport {addDefaultField} from '../field/validation';\nimport {DYNAMIC} from '../schema/logic';\nimport {FieldPathNode} from '../schema/path_node';\nimport {assertPathIsCurrent, SchemaImpl} from '../schema/schema';\nimport {normalizeFormArgs} from '../util/normalize_form_args';\nimport {isArray} from '../util/type_guards';\nimport type {ValidationError} from './rules';\nimport type {\n  FieldState,\n  FieldTree,\n  FormSubmitOptions,\n  ItemType,\n  LogicFn,\n  OneOrMany,\n  PathKind,\n  Schema,\n  SchemaFn,\n  SchemaOrSchemaFn,\n  SchemaPath,\n} from './types';\n\n/**\n * Options that may be specified when creating a form.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport interface FormOptions<TModel> {\n  /**\n   * The injector to use for dependency injection. If this is not provided, the injector for the\n   * current [injection context](guide/di/dependency-injection-context), will be used.\n   */\n  injector?: Injector;\n  /** The name of the root form, used in generating name attributes for the fields. */\n  name?: string;\n  /** Options that define how to handle form submission. */\n  submission?: FormSubmitOptions<TModel, unknown>;\n}\n\n/**\n * Creates a form wrapped around the given model data. A form is represented as simply a `FieldTree`\n * of the model data.\n *\n * `form` uses the given model as the source of truth and *does not* maintain its own copy of the\n * data. This means that updating the value on a `FieldState` updates the originally passed in model\n * as well.\n *\n * @example\n * ```ts\n * const nameModel = signal({first: '', last: ''});\n * const nameForm = form(nameModel);\n * nameForm.first().value.set('John');\n * nameForm().value(); // {first: 'John', last: ''}\n * nameModel(); // {first: 'John', last: ''}\n * ```\n *\n * @param model A writable signal that contains the model data for the form. The resulting field\n * structure will match the shape of the model and any changes to the form data will be written to\n * the model.\n * @return A `FieldTree` representing a form around the data model.\n * @template TModel The type of the data model.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function form<TModel>(model: WritableSignal<TModel>): FieldTree<TModel>;\n\n/**\n * Creates a form wrapped around the given model data. A form is represented as simply a `FieldTree`\n * of the model data.\n *\n * `form` uses the given model as the source of truth and *does not* maintain its own copy of the\n * data. This means that updating the value on a `FieldState` updates the originally passed in model\n * as well.\n *\n * @example\n * ```ts\n * const nameModel = signal({first: '', last: ''});\n * const nameForm = form(nameModel);\n * nameForm.first().value.set('John');\n * nameForm().value(); // {first: 'John', last: ''}\n * nameModel(); // {first: 'John', last: ''}\n * ```\n *\n * The form can also be created with a schema, which is a set of rules that define the logic for the\n * form. The schema can be either a pre-defined schema created with the `schema` function, or a\n * function that builds the schema by binding logic to a parts of the field structure.\n *\n * @example\n * ```ts\n * const nameForm = form(signal({first: '', last: ''}), (name) => {\n *   required(name.first);\n *   pattern(name.last, /^[a-z]+$/i, {message: 'Alphabet characters only'});\n * });\n * nameForm().valid(); // false\n * nameForm().value.set({first: 'John', last: 'Doe'});\n * nameForm().valid(); // true\n * ```\n *\n * @param model A writable signal that contains the model data for the form. The resulting field\n * structure will match the shape of the model and any changes to the form data will be written to\n * the model.\n * @param schemaOrOptions The second argument can be either\n *   1. A schema or a function used to specify logic for the form (e.g. validation, disabled fields, etc.).\n *      When passing a schema, the form options can be passed as a third argument if needed.\n *   2. The form options\n * @return A `FieldTree` representing a form around the data model\n * @template TValue The type of the data model.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function form<TModel>(\n  model: WritableSignal<TModel>,\n  schemaOrOptions: SchemaOrSchemaFn<TModel> | FormOptions<TModel>,\n): FieldTree<TModel>;\n\n/**\n * Creates a form wrapped around the given model data. A form is represented as simply a `FieldTree`\n * of the model data.\n *\n * `form` uses the given model as the source of truth and *does not* maintain its own copy of the\n * data. This means that updating the value on a `FieldState` updates the originally passed in model\n * as well.\n *\n * @example\n * ```ts\n * const nameModel = signal({first: '', last: ''});\n * const nameForm = form(nameModel);\n * nameForm.first().value.set('John');\n * nameForm().value(); // {first: 'John', last: ''}\n * nameModel(); // {first: 'John', last: ''}\n * ```\n *\n * The form can also be created with a schema, which is a set of rules that define the logic for the\n * form. The schema can be either a pre-defined schema created with the `schema` function, or a\n * function that builds the schema by binding logic to a parts of the field structure.\n *\n * @example\n * ```ts\n * const nameForm = form(signal({first: '', last: ''}), (name) => {\n *   required(name.first);\n *   validate(name.last, ({value}) => !/^[a-z]+$/i.test(value()) ? {kind: 'alphabet-only'} : undefined);\n * });\n * nameForm().valid(); // false\n * nameForm().value.set({first: 'John', last: 'Doe'});\n * nameForm().valid(); // true\n * ```\n *\n * @param model A writable signal that contains the model data for the form. The resulting field\n * structure will match the shape of the model and any changes to the form data will be written to\n * the model.\n * @param schema A schema or a function used to specify logic for the form (e.g. validation, disabled fields, etc.)\n * @param options The form options\n * @return A `FieldTree` representing a form around the data model.\n * @template TModel The type of the data model.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function form<TModel>(\n  model: WritableSignal<TModel>,\n  schema: SchemaOrSchemaFn<TModel>,\n  options: FormOptions<TModel>,\n): FieldTree<TModel>;\n\nexport function form<TModel>(...args: any[]): FieldTree<TModel> {\n  const [model, schema, options] = normalizeFormArgs<TModel>(args);\n  const injector = options?.injector ?? inject(Injector);\n  const pathNode = runInInjectionContext(injector, () => SchemaImpl.rootCompile(schema));\n  const fieldManager = new FormFieldManager(\n    injector,\n    options?.name,\n    options?.submission as FormSubmitOptions<unknown, unknown> | undefined,\n  );\n  const adapter = options?.adapter ?? new BasicFieldAdapter();\n  const fieldRoot = FieldNode.newRoot(fieldManager, model, pathNode, adapter);\n  fieldManager.createFieldManagementEffect(fieldRoot.structure);\n\n  return fieldRoot.fieldTree as FieldTree<TModel>;\n}\n\n/**\n * Applies a schema to each item of an array.\n *\n * @example\n * ```ts\n * const nameSchema = schema<{first: string, last: string}>((name) => {\n *   required(name.first);\n *   required(name.last);\n * });\n * const namesForm = form(signal([{first: '', last: ''}]), (names) => {\n *   applyEach(names, nameSchema);\n * });\n * ```\n *\n * @param path The target path for an array field whose items the schema will be applied to.\n * @param schema A schema for an element of the array, or function that binds logic to an\n * element of the array.\n * @template TValue The data type of the item field to apply the schema to.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function applyEach<TValue extends ReadonlyArray<any>>(\n  path: SchemaPath<TValue>,\n  schema: NoInfer<SchemaOrSchemaFn<TValue[number], PathKind.Item>>,\n): void;\nexport function applyEach<TValue extends Object>(\n  path: SchemaPath<TValue>,\n  schema: NoInfer<SchemaOrSchemaFn<ItemType<TValue>, PathKind.Child>>,\n): void;\nexport function applyEach<TValue extends Object>(\n  path: SchemaPath<TValue>,\n  schema: NoInfer<SchemaOrSchemaFn<ItemType<TValue>, PathKind.Item>>,\n): void {\n  assertPathIsCurrent(path);\n\n  const elementPath = FieldPathNode.unwrapFieldPath(path).getChild(DYNAMIC).fieldPathProxy;\n  apply(elementPath, schema as Schema<TValue>);\n}\n\n/**\n * Applies a predefined schema to a given `FieldPath`.\n *\n * @example\n * ```ts\n * const nameSchema = schema<{first: string, last: string}>((name) => {\n *   required(name.first);\n *   required(name.last);\n * });\n * const profileForm = form(signal({name: {first: '', last: ''}, age: 0}), (profile) => {\n *   apply(profile.name, nameSchema);\n * });\n * ```\n *\n * @param path The target path to apply the schema to.\n * @param schema The schema to apply to the property\n * @template TValue The data type of the field to apply the schema to.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function apply<TValue>(\n  path: SchemaPath<TValue>,\n  schema: NoInfer<SchemaOrSchemaFn<TValue>>,\n): void {\n  assertPathIsCurrent(path);\n\n  const pathNode = FieldPathNode.unwrapFieldPath(path);\n  pathNode.mergeIn(SchemaImpl.create(schema));\n}\n\n/**\n * Conditionally applies a predefined schema to a given `FieldPath`.\n *\n * @param path The target path to apply the schema to.\n * @param logic A `LogicFn<T, boolean>` that returns `true` when the schema should be applied.\n * @param schema The schema to apply to the field when the `logic` function returns `true`.\n * @template TValue The data type of the field to apply the schema to.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function applyWhen<TValue>(\n  path: SchemaPath<TValue>,\n  logic: LogicFn<TValue, boolean>,\n  schema: NoInfer<SchemaOrSchemaFn<TValue>>,\n): void {\n  assertPathIsCurrent(path);\n\n  const pathNode = FieldPathNode.unwrapFieldPath(path);\n  pathNode.mergeIn(SchemaImpl.create(schema), {fn: logic, path});\n}\n\n/**\n * Conditionally applies a predefined schema to a given `FieldPath`.\n *\n * @param path The target path to apply the schema to.\n * @param predicate A type guard that accepts a value `T` and returns `true` if `T` is of type\n *   `TNarrowed`.\n * @param schema The schema to apply to the field when `predicate` returns `true`.\n * @template TValue The data type of the field to apply the schema to.\n * @template TNarrowed The data type of the schema (a narrowed type of TValue).\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function applyWhenValue<TValue, TNarrowed extends TValue>(\n  path: SchemaPath<TValue>,\n  predicate: (value: TValue) => value is TNarrowed,\n  schema: SchemaOrSchemaFn<TNarrowed>,\n): void;\n\n/**\n * Conditionally applies a predefined schema to a given `FieldPath`.\n *\n * @param path The target path to apply the schema to.\n * @param predicate A function that accepts a value `T` and returns `true` when the schema\n *   should be applied.\n * @param schema The schema to apply to the field when `predicate` returns `true`.\n * @template TValue The data type of the field to apply the schema to.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function applyWhenValue<TValue>(\n  path: SchemaPath<TValue>,\n  predicate: (value: TValue) => boolean,\n  schema: NoInfer<SchemaOrSchemaFn<TValue>>,\n): void;\n\nexport function applyWhenValue(\n  path: SchemaPath<unknown>,\n  predicate: (value: unknown) => boolean,\n  schema: SchemaOrSchemaFn<unknown>,\n) {\n  applyWhen(path, ({value}) => predicate(value()), schema);\n}\n\n/**\n * Submits a given `FieldTree` using the given action function and applies any submission errors\n * resulting from the action to the field. Submission errors returned by the `action` will be integrated\n * into the field as a `ValidationError` on the sub-field indicated by the `fieldTree` property of the\n * submission error.\n *\n * @example\n * ```ts\n * async function registerNewUser(registrationForm: FieldTree<{username: string, password: string}>) {\n *   const result = await myClient.registerNewUser(registrationForm().value());\n *   if (result.errorCode === myClient.ErrorCode.USERNAME_TAKEN) {\n *     return [{\n *       fieldTree: registrationForm.username,\n *       kind: 'server',\n *       message: 'Username already taken'\n *     }];\n *   }\n *   return undefined;\n * }\n *\n * const registrationForm = form(signal({username: 'god', password: ''}));\n * submit(registrationForm, {\n *   action: async (f) => {\n *     return registerNewUser(registrationForm);\n *   }\n * });\n * registrationForm.username().errors(); // [{kind: 'server', message: 'Username already taken'}]\n * ```\n *\n * @param form The field to submit.\n * @param options Options for the submission.\n * @returns Whether the submission was successful.\n * @template TModel The data type of the field being submitted.\n *\n * @category submission\n * @experimental 21.0.0\n */\nexport async function submit<TModel>(\n  form: FieldTree<TModel>,\n  options?: NoInfer<FormSubmitOptions<unknown, TModel>>,\n): Promise<boolean>;\nexport async function submit<TModel>(\n  form: FieldTree<TModel>,\n  action: NoInfer<FormSubmitOptions<unknown, TModel>['action']>,\n): Promise<boolean>;\nexport async function submit<TModel>(\n  form: FieldTree<TModel>,\n  options?: FormSubmitOptions<unknown, TModel> | FormSubmitOptions<unknown, TModel>['action'],\n): Promise<boolean> {\n  const node = untracked(form) as FieldState<unknown> as FieldNode;\n\n  const field = options === undefined ? node.structure.root.fieldProxy : form;\n  const detail = {root: node.structure.root.fieldProxy, submitted: form};\n\n  // Normalize options.\n  options =\n    typeof options === 'function'\n      ? {action: options}\n      : (options ?? node.structure.fieldManager.submitOptions);\n\n  // Verify that an action was provided.\n  const action = options?.action as FormSubmitOptions<unknown, unknown>['action'];\n  if (!action) {\n    throw new RuntimeError(\n      RuntimeErrorCode.MISSING_SUBMIT_ACTION,\n      (typeof ngDevMode === 'undefined' || ngDevMode) &&\n        'Cannot submit form with no submit action. Specify the action when creating the form, or as an additional argument to `submit()`.',\n    );\n  }\n\n  const onInvalid = options?.onInvalid as FormSubmitOptions<unknown, unknown>['onInvalid'];\n  const ignoreValidators = options?.ignoreValidators ?? 'pending';\n\n  // Determine whether or not to run the action based on the current validity.\n  let shouldRunAction = true;\n  untracked(() => {\n    markAllAsTouched(node);\n\n    if (ignoreValidators === 'none') {\n      shouldRunAction = node.valid();\n    } else if (ignoreValidators === 'pending') {\n      shouldRunAction = !node.invalid();\n    }\n  });\n\n  // Run the action (or alternatively the `onInvalid` callback)\n  try {\n    if (shouldRunAction) {\n      node.submitState.selfSubmitting.set(true);\n      const errors = await untracked(() => action?.(field, detail));\n      errors && setSubmissionErrors(node, errors);\n      return !errors || (isArray(errors) && errors.length === 0);\n    } else {\n      untracked(() => onInvalid?.(field, detail));\n    }\n    return false;\n  } finally {\n    node.submitState.selfSubmitting.set(false);\n  }\n}\n\n/**\n * Creates a `Schema` that adds logic rules to a form.\n * @param fn A **non-reactive** function that sets up reactive logic rules for the form.\n * @returns A schema object that implements the given logic.\n * @template TValue The value type of a `FieldTree` that this schema binds to.\n *\n * @category structure\n * @experimental 21.0.0\n */\nexport function schema<TValue>(fn: SchemaFn<TValue>): Schema<TValue> {\n  return SchemaImpl.create(fn) as unknown as Schema<TValue>;\n}\n\n/** Marks a {@link node} and its descendants as touched. */\nfunction markAllAsTouched(node: FieldNode) {\n  // Don't mark hidden, disabled, or readonly fields as touched since they don't contribute to the\n  // form's validity. This also prevents errors from appearing immediately if they're later made\n  // interactive.\n  if (node.validationState.shouldSkipValidation()) {\n    return;\n  }\n  node.markAsTouched();\n  for (const child of node.structure.children()) {\n    markAllAsTouched(child);\n  }\n}\n\n/**\n * Sets a list of submission errors to their individual fields.\n *\n * @param submittedField The field that was submitted, resulting in the errors.\n * @param errors The errors to set.\n */\nfunction setSubmissionErrors(\n  submittedField: FieldNode,\n  errors: OneOrMany<ValidationError.WithOptionalFieldTree>,\n) {\n  if (!isArray(errors)) {\n    errors = [errors];\n  }\n  const errorsByField = new Map<FieldNode, ValidationError.WithFieldTree[]>();\n  for (const error of errors) {\n    const errorWithField = addDefaultField(error, submittedField.fieldTree);\n    const field = errorWithField.fieldTree() as FieldNode;\n    let fieldErrors = errorsByField.get(field);\n    if (!fieldErrors) {\n      fieldErrors = [];\n      errorsByField.set(field, fieldErrors);\n    }\n    fieldErrors.push(errorWithField);\n  }\n  for (const [field, fieldErrors] of errorsByField) {\n    field.submitState.submissionErrors.set(fieldErrors);\n  }\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {AbstractControl, FormArray, FormGroup, ValidationErrors} from '@angular/forms';\nimport {ValidationError} from '../api/rules';\nimport {FieldTree} from '../api/types';\n\n/**\n * An error used for compat errors.\n *\n * @experimental 21.0.0\n * @category interop\n */\nexport class CompatValidationError<T = unknown> implements ValidationError {\n  readonly kind: string = 'compat';\n  readonly control: AbstractControl;\n  readonly fieldTree!: FieldTree<unknown>;\n  readonly context: T;\n  readonly message?: string;\n\n  constructor({context, kind, control}: {context: T; kind: string; control: AbstractControl}) {\n    this.context = context;\n    this.kind = kind;\n    this.control = control;\n  }\n}\n\n/**\n * Converts signal forms validation errors to reactive forms ValidationErrors.\n *\n * @experimental 21.0.0\n */\nexport function signalErrorsToValidationErrors(errors: ValidationError[]): ValidationErrors | null {\n  if (errors.length === 0) {\n    return null;\n  }\n  const errObj: ValidationErrors = {};\n  for (const error of errors) {\n    errObj[error.kind] = error instanceof CompatValidationError ? error.context : error;\n  }\n  return errObj;\n}\n\n/**\n * Converts reactive form validation error to signal forms CompatValidationError.\n * @param errors\n * @param control\n * @return list of errors.\n */\nexport function reactiveErrorsToSignalErrors(\n  errors: ValidationErrors | null,\n  control: AbstractControl,\n): CompatValidationError[] {\n  if (errors === null) {\n    return [];\n  }\n\n  return Object.entries(errors).map(([kind, context]) => {\n    return new CompatValidationError({context, kind, control});\n  });\n}\n\n/**\n * Extracts all reactive errors from a control and its children.\n * @param control\n * @return list of errors.\n */\nexport function extractNestedReactiveErrors(control: AbstractControl): CompatValidationError[] {\n  const errors: CompatValidationError[] = [];\n\n  if (control.errors) {\n    errors.push(...reactiveErrorsToSignalErrors(control.errors, control));\n  }\n\n  if (control instanceof FormGroup || control instanceof FormArray) {\n    for (const c of Object.values(control.controls)) {\n      errors.push(...extractNestedReactiveErrors(c));\n    }\n  }\n\n  return errors;\n}\n"],"names":["boundPathDepth","getBoundPathDepth","setBoundPathDepthForResolution","fn","depth","args","shortCircuitFalse","value","shortCircuitTrue","getInjectorFromOptions","options","kind","fieldManager","injector","parent","structure","root","isArray","Array","isObject","DYNAMIC","Symbol","IGNORED","AbstractLogic","predicates","fns","constructor","push","logicFn","wrapWithPredicates","mergeIn","other","map","BooleanOrLogic","defaultValue","compute","arg","some","f","result","ArrayMergeIgnoreLogic","ignore","ignoreNull","e","reduce","prev","undefined","filter","ArrayMergeLogic","MetadataMergeLogic","key","reducer","getInitial","ctx","length","acc","i","item","predicate","predicateField","stateOf","path","depthDiff","untracked","pathKeys","context","LogicContainer","hidden","disabledReasons","readonly","syncErrors","syncTreeErrors","asyncErrors","metadata","Map","hasMetadata","has","getMetadataKeys","keys","getMetadata","set","get","metadataLogic","AbstractLogicNodeBuilder","build","LeafLogicNode","LogicNodeBuilder","current","all","addHiddenRule","logic","getCurrent","addDisabledReasonRule","addReadonlyRule","addSyncErrorRule","addSyncTreeErrorRule","addAsyncErrorRule","addMetadataRule","getChild","children","size","hasLogic","builder","subBuilder","NonMergeableLogicNodeBuilder","newRoot","createLogic","childBuilders","getAllChildBuilders","p","bindLevel","builtNodes","CompositeLogicNode","node","flatMap","child","RuntimeError","ngDevMode","PATH","FieldPathNode","keyInParent","fieldPathProxy","Proxy","FIELD_PATH_PROXY_HANDLER","logicBuilder","compile","unwrapFieldPath","formPath","property","currentCompilingNode","compiledSchemas","SchemaImpl","schemaFn","prevCompilingNode","create","schema","rootCompile","clear","isSchemaOrSchemaFn","assertPathIsCurrent","pathNode","MetadataReducer","list","min","Math","max","next","or","and","override","_","MetadataKey","brand","createMetadataKey","createManagedMetadataKey","REQUIRED","MIN","MAX","MIN_LENGTH","MAX_LENGTH","PATTERN","calculateValidationSelfStatus","state","errors","pending","FieldValidationState","rawSyncTreeErrors","computed","shouldSkipValidation","logicNode","validationState","normalizeErrors","submitState","submissionErrors","syncValid","reduceChildren","err","fieldTree","rawAsyncErrors","parseErrors","formFieldBindings","field","debugName","errorSummary","ngServerMode","sort","compareErrorPosition","includes","status","ownStatus","v","valid","invalid","disabled","error","addDefaultField","getFirstBoundElement","formField","element","el","binding","compareDocumentPosition","Node","DOCUMENT_POSITION_PRECEDING","a","b","aEl","bEl","DEBOUNCER","FieldNodeContext","cache","WeakMap","resolve","target","resolver","targetPathNode","stepsRemaining","join","fieldProxy","index","Number","fieldTreeOf","valueOf","AbstractControl","FieldMetadataState","runInInjectionContext","FIELD_PROXY_HANDLER","getTgt","receiver","tgt","iterator","prototype","apply","getOwnPropertyDescriptor","prop","desc","Reflect","configurable","ownKeys","deepSignal","source","read","SIGNAL","update","valueForWrite","asReadonly","sourceValue","newPropValue","newValue","FieldNodeStructure","createChildNode","identitySymbol","_injector","Injector","providers","childrenMap","from","byPropertyKey","values","reader","strKey","toString","createReader","initialValue","shortCircuit","destroy","createKeyInParent","identityInParent","initialKeyInParent","ROOT_KEY_IN_PARENT","getDebugName","lastKnownKey","parentValue","data","hasOwnProperty","createChildrenMap","linkedSignal","computation","previous","prevData","parentIsArray","maybeRemoveStaleArrayFields","maybeRemoveStaleObjectFields","Object","trackingKey","childValue","delete","globalId","childNode","byTrackingKey","RootFieldNodeStructure","ROOT_PATH_KEYS","ChildFieldNodeStructure","fieldAdapter","structures","add","oldKeys","Set","oldTracking","id","FieldSubmitState","selfSubmitting","signal","submitting","FieldNode","metadataState","nodeState","controlValue","_context","createStructure","createValidationState","createNodeState","controlValueSignal","focusBoundControl","getBindingForFocus","focus","own","firstInDom","pendingSync","_source","abort","dirty","touched","name","maxLength","minLength","pattern","EMPTY","required","FALSE","markAsTouched","flushSync","markAsDirty","markAsPristine","markAsUntouched","reset","_reset","debounceSync","updateFn","sync","aborted","debouncer","controller","AbortController","promise","adapter","newChild","bind","trackingId","childPath","childLogic","position","FieldNodeState","selfTouched","selfDirty","selfDirtyValue","isNonInteractive","selfTouchedValue","rootName","debouncerLogic","BasicFieldAdapter","FormFieldManager","submitOptions","APP_ID","nextFormId","createFieldManagementEffect","effect","liveStructures","markStructuresLive","normalizeFormArgs","model","form","inject","submission","fieldRoot","applyEach","elementPath","applyWhen","applyWhenValue","submit","detail","submitted","action","onInvalid","ignoreValidators","shouldRunAction","markAllAsTouched","setSubmissionErrors","submittedField","errorsByField","errorWithField","fieldErrors","CompatValidationError","control","message","signalErrorsToValidationErrors","errObj","reactiveErrorsToSignalErrors","entries","extractNestedReactiveErrors","FormGroup","FormArray","c","controls"],"mappings":";;;;;;;;;;AAQA,IAAIA,cAAc,GAAG,CAAC;SAMNC,iBAAiBA,GAAA;AAC/B,EAAA,OAAOD,cAAc;AACvB;AAgCM,SAAUE,8BAA8BA,CAC5CC,EAAqB,EACrBC,KAAa,EAAA;EAEb,OAAO,CAAC,GAAGC,IAAO,KAAI;IACpB,IAAI;AACFL,MAAAA,cAAc,GAAGI,KAAK;AACtB,MAAA,OAAOD,EAAE,CAAC,GAAGE,IAAI,CAAC;AACpB,IAAA,CAAA,SAAU;AACRL,MAAAA,cAAc,GAAG,CAAC;AACpB,IAAA;EACF,CAAC;AACH;;ACjDM,SAAUM,iBAAiBA,CAACC,KAAc,EAAA;AAC9C,EAAA,OAAO,CAACA,KAAK;AACf;AAGM,SAAUC,gBAAgBA,CAACD,KAAc,EAAA;AAC7C,EAAA,OAAOA,KAAK;AACd;AASM,SAAUE,sBAAsBA,CAACC,OAAyB,EAAA;AAC9D,EAAA,IAAIA,OAAO,CAACC,IAAI,KAAK,MAAM,EAAE;AAC3B,IAAA,OAAOD,OAAO,CAACE,YAAY,CAACC,QAAQ;AACtC,EAAA;EAEA,OAAOH,OAAO,CAACI,MAAM,CAACC,SAAS,CAACC,IAAI,CAACD,SAAS,CAACF,QAAQ;AACzD;;ACtBM,SAAUI,OAAOA,CAACV,KAAc,EAAA;AACpC,EAAA,OAAOW,KAAK,CAACD,OAAO,CAACV,KAAK,CAAC;AAC7B;AAKM,SAAUY,QAAQA,CAACZ,KAAc,EAAA;AACrC,EAAA,OAAO,CAAC,OAAOA,KAAK,KAAK,QAAQ,IAAI,OAAOA,KAAK,KAAK,UAAU,KAAKA,KAAK,IAAI,IAAI;AACpF;;ACIO,MAAMa,OAAO,GAAkBC,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