@dynamicforms/vue-forms 2.0.3 → 3.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"dynamicforms-vue-forms.js","names":["#state","#raw"],"sources":["../src/access.ts","../src/visibility.ts","../src/actions/field-action-base.ts","../src/field.interface.ts","../src/actions/value-changed-action.ts","../src/transaction.ts","../src/config.ts","../src/validators/validation-error.ts","../src/validators/error-message-builder.ts","../src/validators/translations.ts","../src/validators/validator.ts","../src/actions/actions-map.ts","../src/binding/resolve.ts","../src/actions/conditional/conditional-statement-action.ts","../src/actions/conditional/operator.ts","../src/actions/access-actions.ts","../src/actions/contribution-changed-action.ts","../src/actions/enabled-actions.ts","../src/actions/valid-changed-action.ts","../src/actions/visibility-actions.ts","../src/field-base.ts","../src/actions/conditional/statement.ts","../src/actions/execute-action.ts","../src/actions/list-item-added-action.ts","../src/actions/list-item-removed-action.ts","../src/element-state.ts","../src/field.ts","../src/action.ts","../src/components/messages-widget.vue","../src/components/messages-widget.vue","../src/container.ts","../src/group.ts","../src/is-equal.ts","../src/list.ts","../src/validators/validator-compare-to.ts","../src/validators/validator-in-allowed-values.ts","../src/validators/validator-required.ts","../src/validators/validator-min-max-range.ts","../src/validators/validator-min-max-range-length.ts","../src/validators/validator-pattern.ts","../src/validators/index-validators.ts","../src/view.ts","../src/index-individual.ts","../src/index.ts"],"sourcesContent":["/**\n * What a form element accepts and what it sends. The four values follow HTML: `'editable'` and `'readonly'` send\n * the element's value the way an `<input>` and an `<input readonly>` are submitted, `'disabled'` sends nothing the\n * way an `<input disabled>` is left out, and `'disabled-null'` sends `null` in the element's place.\n *\n * | access | accepts input | contributes to its container's `value` |\n * |-------------------|---------------|----------------------------------------|\n * | `'editable'` | yes | its value |\n * | `'readonly'` | no | its value |\n * | `'disabled'` | no | nothing: the key or row is left out |\n * | `'disabled-null'` | no | `null` |\n *\n * An element that contributes no value of its own is not counted in its container's validity. `fullValue` carries\n * every element whatever its access.\n */\nexport type Access = 'editable' | 'readonly' | 'disabled' | 'disabled-null';\n\n/** every access, in the order of the table above */\nexport const accessValues: readonly Access[] = Object.freeze(['editable', 'readonly', 'disabled', 'disabled-null']);\n\n/** What an element's access is when nothing sets it. */\nexport const defaultAccess: Access = 'editable';\n\n/** Answers whether `value` is one of the four accesses. */\nexport function isAccess(value: unknown): value is Access {\n return (accessValues as readonly unknown[]).includes(value);\n}\n","/**\n * How a rendering layer shows a form element. It is presentation alone: what an element sends and whether it is\n * validated are its `access`, and no visibility changes either.\n *\n * - `'full'`: rendered and shown\n * - `'invisible'`: rendered and keeps its space in the layout, but is not painted (`visibility: hidden`)\n * - `'hidden'`: rendered but not displayed, taking no space (`display: none`)\n * - `'suppress'`: not rendered at all\n */\nexport type Visibility = 'full' | 'invisible' | 'hidden' | 'suppress';\n\n/** every visibility, from shown to not rendered */\nexport const visibilityValues: readonly Visibility[] = Object.freeze(['full', 'invisible', 'hidden', 'suppress']);\n\n/** What an element's visibility is when nothing sets it. */\nexport const defaultVisibility: Visibility = 'full';\n\n/** Answers whether `value` is one of the four visibilities. */\nexport function isVisibility(value: unknown): value is Visibility {\n return (visibilityValues as readonly unknown[]).includes(value);\n}\n","import type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\ntype ActionExecutor = (field: FieldBase, supr: FieldActionExecute, ...params: any[]) => any;\n\nexport default abstract class FieldActionBase {\n public static get classIdentifier(): symbol {\n throw new Error('classIdentifier must be declared');\n }\n\n public get classIdentifier(): symbol {\n return (<any>this.constructor).classIdentifier;\n }\n\n private readonly executorFn: ActionExecutor;\n\n /**\n * What this action remembers about one of the elements it serves. An action instance is shared - a `List` row\n * carries the instances the item template carries - so anything an action holds about the element it last ran\n * over belongs to that element rather than to the action: a verdict, a sequence number, a listener it installed.\n * The keys are weak, so what an action remembers about a row is released with the row.\n */\n private readonly states = new WeakMap<object, any>();\n\n constructor(executorFn: ActionExecutor) {\n this.executorFn = executorFn;\n }\n\n /**\n * This action's state for `key`, created by `init` the first time it is asked for. The key is the element the\n * action is running over, or the record that element belongs to where what is remembered is a fact about the\n * whole record.\n */\n protected state<S>(key: object, init: () => S): S {\n if (!this.states.has(key)) this.states.set(key, init());\n return this.states.get(key) as S;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, ...params: any[]): any {\n return this.executorFn(field, supr, ...params);\n }\n\n get eager() {\n return false;\n }\n\n /**\n * Announces that this action now serves `binding`. It runs once per element the action is registered on, the\n * copies of that element included: a copy takes on the instances it was copied from and each is told about the\n * copy as it does.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n boundToBinding(binding: FieldBase) {}\n\n /**\n * Announces that `binding` no longer holds this action, and takes back what running it left there. It names one\n * element rather than the action as a whole, because the instance goes on serving every other element it was\n * registered on. It runs inside the operation that drops the registration, so an operation that unwinds puts the\n * registration and what this took back both back.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n unregisterFrom(binding: FieldBase) {}\n}\n","import type { Access } from './access';\nimport type FieldActionBase from './actions/field-action-base';\nimport type { FieldBase } from './field-base';\nimport { type ValidationError } from './validators/validation-error';\nimport type { Visibility } from './visibility';\n\nexport interface IFieldConstructorActionsList {\n actions?: FieldActionBase[];\n validators?: FieldActionBase[];\n}\n\n/**\n * Parameters accepted by field constructors and by bind overrides.\n *\n * Only writable members are listed. valid, validating, busy, fullValue, isChanged, enabled and effectiveEnabled are\n * getter-only, so assigning them throws a TypeError. So are parent and fieldName: a container writes the slots\n * behind them when it takes an element, and nobody else can, which is why the type rejects them.\n */\nexport type IFieldConstructorParams<T = any> = {\n value: T;\n originalValue: T;\n access: Access;\n visibility: Visibility;\n touched: boolean;\n errors: ValidationError[];\n} & IFieldConstructorActionsList;\n\n/**\n * The extended properties an element carries when nothing states otherwise. It is empty as declared and exists\n * to be augmented: the layer that renders the elements declares what it renders them with, and every element in\n * the application then carries those properties without a type argument at any construction site.\n *\n * ```ts\n * declare module '@dynamicforms/vue-forms' {\n * interface Extras {\n * label?: string;\n * hint?: string;\n * cssClass?: string;\n * }\n * }\n * ```\n *\n * The interface is one per application, so two packages that both declare a property of the same name must give\n * it the same type; declaration merging refuses a second declaration that differs.\n *\n * An element that states an X of its own replaces this rather than adding to it, so an element that carries both\n * is `Field<string, Extras & Local>`.\n */\nexport interface Extras {}\n\n/**\n * What an element's constructor accepts: the parameters the element answers for itself, together with the\n * extended properties its X parameter declares.\n *\n * X is left out of inference, so an element carries what its X states - `Extras` where no type argument replaces\n * it - and a parameter object naming anything else is rejected as an excess property.\n *\n * The two halves are made partial separately. `Partial<A & X>` is a mapped type over an intersection, which is\n * what T is inferred through, and inference through it answers with one constituent of a union rather than the\n * union: `new Field({ value: someStringOrNumber })` would be a Field<string>.\n */\nexport type IFieldParams<T = any, X extends object = Extras> = Partial<IFieldConstructorParams<T>> &\n Partial<NoInfer<X>>;\n\n/**\n * What bind() accepts beside the data it binds: the three members a binding takes over from the element it was\n * bound from, and the extended properties. What is left out is left out because a binding cannot honour it -\n * `validators` and `actions` are carried from the declaration rather than supplied, and `touched` and `errors`\n * are what the binding establishes for itself as it validates.\n */\nexport type IBindParams<T = any, X extends object = Extras> = Partial<\n Pick<IFieldConstructorParams<T>, 'originalValue' | 'access' | 'visibility'>\n> &\n Partial<NoInfer<X>>;\n\n/**\n * Thrown from a handler to end the run it is in. What the trigger answers with is the exception itself rather than\n * `null`, so a caller can tell a run a handler ended from one that reached no handler at all - and the setters\n * that ask a `*Changing*` handler read it as a refusal and write nothing. The answer carries it directly where the\n * chain ran synchronously, and as what the answered promise resolves to where a handler in it was asynchronous.\n */\nexport class AbortEventHandlingException extends Error {}\n\nexport type FieldActionExecute<T = any> = (field: FieldBase<T>, ...params: any[]) => any;\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nexport const ValueChangedActionClassIdentifier = Symbol('ValueChangedAction');\n\nexport class ValueChangedAction<T = any> extends FieldActionBase {\n constructor(executorFn: (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ValueChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import type FieldActionBase from './actions/field-action-base';\nimport type { FieldBase } from './field-base';\n\n/**\n * A transaction is the unit an observer sees a change in. Every mutating operation runs inside one: where the\n * caller opens none, the operation is the transaction, so a single write is atomic without anything having to be\n * remembered at the call site.\n *\n * Writes land in the element straight away and only the announcement waits. At commit the net transitions are\n * measured against the state the elements last announced and each is announced once, so a value that goes A -> B\n * -> A within one transaction says nothing. Validators run while the transaction is open, because the verdict\n * they reach is what the commit announces; every other action fires at commit.\n *\n * A transaction may not cross an await: transaction() throws when the callback returns a thenable. Two\n * overlapping transactions therefore cannot exist, and an asynchronous validator settling later opens one of its\n * own at that moment.\n */\n\n/** the slots of one element as they stood when the transaction first modified it */\nexport type TxSnapshot = Record<string, any>;\n\n/** a ListItemAddedAction or ListItemRemovedAction waiting for the commit that will emit it */\nexport interface TxStructuralEvent {\n actionClass: (abstract new (...args: any[]) => FieldActionBase) & { classIdentifier: symbol };\n item: any;\n index: number;\n}\n\n/**\n * The protocol a transaction drives its participants through. The four members are symbol-keyed so that they\n * carry no name a consumer could reach or collide with, and they live on the prototype, so no walker over an\n * element's own keys sees them either.\n */\nexport const TxCapture = Symbol('Transaction.capture');\n/** asked by a validator before it runs: whether the element is sent nowhere, read without tracking */\nexport const SentNowhere = Symbol('FieldBase.sentNowhere');\nexport const TxRestore = Symbol('Transaction.restore');\nexport const TxAnnounceValue = Symbol('Transaction.announceValue');\nexport const TxSettleValidity = Symbol('Transaction.settleValidity');\n\ninterface TxParticipantElement {\n readonly parent: FieldBase | undefined;\n [TxCapture](): TxSnapshot;\n [TxRestore](snapshot: TxSnapshot): void;\n [TxAnnounceValue](tx: Transaction, dirty: boolean, force: boolean, structural?: TxStructuralEvent[]): void;\n [TxSettleValidity](tx: Transaction): void;\n}\n\n/** FieldBase declares the four members above as protected, which is what keeps them off the documented surface */\nfunction hooks(element: FieldBase): TxParticipantElement {\n return element as unknown as TxParticipantElement;\n}\n\ninterface Participant {\n element: FieldBase;\n /** the element's state as the transaction found it, taken the first time the transaction modified the element */\n snapshot?: TxSnapshot;\n /** the commit has to work out whether this element's value changed and announce it where it did */\n valueDirty: boolean;\n /** the caller already knows the value changed, so the commit announces it without comparing */\n forceValue: boolean;\n /** the commit has to re-form this element's verdict and announce a transition of it */\n validityDirty: boolean;\n structural?: TxStructuralEvent[];\n}\n\n/** how many containers stand above an element; the commit announces the deepest first */\nfunction depthOf(element: FieldBase): number {\n let depth = 0;\n let ancestor = element.parent;\n while (ancestor) {\n depth++;\n ancestor = ancestor.parent;\n }\n return depth;\n}\n\nexport class Transaction {\n private readonly participants = new Map<FieldBase, Participant>();\n\n /** what a rollback has to put back beyond the state slots, newest last */\n private readonly undo: (() => void)[] = [];\n\n /** what the commit has to do once the change stands, in the order it was handed in */\n private readonly settled: (() => void)[] = [];\n\n /** true once the transaction has been unwound, which is what tells a run started inside it to say nothing */\n private unwound = false;\n\n /** the depth the announcement in progress is working at, -1 while none is */\n private passDepth = -1;\n\n /** set while a pass is running and an element it has already passed the depth of gets enrolled */\n private restartPass = false;\n\n /** true for a transaction that was rolled back rather than committed */\n get rolledBack(): boolean {\n return this.unwound;\n }\n\n private participant(element: FieldBase): Participant {\n let entry = this.participants.get(element);\n if (!entry) {\n entry = { element, valueDirty: false, forceValue: false, validityDirty: false };\n this.participants.set(element, entry);\n }\n return entry;\n }\n\n /**\n * Records the state of an element the first time the transaction modifies it. The whole of the mutable state\n * goes into the snapshot rather than the part being written: a rollback that restored some of it would leave\n * the element in a state the form never held.\n */\n touch(element: FieldBase): void {\n const entry = this.participant(element);\n if (!entry.snapshot) entry.snapshot = hooks(element)[TxCapture]();\n }\n\n /** Enrols an element as one whose value the commit has to announce. `force` skips the comparison. */\n markValueChanged(element: FieldBase, force: boolean): void {\n const entry = this.participant(element);\n entry.valueDirty = true;\n if (force) entry.forceValue = true;\n this.noteDepth(element);\n }\n\n /** Enrols an element as one whose verdict the commit has to re-form. */\n markValidityDirty(element: FieldBase): void {\n this.participant(element).validityDirty = true;\n this.noteDepth(element);\n }\n\n /**\n * Queues an event that states an operation rather than a state. Added and removed items have no net over a\n * transaction, so they are neither compared nor coalesced: the commit emits them in the order they happened.\n */\n recordStructural(element: FieldBase, event: TxStructuralEvent): void {\n const entry = this.participant(element);\n (entry.structural ??= []).push(event);\n this.noteDepth(element);\n }\n\n /** True where the commit still owes this element a value announcement. */\n willAnnounceValue(element: FieldBase): boolean {\n return this.participants.get(element)?.valueDirty ?? false;\n }\n\n /**\n * Registers what a rollback has to put back beyond the element's state slots. The snapshot covers the slots,\n * which is everything an ordinary write touches; an operation that replaces something else the element carries\n * hands its own undo in here rather than making every snapshot carry the thing.\n */\n whenRolledBack(work: () => void): void {\n this.undo.push(work);\n }\n\n /**\n * Registers work that runs once the transaction has committed, and not at all where it is rolled back. It is\n * how an operation defers a step that cannot be taken back - cancelling work in flight, for one - until the\n * change it belongs to actually stands.\n */\n whenCommitted(work: () => void): void {\n this.settled.push(work);\n }\n\n /**\n * Notes that an element at or below the depth the pass in progress is working at has been enrolled. The pass\n * then gives up the rest of its batch and is started again over what is now owed, so the newcomer is reached\n * before the containers above it: an element a handler writes must still be announced before the container\n * whose composed value carries that write. The depth is only measured while a pass is running - outside one\n * there is nothing the answer would change.\n */\n private noteDepth(element: FieldBase): void {\n if (this.passDepth < 0) return;\n if (depthOf(element) >= this.passDepth) this.restartPass = true;\n }\n\n /**\n * Puts every element the transaction modified back as it found it. Nothing is announced: from an observer's\n * point of view the transaction never happened. What a rollback cannot take back are side effects - a handler\n * that called a server during the transaction already did.\n */\n rollback(): void {\n this.unwound = true;\n const entries = [...this.participants.values()].reverse();\n entries.forEach((entry) => {\n if (entry.snapshot) hooks(entry.element)[TxRestore](entry.snapshot);\n });\n this.participants.clear();\n // newest first, so an element written twice ends up as the earlier of the two writes found it\n for (let index = this.undo.length - 1; index >= 0; index--) this.undo[index]();\n this.undo.length = 0;\n // the change never stood, so what was waiting for it never runs\n this.settled.length = 0;\n }\n\n /**\n * Announces what the transaction did. Values first and verdicts after, because a container's validators run\n * with its value announcement and the verdict they reach is what the validity pass then reports. Both passes\n * run deepest first - field, then row, then list - which is the order the change travelled in.\n *\n * A handler may write while the commit runs; its writes join this transaction, so both passes repeat until\n * nothing is left dirty.\n */\n commit(): void {\n for (;;) {\n if (this.announceValues()) continue;\n if (this.settleValidity()) continue;\n break;\n }\n // everything is announced and the change stands, so the steps that were waiting for it run here\n for (let index = 0; index < this.settled.length; index++) this.settled[index]();\n this.settled.length = 0;\n }\n\n /**\n * The dirty participants a pass has to visit, one bucket per nesting depth; ties keep the order they were\n * enrolled in. A nesting depth is a small integer, so the elements go into buckets rather than through a\n * comparison sort: a whole-list assignment enrols one participant per field, and ordering those by comparison\n * would cost more than the announcement it orders.\n */\n private buckets(pick: (entry: Participant) => boolean): (Participant[] | undefined)[] {\n const buckets: (Participant[] | undefined)[] = [];\n this.participants.forEach((entry) => {\n if (!pick(entry)) return;\n const depth = depthOf(entry.element);\n (buckets[depth] ??= []).push(entry);\n });\n return buckets;\n }\n\n /**\n * Runs one pass over the dirty participants, deepest bucket first; the caller repeats it until it answers\n * false. The buckets are taken once, and the pass gives up as soon as a handler enrols an element at or below\n * the depth being drained: that element is not in the bucket being walked, and going on would reach the\n * containers above it first. The caller's next pass takes fresh buckets and finds it at its own depth.\n */\n private pass(pick: (entry: Participant) => boolean, visit: (entry: Participant) => void): boolean {\n const buckets = this.buckets(pick);\n if (!buckets.length) return false;\n for (let depth = buckets.length - 1; depth >= 0; depth--) {\n const bucket = buckets[depth];\n if (!bucket) continue;\n this.passDepth = depth;\n this.restartPass = false;\n try {\n for (let index = 0; index < bucket.length; index++) {\n if (this.restartPass) return true;\n const entry = bucket[index];\n // a handler that ran earlier in this pass may have taken the entry off the list of what is owed\n if (pick(entry)) visit(entry);\n }\n } finally {\n this.passDepth = -1;\n }\n if (this.restartPass) return true;\n }\n return true;\n }\n\n private announceValues(): boolean {\n return this.pass(\n (entry) => entry.valueDirty || entry.structural !== undefined,\n (entry) => {\n const { structural } = entry;\n const dirty = entry.valueDirty;\n const force = entry.forceValue;\n entry.structural = undefined;\n entry.valueDirty = false;\n entry.forceValue = false;\n hooks(entry.element)[TxAnnounceValue](this, dirty, force, structural);\n },\n );\n }\n\n private settleValidity(): boolean {\n return this.pass(\n (entry) => entry.validityDirty,\n (entry) => {\n entry.validityDirty = false;\n hooks(entry.element)[TxSettleValidity](this);\n },\n );\n }\n}\n\n/** the transaction every mutating operation currently joins, absent while none is open */\nlet current: Transaction | undefined;\n\n/** the handle of the open transaction, which a nested call joining it receives too */\nlet currentHandle: TransactionHandle | undefined;\n\n/** The open transaction, for the bookkeeping an element does only where one is running. */\nexport function currentTransaction(): Transaction | undefined {\n return current;\n}\n\n/**\n * Unwinds the transaction from wherever it is called. It is a signal rather than an error: transaction()\n * catches it, rolls back and returns undefined, and nothing is reported as a failure.\n */\nclass RollbackSignal {}\n\nexport interface TransactionControl {\n /**\n * Undoes everything the transaction has done and ends it, announcing nothing. It unwinds from the point of\n * the call, so nothing after it runs. There are no savepoints: a nested call rolls back the whole transaction\n * it joined, not its own part of it.\n *\n * @throws TypeError where the transaction the handle belongs to has already closed.\n */\n rollback(): never;\n}\n\n/**\n * The handle one transaction hands the callbacks that take part in it. It is spent the moment the transaction\n * closes: a handle kept beyond that call names a transaction that no longer exists, and letting it unwind\n * whatever transaction happened to be open instead would roll back an unrelated operation.\n */\nclass TransactionHandle implements TransactionControl {\n private open = true;\n\n rollback(): never {\n if (!this.open) {\n throw new TypeError(\n 'this transaction handle is spent: the transaction that handed it out has closed. A handle is only ' +\n 'usable inside the call that received it.',\n );\n }\n throw new RollbackSignal();\n }\n\n close(): void {\n this.open = false;\n }\n}\n\nfunction rejectThenable(result: unknown): void {\n if (result != null && typeof (result as PromiseLike<unknown>).then === 'function') {\n throw new TypeError(\n 'a transaction may not be asynchronous: the callback returned a thenable. Do the awaiting outside and open ' +\n 'a transaction for each synchronous part.',\n );\n }\n}\n\n/**\n * Runs `fn` as one atomic change. The writes it makes land in the elements as they are made and the events they\n * produce are announced once, at the end, over the net result.\n *\n * A call made while a transaction is already open joins it: nothing is committed until the outermost call\n * returns. A throw out of `fn` rolls the whole transaction back and rethrows, and `tx.rollback()` rolls it back\n * without an error, in which case the call answers undefined.\n *\n * The handle `fn` receives is usable only for the duration of that call; calling it afterwards throws a TypeError.\n *\n * @throws TypeError immediately if `fn` returns a thenable - a transaction cannot cross an await.\n */\nexport function transaction<R>(fn: (tx: TransactionControl) => R): R | undefined {\n if (current) {\n const joined = fn(currentHandle!);\n rejectThenable(joined);\n return joined;\n }\n\n const tx = new Transaction();\n const handle = new TransactionHandle();\n current = tx;\n currentHandle = handle;\n try {\n const result = fn(handle);\n rejectThenable(result);\n tx.commit();\n return result;\n } catch (error) {\n // the commit may have announced part of the change before the throw; the state goes back all the same, and\n // what a handler did with the events it already received is a side effect no snapshot reaches\n tx.rollback();\n if (error instanceof RollbackSignal) return undefined;\n throw error;\n } finally {\n current = undefined;\n currentHandle = undefined;\n handle.close();\n }\n}\n\n/**\n * Runs a mutating operation inside the open transaction, opening one for the operation where none is. It is how\n * an element reaches the transaction it takes part in: everything the library mutates goes through here.\n */\nexport function transactional<R>(fn: (tx: Transaction) => R): R {\n if (current) return fn(current);\n return transaction(() => fn(current!)) as R;\n}\n","/**\n * Global configuration for @dynamicforms/vue-forms.\n *\n * The configuration is module-global: `setConfig` and the plugin's `install` write the single record this module\n * holds, so in a process running several Vue apps the configuration applied last is the one all of them read.\n */\nexport interface FormsConfig {\n /** Whether the built-in validators phrase their error messages as `MdString` markdown instead of plain text. */\n useMarkdownInValidators: boolean;\n}\n\n// Default configuration\nconst config: FormsConfig = { useMarkdownInValidators: true };\n\n/** The current configuration. The object is the module's own record, and reading it again reports later writes. */\nexport function getConfig(): FormsConfig {\n return config;\n}\n\n/** Writes the members `newConfig` names and leaves the rest as they stand. */\nexport function setConfig(newConfig: Partial<FormsConfig>): void {\n Object.assign(config, newConfig);\n}\n\n// Vue plugin installation\nexport default {\n install(app: any, options?: Partial<FormsConfig>) {\n if (options) {\n setConfig(options);\n }\n },\n};\n","import { isEqual } from 'lodash-es';\nimport { computed, ComputedRef, Ref, unref } from 'vue';\n\n/**\n * Marks content for markdown rendering\n */\nexport class MdString extends String {\n plugins?: any[];\n options?: any;\n\n constructor(value: string, options?: any, plugins?: any[]) {\n super(value);\n this.plugins = plugins;\n this.options = options;\n }\n}\n\n/**\n * Interface for custom component content definition\n */\nexport interface SimpleComponentDef {\n componentName: string;\n componentProps?: Record<any, any>;\n componentVHtml?: string;\n}\n\nexport type ClassType = string | string[] | Record<string, boolean>;\nexport type ClassTypes = ClassType | ClassType[];\n\nexport type RenderContentNonCallable = string | MdString | SimpleComponentDef;\nexport type RenderContentCallable = () => RenderContentNonCallable;\n/**\n * Type for different renderable content formats: plain string, markdown, or custom component\n */\nexport type RenderContent = RenderContentNonCallable | RenderContentCallable;\n/**\n * Type for different renderable content formats (supporting references): plain string, markdown, or custom component\n */\nexport type RenderContentRef = RenderContent | Ref<RenderContent>;\n\n/**\n * Type guard to check if content is a custom component definition\n * @param msg - Content to check\n * @returns True if content is a custom component definition\n */\nexport function isSimpleComponentDef(msg?: RenderContentRef): msg is SimpleComponentDef {\n const uMsg = unref(msg);\n // typeof null is 'object', and `in` refuses null: the answer for it is that it defines no component\n return typeof uMsg === 'object' && uMsg !== null && 'componentName' in uMsg;\n}\n\nexport function isCallableFunction(msg?: RenderContentRef): msg is RenderContentCallable {\n return typeof unref(msg) === 'function';\n}\n\n/**\n * Where an error comes from. `'validator'` is an error a validator produced, `'server'` one the server returned and\n * `'application'` one the application's own code computed and wrote into `errors`. Any other string is an origin of\n * the application's own.\n */\nexport type ErrorOrigin = 'validator' | 'server' | 'application' | (string & {});\n\n/**\n * Base validation error class with component rendering capabilities\n */\n\nexport class ValidationError {\n /**\n * @param code Machine-readable identifier of what failed, in kebab-case. Every validator this library ships states\n * one, so code that reacts to a particular failure does not have to match the message text, which is translated\n * and configurable. It is optional: an error built by hand carries whatever its author gives it, or nothing.\n * @param statedOrigin Where the error comes from, where its author states it; see `origin`.\n */\n constructor(\n public code?: string,\n private readonly statedOrigin?: ErrorOrigin,\n ) {}\n\n /**\n * Where the error comes from: the origin its author stated, and otherwise `'validator'` for an error a validator\n * produced - a validator stamps every error it hands a field - and `'application'` for one written into `errors`\n * by any other code. It is what a rendering layer reads to decide when to show the error, and what code reads to\n * withdraw the errors of one origin and leave the rest.\n */\n get origin(): ErrorOrigin {\n if (this.statedOrigin !== undefined) return this.statedOrigin;\n return typeof (this as { source?: unknown }).source === 'symbol' ? 'validator' : 'application';\n }\n\n /**\n * True where `other` is an error of this class that renders exactly as this one does and reports the same code.\n * Two runs of one validator over an unchanged value produce two instances of one message, and this is what lets\n * the validator hand the field back the instance it already holds rather than a fresh one: an equal error is not\n * a new error, and nothing re-renders over a verdict that did not move.\n *\n * The comparison is over what renders - the component, its bindings, its body and the classes - because that is\n * what a reader of `field.errors` sees. A structural comparison of the errors themselves answers nothing useful:\n * `ValidationErrorRenderContent` holds a Vue `computed`, and two of those are never structurally equal.\n */\n sameAs(other: ValidationError): boolean {\n return (\n Object.getPrototypeOf(this) === Object.getPrototypeOf(other) &&\n this.code === other.code &&\n this.statedOrigin === other.statedOrigin &&\n this.componentName === other.componentName &&\n isEqual(this.componentBody, other.componentBody) &&\n isEqual(this.componentBindings, other.componentBindings) &&\n isEqual(this.extraClasses, other.extraClasses)\n );\n }\n\n get componentName() {\n return 'Comment';\n }\n\n get componentBindings() {\n return {};\n }\n\n get componentBody() {\n return '';\n }\n\n get extraClasses(): ClassTypes {\n return '';\n }\n}\n\n/**\n * Simple text-only ValidationError\n */\nexport class ValidationErrorText extends ValidationError {\n constructor(\n public text: string,\n public classes: ClassTypes = '',\n code?: string,\n origin?: ErrorOrigin,\n ) {\n super(code, origin);\n }\n\n get componentName() {\n return 'template';\n }\n\n get componentBody() {\n return this.text;\n }\n\n get extraClasses() {\n return this.classes;\n }\n}\n\n/**\n * Validation error that supports multiple content types (plain text, markdown, component)\n */\nexport class ValidationErrorRenderContent extends ValidationError {\n private text: RenderContent | Ref<RenderContent>;\n\n private textType: ComputedRef<'string' | 'md' | 'component'>;\n\n constructor(\n text: RenderContentRef,\n public classes: ClassTypes = '',\n code?: string,\n origin?: ErrorOrigin,\n ) {\n super(code, origin);\n this.text = text;\n this.textType = computed(() => this.getTextType);\n }\n\n get resolvedText() {\n const text = unref(this.text);\n return isCallableFunction(text) ? text() : text;\n }\n\n get getTextType() {\n const msg = this.resolvedText;\n\n if (!msg) return 'string';\n if (msg instanceof MdString) return 'md';\n if (isSimpleComponentDef(msg)) return 'component';\n return 'string';\n }\n\n get componentName() {\n switch (unref(this.textType)) {\n case 'string':\n return 'template';\n case 'md':\n return 'vue-markdown';\n case 'component':\n return (this.resolvedText as SimpleComponentDef).componentName;\n default:\n return 'template';\n }\n }\n\n get componentBindings() {\n switch (unref(this.textType)) {\n case 'string':\n return {};\n case 'md': {\n const text = this.resolvedText as MdString;\n return { source: text.toString(), options: text.options, plugins: text.plugins };\n }\n case 'component':\n return (this.resolvedText as SimpleComponentDef).componentProps || {};\n default:\n return {};\n }\n }\n\n get componentBody() {\n switch (unref(this.textType)) {\n case 'string':\n return this.resolvedText as string;\n case 'component':\n return (this.resolvedText as SimpleComponentDef).componentVHtml || '';\n default:\n return '';\n }\n }\n\n get extraClasses() {\n return this.classes;\n }\n}\n\n/**\n * A value, renderable three different ways (plain text, markdown, component) - alias for ValidationErrorRenderContent\n */\nexport class RenderableValue extends ValidationErrorRenderContent {}\n\n/** ********************************************************************************************************************\n *\n at some point there will be classes here that will support links or action buttons or something even more complex\n *\n ******************************************************************************************************************** */\n","import { computed, ComputedRef, isRef, Ref } from 'vue';\n\nimport { getConfig } from '../config';\n\nimport { MdString } from './validation-error';\n\nfunction stripOrWrap(mdErrorString: string): string | MdString {\n const useMarkdownInValidators = getConfig().useMarkdownInValidators;\n if (useMarkdownInValidators) return new MdString(mdErrorString);\n\n return mdErrorString\n .replace(/[*_~`]/g, '') // remove basic markdown (italic, bold, strike, code)\n .replace(/!\\[(.*?)\\]\\(.*?\\)/g, '$1') // remove images, keep alt only\n .replace(/\\[(.*?)\\]\\((.*?)\\)/g, '$1') // remove links, keep name only\n .replace(/#+\\s?/g, '') // Remove heading markers (#, ##, ###)\n .replace(/>\\s?/g, '') // remove quotes\n .replace(/(\\*|-|\\d+\\.)\\s+/g, '') // remove lists (bullet points and numbered lists)\n .replace(/`{3}[\\s\\S]*?`{3}/g, '') // remove code blocks\n .replace(/`([^`]+)`/g, '$1') // remove inline code markers\n .replace(/\\n{2,}/g, '\\n'); // removes excessive empty lines\n}\n\n/**\n * Depending on the useMarkdownInValidators setting, return either markdown or a plain string error message. A\n * Ref is stripped/wrapped on read rather than once here, so a translated template re-applies the same choice\n * as its text changes.\n * @param mdErrorString markdown source to optionally be stripped\n * @return MdString or string, or a ComputedRef of either where `mdErrorString` is itself a Ref\n */\nexport function buildErrorMessage<T extends string | Ref<string>>(\n mdErrorString: T,\n): T extends Ref<string> ? ComputedRef<string | MdString> : string | MdString {\n type Result = T extends Ref<string> ? ComputedRef<string | MdString> : string | MdString;\n\n if (isRef(mdErrorString)) return computed(() => stripOrWrap(mdErrorString.value)) as Result;\n return stripOrWrap(mdErrorString as string) as Result;\n}\n","import { createTranslatable } from '@dynamicforms/translatable';\nimport { toRef } from 'vue';\n\nimport { buildErrorMessage } from './error-message-builder';\n\n/**\n * The built-in validators' default English messages, keyed by what each one validates rather than by its text -\n * a translation set reads as a list of concepts, not a list of English sentences to override. The `{name}`\n * placeholders are substituted by the validator that owns each message, against the value it is currently\n * validating, so a translation keeps them as they stand.\n */\nexport const { strings, translateStrings } = createTranslatable({\n Required: 'Please enter a value',\n MinValue: 'Value must be larger or equal to **{minValue}**',\n MaxValue: 'Value must be less than or equal to **{maxValue}**',\n ValueInRange: 'Value must be between **{minValue}** and **{maxValue}**',\n MinLength: 'Length must be larger or equal to **{minLength}**',\n MaxLength: 'Length must be less than or equal to **{maxLength}**',\n LengthInRange: 'Length must be between **{minLength}** and **{maxLength}**',\n Pattern: 'Value must match pattern \"**{pattern}**\"',\n InAllowedValues: 'Must be one of [**{allowedAsText}**]',\n ValidationFailed: 'Validation could not be completed',\n});\n\n/** A built-in validator's default message, translated and reactive to a later `translateStrings` call. */\nexport function translatedMessage(key: keyof typeof strings) {\n return buildErrorMessage(toRef(strings, key));\n}\n","import { interpolate } from '@dynamicforms/translatable';\nimport { isRef, unref } from 'vue';\n\nimport { ValueChangedAction } from '../actions/value-changed-action';\nimport { type FieldBase } from '../field-base';\nimport { FieldActionExecute } from '../field.interface';\nimport { currentTransaction, SentNowhere, transaction, transactional } from '../transaction';\n\nimport { translatedMessage } from './translations';\nimport {\n isCallableFunction,\n isSimpleComponentDef,\n MdString,\n RenderContentNonCallable,\n RenderContentRef,\n ValidationError,\n ValidationErrorRenderContent,\n} from './validation-error';\n\nexport type ValidationFunctionResult = ValidationError[] | null;\n/**\n * What a validator does with a value. `signal` aborts when the verdict this call would reach stops counting - a\n * newer run over the same field, a field the validator was taken off once that removal stands, a transaction that\n * was unwound - so an asynchronous check hands it to the work it commissions and stops paying for an answer nobody\n * will read. A function that has nothing to cancel ignores it.\n */\nexport type ValidationFunction<T = any> = (\n newValue: T,\n oldValue: T,\n field: FieldBase<T>,\n signal: AbortSignal,\n) => ValidationFunctionResult | Promise<ValidationFunctionResult>;\n\ninterface SourceProp {\n source: symbol;\n}\n\n/** What a validator remembers about one field it is registered on; a subclass widens it. */\nexport interface ValidatorBindingState {\n run: number;\n /** cancels the asynchronous run in flight over the field, absent while no run is waiting for its verdict */\n abandon?: () => void;\n}\n\nconst ValidatorClassIdentifier = Symbol('Validator');\n\n/**\n * Message shown when a validation run rejects. It is built per rejection because the markdown setting it reads is\n * a runtime configuration value.\n */\nconst validationFailedMessage = (): RenderContentRef => translatedMessage('ValidationFailed');\n\n/**\n * Validator is a specialized action that performs validation when a field's value changes.\n * It automatically adds/removes validation errors from the field's errors array.\n */\nexport class Validator<T = any> extends ValueChangedAction {\n private readonly source: symbol;\n\n /**\n * Creates a new validator\n * @param validationFn Function that validates the field value and returns errors or null\n */\n constructor(validationFn: ValidationFunction<T>) {\n const executor = (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T) => {\n const runs = this.bindingState(field);\n // the run still waiting for its verdict over this field, which this one takes the place of\n const superseded = runs.abandon;\n const run = ++runs.run;\n const epoch = field.validationEpoch;\n // the transaction this run started in, so that a run reaching its verdict after that transaction was\n // unwound says nothing: the value it examined is one the form never went on to hold\n const startedIn = currentTransaction();\n // a result counts only while nothing newer has been decided for this field, the field still holds the\n // validators it held when the run started, the change that prompted it still stands, and the run was not\n // cancelled. Cancellation is the one condition that does not read the field: the work behind the run is\n // already called off, so whatever the run says afterwards is an answer about work that was stopped\n let abandoned = false;\n const isCurrent = () =>\n !abandoned && runs.run === run && field.validationEpoch === epoch && !startedIn?.rolledBack;\n\n // work a validation function commissions is cancelled at the moment its verdict stops counting, which is the\n // moment isCurrent turns false; a run whose verdict still counts is left alone\n const controller = new AbortController();\n const abandon = () => {\n if (isCurrent()) return;\n abandoned = true;\n if (runs.abandon === abandon) runs.abandon = undefined;\n controller.abort();\n };\n // this run holds the newest number now, so the one it replaces is no longer current and its signal aborts\n superseded?.();\n\n // an element that is sent nowhere is not checked: the run reaches no verdict and withdraws this validator's\n // errors\n const errors = field[SentNowhere]() ? [] : validationFn(newValue, oldValue, field, controller.signal) || [];\n\n // the swap of this validator's errors and the verdict that follows from it are one change: a run that\n // settles after the operation that started it opens a transaction of its own here, and one that settles\n // during it joins the transaction already open\n const processErrors = (err: ValidationFunctionResult) =>\n transaction(() => {\n const mine = err?.map((e) => this.claim(e)) ?? [];\n for (let i = field.errors.length - 1; i >= 0; i--) {\n const error = field.errors[i] as ValidationError & SourceProp;\n if (error.source === this.source) {\n const idx = mine.findIndex((e) => e.sameAs(error));\n if (idx >= 0) mine.splice(idx, 1);\n else field.errors.splice(i, 1);\n }\n }\n\n if (mine.length > 0) field.errors.push(...mine);\n field.validate(); // Update the field's valid state\n });\n\n if (errors instanceof Promise) {\n // a run that has not reached its verdict is the only one there is anything left to cancel, and an unwound\n // transaction takes back the very change this run is examining\n runs.abandon = abandon;\n startedIn?.whenRolledBack(abandon);\n field.beginValidating();\n errors\n .then(\n (err) => {\n if (isCurrent()) processErrors(err);\n },\n (reason) => {\n // a rejection reaches no verdict, and no verdict may not read as a pass: this validator's errors are\n // replaced by the single failure error, so the field is invalid while the value is unchecked and the\n // form cannot be submitted on it. The error carries this validator's own source stamp, so the next\n // successful run of the same validator withdraws it like any other error of its own. The reason never\n // reaches the user, whose message says only that the check did not complete, so it is logged.\n if (isCurrent()) {\n processErrors([new ValidationErrorRenderContent(validationFailedMessage(), '', 'validation-failed')]);\n console.error('Validation failed', reason);\n }\n },\n )\n .finally(() => {\n if (runs.abandon === abandon) runs.abandon = undefined;\n field.endValidating();\n })\n // applying a verdict fires ValidChangedAction, so a handler that throws would leave this chain\n // rejected with nowhere to report it\n .catch((error) => console.error('Validation failed', error));\n } else processErrors(errors);\n return supr(field, newValue, oldValue); // Continue the action chain\n };\n\n super(executor);\n\n // Create a unique symbol for this validator instance\n this.source = Symbol(this.constructor.name);\n }\n\n /**\n * Returns the error instance this validator owns and may later withdraw: the argument itself when it carries no\n * ownership stamp or already carries this validator's, a copy of it when it belongs to another validator. The\n * stamp is not configurable, so an instance one validator owns can never be reassigned to another; the copy is\n * what makes an error instance shareable between validators, and it keeps the prototype and every own property,\n * including the non-enumerable ones, so it renders exactly like the instance it was made from.\n */\n private claim(error: ValidationError): ValidationError {\n const owner = (error as ValidationError & Partial<SourceProp>).source;\n if (owner === this.source) return error;\n\n const stamp: PropertyDescriptor = { value: this.source, enumerable: false, configurable: false };\n if (owner === undefined) {\n Object.defineProperty(error, 'source', stamp);\n return error;\n }\n const descriptors = Object.getOwnPropertyDescriptors(error) as Record<string, PropertyDescriptor>;\n return Object.create(Object.getPrototypeOf(error), { ...descriptors, source: stamp });\n }\n\n static get classIdentifier() {\n return ValidatorClassIdentifier;\n }\n\n get eager() {\n return true;\n }\n\n /**\n * Takes this validator off `field`: the errors it put there are withdrawn and the verdict is re-formed over what\n * the validators the field still holds have to say. Withdrawing them is what keeps a field from staying invalid\n * on an error no validator is left to take back.\n *\n * A run in flight over the field is cancelled once the removal stands, and not before: a transaction that\n * unwinds puts the validator and its epoch back, and the run it never cancelled goes on to reach the verdict the\n * field is then owed. Cancelling it as the removal is made would leave the field reporting itself valid over a\n * value nothing checked, on the strength of a transaction that never happened.\n */\n unregisterFrom(field: FieldBase) {\n transactional((tx) => {\n tx.whenCommitted(() => this.abandonRun(field));\n for (let i = field.errors.length - 1; i >= 0; i--) {\n if ((field.errors[i] as ValidationError & SourceProp).source === this.source) field.errors.splice(i, 1);\n }\n field.validate();\n });\n }\n\n /**\n * Cancels the asynchronous run in flight over `field`, where there is one. It is called once the field has\n * stopped holding this validator: the field's validation epoch has moved on by then, so the run's verdict is\n * already dropped and the signal it handed its check aborts with it.\n */\n protected abandonRun(field: FieldBase): void {\n this.bindingState(field).abandon?.();\n }\n\n /**\n * What this validator remembers about one of the fields it validates. One instance may be registered on several\n * fields - every row of a list carries the instances the item template carries - so each field has a record of\n * its own. A subclass that remembers more widens the record by overriding `newBindingState`.\n */\n protected bindingState(field: FieldBase<any>): ValidatorBindingState {\n return this.state(field, () => this.newBindingState());\n }\n\n /**\n * The record a field starts with. `run` is the sequence number of the newest run over that field: every\n * execution takes the next one and a result is applied only while its number is still the newest, so a slow run\n * cannot overwrite the verdict of a faster one that started after it.\n */\n protected newBindingState(): ValidatorBindingState {\n return { run: 0 };\n }\n\n protected replacePlaceholdersFunction(text: RenderContentRef, replace: Record<string, any>): RenderContentRef {\n return () => {\n let ret = unref(text);\n while (isCallableFunction(ret)) {\n ret = unref(this.replacePlaceholders(ret(), replace));\n }\n return ret;\n };\n }\n\n protected replacePlaceholders(text: RenderContentRef, replace: Record<string, any>): RenderContentRef {\n if (isCallableFunction(text)) return this.replacePlaceholdersFunction(text, replace);\n\n if (isSimpleComponentDef(text)) return text;\n // a Ref is resolved on read, not here: substituting once would freeze the message at the value the reference\n // held during validation, and a translated message would stay in the language that was active back then\n if (isRef(text)) {\n return this.replacePlaceholdersFunction(() => unref(text) as RenderContentNonCallable, replace);\n }\n const ret = unref(text) as string | MdString;\n const substituted = interpolate(ret.toString(), replace);\n return ret instanceof MdString ? new MdString(substituted, ret.options, ret.plugins) : substituted;\n }\n}\n","import { type FieldBase } from '../field-base';\nimport { AbortEventHandlingException } from '../field.interface';\nimport { Validator } from '../validators/validator';\n\nimport FieldActionBase from './field-action-base';\n\n/**\n * The actions one declaration has registered, in registration order. A trigger walks them from the end backwards\n * and passes over the ones registered under another identifier, so the newest registration of an identifier is its\n * outermost handler and reaches the ones before it through the `supr` it is handed. A handler that does not call\n * `supr` ends the run there, and one that calls it may transform what it answers with.\n *\n * The order is the whole index. An element carries a handful of actions, and a walk over that many is cheaper than\n * a keyed lookup as well as smaller: measured over three actions, the walk is about twice as fast as `Map.get` and\n * the two maps it replaces cost about 500 bytes per declaration.\n */\nexport default class ActionsMap {\n /**\n * Every action registered here, in registration order. It is replaced rather than written when an action is\n * dropped, so a run already walking it finishes on the array it started with and the removal takes effect from\n * the next trigger.\n */\n private actions: FieldActionBase[] = [];\n\n /**\n * Registers `action`. It becomes the outermost handler of its identifier, or - where `before` is given and is\n * registered here under the same identifier - takes that action's place in the order, so `before` wraps it and\n * reaches it through `supr`. That is what lets an action be added to a chain someone else built and still sit\n * inside a handler already there.\n */\n register(action: FieldActionBase, before?: FieldActionBase): void {\n if (!(action instanceof FieldActionBase)) throw new Error('Invalid action type');\n const at = before ? this.actions.indexOf(before) : -1;\n if (before && (before.classIdentifier !== action.classIdentifier || at < 0)) {\n throw new Error('Action to register before is not registered under the same identifier');\n }\n if (at < 0) this.actions.push(action);\n else this.actions.splice(at, 0, action);\n }\n\n /** Drops `action` and answers whether it was registered here. */\n unregister(action: FieldActionBase): boolean {\n if (!this.actions.includes(action)) return false;\n this.actions = this.actions.filter((registered) => registered !== action);\n return true;\n }\n\n /** True where something is registered under `identifier`. */\n willTrigger(identifier: symbol): boolean {\n return this.actions.some((action) => action.classIdentifier === identifier);\n }\n\n /** True where any eager action is registered, whatever identifier it stands under. */\n get hasEager(): boolean {\n return this.actions.some((action) => action.eager);\n }\n\n /** Runs the actions registered under `ActionClass` and answers with what the outermost of them returned. */\n trigger<T extends FieldActionBase>(\n ActionClass: (abstract new (...args: any[]) => T) & { classIdentifier: symbol },\n field: FieldBase,\n ...params: any[]\n ): any {\n return this.run(ActionClass.classIdentifier, false, field, params);\n }\n\n /**\n * Runs the eager actions of every identifier, each group on its own. A group is entered at its outermost eager\n * action, which is the last one registered under that identifier.\n */\n triggerEager(field: FieldBase, ...params: any[]): void {\n const actions = this.actions;\n for (let index = actions.length - 1; index >= 0; index--) {\n const action = actions[index];\n if (!action.eager) continue;\n // the group is entered once, at the outermost of its eager actions; the ones below are reached through supr\n if (ActionsMap.outermostEager(actions, index)) {\n try {\n const result = this.walk(actions, index, action.classIdentifier, true, field, params);\n // an abort out of an asynchronous handler arrives as a rejection, which the catch below never sees; ending\n // it here is what keeps it from being reported as unhandled. Any other rejection stays the runtime's.\n if (ActionsMap.isPromise(result)) {\n result.then(undefined, (error: unknown) => {\n if (!(error instanceof AbortEventHandlingException)) throw error;\n });\n }\n } catch (error) {\n // one eager group ending its run says nothing about the others, which are separate rules\n if (!(error instanceof AbortEventHandlingException)) throw error;\n }\n }\n }\n }\n\n /** Runs the eager actions registered under `identifier` and nothing else. */\n triggerEagerFor(identifier: symbol, field: FieldBase, ...params: any[]): any {\n return this.run(identifier, true, field, params);\n }\n\n /** the validators registered here, in registration order */\n get validators(): Validator[] {\n return this.actions.filter((action): action is Validator => action instanceof Validator);\n }\n\n /**\n * Tells every action here that it serves `owner`. A binding reads the map its declaration holds, so this is what\n * announces the new element to the actions already in it - the way registering an action announces the elements\n * it comes to serve.\n */\n bindTo(owner: FieldBase): void {\n this.actions.forEach((action) => action.boundToBinding(owner));\n }\n\n /** True where no eager action of `identifier` stands after `index`, which makes `index` the group's entry. */\n private static outermostEager(actions: FieldActionBase[], index: number): boolean {\n const identifier = actions[index].classIdentifier;\n for (let above = actions.length - 1; above > index; above--) {\n if (actions[above].eager && actions[above].classIdentifier === identifier) return false;\n }\n return true;\n }\n\n /**\n * True where `value` is a promise, which is what a walk through an asynchronous handler answers with. The test is\n * the type rather than a `then` member: a handler may answer with a value object that carries one, and calling\n * `then` on such an object replaces the answer with whatever that call returns.\n */\n private static isPromise(value: any): value is Promise<any> {\n return value instanceof Promise;\n }\n\n /**\n * Answers an abort with itself on the asynchronous path as well. Where a handler in the chain is asynchronous, the\n * walk answers with a promise and the abort raised under it arrives as that promise's rejection; this turns it back\n * into the value the caller receives, so a promise the trigger answers with resolves to the exception instead of\n * rejecting with it. Anything else keeps rejecting.\n */\n private static answerAbort(value: any): any {\n if (!ActionsMap.isPromise(value)) return value;\n return value.then(undefined, (error: unknown) => {\n if (error instanceof AbortEventHandlingException) return error;\n throw error;\n });\n }\n\n /**\n * Enters a group at its outermost action. An abort ends the run and is answered with rather than raised: the\n * exception is what the caller receives - directly where the chain ran synchronously, as what the answered promise\n * resolves to where it did not - so a run a handler ended is told apart from one that reached no handler and from\n * one whose handler answered null.\n */\n private run(identifier: symbol, eagerOnly: boolean, field: FieldBase, params: any[]): any {\n const actions = this.actions;\n try {\n return ActionsMap.answerAbort(this.walk(actions, actions.length - 1, identifier, eagerOnly, field, params));\n } catch (error) {\n if (error instanceof AbortEventHandlingException) return error;\n throw error;\n }\n }\n\n /**\n * Walks from `index` backwards to the first action of `identifier`, handing it a `supr` that continues at the one\n * before it. The actions registered under other identifiers are passed over, so the array needs no grouping of\n * its own; the closures exist for the length of the run and only as deep as the run actually goes.\n */\n private walk(\n actions: FieldActionBase[],\n index: number,\n identifier: symbol,\n eagerOnly: boolean,\n field: FieldBase,\n params: any[],\n ): any {\n let at = index;\n while (at >= 0 && (actions[at].classIdentifier !== identifier || (eagerOnly && !actions[at].eager))) at--;\n if (at < 0) return null;\n const supr = (next: FieldBase, ...rest: any[]) => this.walk(actions, at - 1, identifier, eagerOnly, next, rest);\n return actions[at].execute(field, supr, ...params);\n }\n}\n","import type { FieldBase } from '../field-base';\nimport type { Group } from '../group';\n\n/**\n * Resolution of one element against another element's record.\n *\n * An action instance is shared: every row a `List` builds from an item template carries the instances the template\n * carries, and what differs per row is the data. An action that reads a second element - a statement comparing two\n * fields, a validator comparing a password with its confirmation - therefore has to be told which second element it\n * means for the row it is running over, and the structure is what tells it: the element the action was declared\n * against, and the record it is running in, name it between them.\n */\n\n/**\n * The record an element belongs to: the `List` row that holds it, or the top of its container chain where no row\n * does. A container holds a row without a name and a `Group` names every member, so the element whose container\n * gave it no name is where a record begins.\n */\nexport function scopeOf(element: FieldBase): FieldBase {\n let current = element;\n while (current.fieldName !== undefined && current.parent) current = current.parent;\n return current;\n}\n\n/**\n * The member of `record` that was declared as `declaration`, and `undefined` where the record holds none. The path\n * of names is what locates it: the record is walked down the same names that lead from the declaration's own record\n * to the declaration itself.\n */\nfunction memberOf(record: FieldBase, declaration: FieldBase): FieldBase | undefined {\n let resolved: FieldBase | undefined = record;\n for (const name of pathOf(declaration)) {\n resolved = (resolved as Group).field?.(name) ?? undefined;\n if (!resolved) return undefined;\n }\n return resolved?.declaration === declaration ? resolved : undefined;\n}\n\n/** The names leading from an element's record down to the element itself. */\nfunction pathOf(element: FieldBase): string[] {\n const path: string[] = [];\n let current = element;\n while (current.fieldName !== undefined && current.parent) {\n path.unshift(current.fieldName);\n current = current.parent;\n }\n return path;\n}\n\n/**\n * The element `declaration` stands for within `scope`. It is the member `scope` holds at the same position, where\n * that member was declared as `declaration`; `declaration` itself, where it belongs to a record other than\n * `scope`'s and is therefore the one element every record reads - a form field above a list, or a field of another\n * row named on purpose; and `undefined`, where `scope` is a record of the same kind that has yet to be built,\n * which says that the question has to be asked again once it is.\n */\nexport function resolveInScope(declaration: FieldBase, scope: FieldBase): FieldBase | undefined {\n const withinRecord = memberOf(scope, declaration);\n if (withinRecord) return withinRecord;\n\n // the record holds no member declared as this element, so it belongs to a record further out. A list nested in a\n // row makes that record one per row - an order's total, read by the lines of that order - so the containers are\n // asked in turn before the element is taken for one every record reads alike\n let enclosing = scope.parent;\n while (enclosing) {\n const bound = memberOf(scopeOf(enclosing), declaration);\n if (bound) return bound;\n enclosing = enclosing.parent;\n }\n\n // nothing above holds a binding of it either. Either it is the one element every record reads - a form field\n // above a list - or the record is one of the same family and is still being assembled\n return scopeOf(declaration) === scopeOf(scope.declaration) ? undefined : declaration;\n}\n\n/**\n * Every element `declaration` stands for when something changes in `scope`. It is the one member of that record\n * where the record holds one; where the element belongs to a record above - a form field the rows of a list read -\n * it is each of its bindings inside `scope`, because a change there speaks for every one of them; and where\n * `scope` reaches no binding at all, it is the element itself, which is the answer for a form that has no records\n * below it.\n * A record still being assembled reaches none of these and answers with nothing, so the assignment that finishes\n * it asks again.\n */\nexport function bindingsIn(declaration: FieldBase, scope: FieldBase): FieldBase[] {\n const resolved = resolveInScope(declaration, scope);\n if (!resolved) return [];\n if (resolved !== declaration) return [resolved];\n const found = scope.bindingsOf(declaration);\n return found.length > 0 ? found : [declaration];\n}\n\n/**\n * The element named `name` in the nearest container above `element` that holds one, and `undefined` where no\n * container does. A row is searched before the form the list sits in, so a rule written against a name reads the\n * row it is running over.\n */\nexport function resolveByName(name: string, element: FieldBase): FieldBase | undefined {\n let container = element.parent;\n while (container) {\n const member = (container as Group).field?.(name);\n if (member) return member;\n container = container.parent;\n }\n return undefined;\n}\n","import type { Access } from '../../access';\nimport { bindingsIn, scopeOf } from '../../binding/resolve';\nimport { type FieldBase } from '../../field-base';\nimport { FieldActionExecute } from '../../field.interface';\nimport type { Visibility } from '../../visibility';\nimport { ValueChangedAction } from '../value-changed-action';\n\nimport { Statement } from './statement';\n\nconst ConditionalStatementActionClassIdentifier = Symbol('ConditionalStatementAction');\n\ntype ConditionalExecutorFn = (field: FieldBase, currentResult: boolean, previousResult: boolean | undefined) => void;\n\n/** What the action remembers about one record: the result the record's fields last produced. */\ninterface ConditionalRecordState {\n lastResult: boolean | undefined;\n}\n\nexport class ConditionalStatementAction extends ValueChangedAction {\n private readonly statement: Statement;\n\n private readonly conditionalExecutor: ConditionalExecutorFn;\n\n /**\n * What the elements this action was registered on were declared as. It holds declarations rather than the\n * elements themselves, so one entry stands for every row of a list, and the element a result is applied to is\n * the one that declaration names within the record the change happened in.\n */\n private readonly declarations = new Set<FieldBase>();\n\n /**\n * The elements this action was registered on. Registration reaches one element at a time - the rows of a list\n * take the action on one by one, as they are built from the item template that carries it - so this is what\n * says which of the elements a declaration stands for the action actually drives.\n */\n private readonly registrations = new WeakSet<FieldBase>();\n\n constructor(statement: Statement, executorFn: ConditionalExecutorFn) {\n // the element the action fires for names the record: an eager pass over one row's field re-evaluates that\n // row's fields and reaches that row's targets. A pass that reaches none of them is running over an element\n // whose record is still being built, and the container that finishes it runs the pass again\n super((field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => {\n if (!this.applyIn(scopeOf(field))) field.markRecordIncomplete();\n return supr(field, newValue, oldValue);\n });\n\n this.statement = statement;\n this.conditionalExecutor = executorFn;\n\n // one listener per field the statement reads, however many records that field ends up having: the listener\n // receives the field that changed, which is what says which record to re-evaluate. Registering per record\n // instead would grow the field's handler chain by one link for every row a list holds.\n const relay = new ValueChangedAction((source: FieldBase, supr: FieldActionExecute, ...params: any[]) => {\n this.applyFrom(source);\n return supr(source, ...params);\n });\n statement.collectFields().forEach((field) => field.registerAction(relay));\n }\n\n static get classIdentifier() {\n return ConditionalStatementActionClassIdentifier;\n }\n\n get eager() {\n return true;\n }\n\n boundToBinding(binding: FieldBase) {\n this.declarations.add(binding.declaration);\n this.registrations.add(binding);\n }\n\n unregisterFrom(binding: FieldBase) {\n this.registrations.delete(binding);\n }\n\n /**\n * The elements of `scope` this action controls: what each declaration it serves names within that record, and of\n * those the ones that took the action on. A row of a list that never took it on is not one this action drives.\n */\n private targetsIn(scope: FieldBase): FieldBase[] {\n const targets: FieldBase[] = [];\n this.declarations.forEach((declaration) =>\n bindingsIn(declaration, scope).forEach((target) => {\n if (this.registrations.has(target)) targets.push(target);\n }),\n );\n return targets;\n }\n\n /**\n * Re-evaluates the statement over one record and applies the result where it changed. The result is recorded\n * before the executor runs, because an executor that writes a value re-enters through that value's eager pass\n * and what it has to find there is the result being applied. It answers whether the record held anything for\n * this action to drive, which is how a caller learns that the record is not assembled yet.\n */\n private applyIn(scope: FieldBase): boolean {\n const targets = this.targetsIn(scope);\n if (targets.length === 0) return false;\n const state = this.state(scope, (): ConditionalRecordState => ({ lastResult: undefined }));\n const currentResult = this.statement.evaluate(scope);\n if (currentResult === state.lastResult) return true;\n const previousResult = state.lastResult;\n state.lastResult = currentResult;\n targets.forEach((target) => this.conditionalExecutor(target, currentResult, previousResult));\n return true;\n }\n\n /**\n * Re-evaluates the records a change of `source` speaks for. A field of the record the targets live in speaks for\n * that record alone, which is what keeps one row of a list from answering for another; a field above them - a\n * form field every row reads - speaks for every record below it, and for the record the action was declared in\n * where the change reaches none.\n */\n private applyFrom(source: FieldBase): void {\n const scopes = new Set<FieldBase>();\n this.targetsIn(scopeOf(source)).forEach((target) => scopes.add(scopeOf(target)));\n scopes.forEach((scope) => this.applyIn(scope));\n }\n}\n\n// Derived classes for visibility, access, and value changes\n\n/**\n * Sets the visibility of the elements it is registered on from the statement's result: `whenTrue` while the\n * statement holds, `whenFalse` otherwise. Visibility is presentation alone, so what the elements send is left to\n * their access.\n */\nexport class ConditionalVisibilityAction extends ConditionalStatementAction {\n constructor(statement: Statement, whenTrue: Visibility = 'full', whenFalse: Visibility = 'suppress') {\n super(statement, (field: FieldBase, currentResult) => {\n field.visibility = currentResult ? whenTrue : whenFalse;\n });\n }\n}\n\n/**\n * Sets the access of the elements it is registered on from the statement's result: `whenTrue` while the statement\n * holds, `whenFalse` otherwise.\n */\nexport class ConditionalAccessAction extends ConditionalStatementAction {\n constructor(statement: Statement, whenTrue: Access = 'editable', whenFalse: Access = 'disabled') {\n super(statement, (field, currentResult) => {\n field.access = currentResult ? whenTrue : whenFalse;\n });\n }\n}\n\nexport class ConditionalValueAction<T> extends ConditionalStatementAction {\n constructor(statement: Statement, trueValue: T) {\n super(statement, (field, currentResult) => {\n if (currentResult) field.value = trueValue;\n });\n }\n}\n","/**\n * Operators provides us a functionality for backend to send us complex condition upon which we send\n * dynamic visibility prop for form input fields\n */\nenum Operator {\n // Logic Operators\n NOT = 0,\n OR = 1,\n AND = 2,\n XOR = 3,\n NAND = 4,\n NOR = 5,\n\n // Comparators (comparison operators)\n EQUALS = -1,\n NOT_EQUALS = -2,\n GT = -3,\n LT = -4,\n GE = -5,\n LE = -6,\n IN = -7,\n NOT_IN = -8,\n INCLUDES = -9,\n NOT_INCLUDES = -10,\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, no-redeclare\nnamespace Operator {\n export function fromString(operator: string): Operator {\n const op = operator.toLowerCase();\n if (op === 'not') return Operator.NOT;\n if (op === 'or') return Operator.OR;\n if (op === 'and') return Operator.AND;\n if (op === 'xor') return Operator.XOR;\n if (op === 'nand') return Operator.NAND;\n if (op === 'nor') return Operator.NOR;\n\n if (op === 'equals') return Operator.EQUALS;\n if (['not_equals', 'not-equals', 'not equals'].includes(op)) return Operator.NOT_EQUALS;\n if (op === 'gt') return Operator.GT;\n if (op === 'lt') return Operator.LT;\n if (op === 'ge') return Operator.GE;\n if (op === 'le') return Operator.LE;\n if (op === 'in') return Operator.IN;\n if (['not_in', 'not-in', 'not in'].includes(op)) return Operator.NOT_IN;\n if (op === 'includes') return Operator.INCLUDES;\n if (['not_includes', 'not-includes', 'not includes'].includes(op)) return Operator.NOT_INCLUDES;\n throw new Error(`Unrecognised operator ${op}`);\n }\n\n export function fromAny(mode: any): Operator {\n const input = typeof mode === 'number' ? mode : Operator.fromString(mode as string);\n if (Object.values(Operator).includes(input)) return input;\n throw new Error(`Unrecognised operator ${mode}`);\n }\n\n export function isDefined(operator: number | string): boolean {\n const check = typeof operator === 'number' ? operator : Operator.fromString(operator as string);\n return Object.values(Operator).includes(check);\n }\n\n // c8 bug: it doesn't matter what there is in the next line (e.g. console.log()).\n // it will always be a branch with one branch not covered\n export function isLogicOperator(operator: Operator): boolean {\n return operator >= 0;\n }\n}\n\nObject.freeze(Operator);\n\nexport default Operator;\n","import FieldActionBase from './field-action-base';\n\nimport type { Access } from '@/access';\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst AccessChangingActionClassIdentifier = Symbol('AccessChangingAction');\n\n/**\n * Asked before an element's `access` is written. A handler answers with the access to write instead, or throws\n * `AbortEventHandlingException` to refuse the write.\n */\nexport class AccessChangingAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access) => Access) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return AccessChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access): Access {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst AccessChangedActionClassIdentifier = Symbol('AccessChangedAction');\n\n/** Told once an element's `access` has been written. */\nexport class AccessChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return AccessChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nexport const ContributionChangedActionClassIdentifier = Symbol('ContributionChangedAction');\n\n/**\n * Told what an element contributes to its container's `value` once that changed over a transaction: the element's\n * value where its access sends it, `null` for `'disabled-null'`, and `undefined` for `'disabled'`, whose key or row\n * is left out. The pair carried is (contribution now, contribution at the last announcement).\n *\n * It answers a different question from `ValueChangedAction`, which reports what the element holds. A write into a\n * `'disabled'` field changes what the field holds and not what it sends, so it fires `ValueChangedAction` alone;\n * switching a field's access changes what it sends and not what it holds, so it fires this action alone. On a\n * container, what it holds is its `fullValue` and what it sends is its `value`, so a change of a member's access\n * reaches the containers above as a change of their contribution, never of their value.\n */\nexport class ContributionChangedAction<T = any> extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: unknown, oldValue: unknown) => void,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ContributionChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: unknown, oldValue: unknown): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst EnabledChangingActionClassIdentifier = Symbol('EnabledChangingAction');\n\n/**\n * Asked before a write of `access` that would change `enabled`: a switch into or out of `'editable'`. It is asked\n * after `AccessChangingAction`, over the access that would be written. `enabled` is read from `access`, so the\n * answer cannot set it: answering with the value `enabled` has now, or throwing `AbortEventHandlingException`,\n * refuses the write of `access`, and answering with the new value, `null` or `undefined` lets it through.\n */\nexport class EnabledChangingAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => boolean,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return EnabledChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): boolean {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst EnabledChangedActionClassIdentifier = Symbol('EnabledChangedAction');\n\n/**\n * Told once a write of `access` changed `enabled`: a switch into or out of `'editable'`. It fires after\n * `AccessChangedAction`, and a switch between two accesses that are not `'editable'` does not fire it.\n */\nexport class EnabledChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return EnabledChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ValidChangedActionClassIdentifier = Symbol('ValidChangedAction');\n\nexport class ValidChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ValidChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\nimport type { Visibility } from '@/visibility';\n\nconst VisibilityChangingActionClassIdentifier = Symbol('VisibilityChangingAction');\n\nexport class VisibilityChangingAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility) => Visibility,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return VisibilityChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility): Visibility {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst VisibilityChangedActionClassIdentifier = Symbol('VisibilityChangedAction');\n\nexport class VisibilityChangedAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility) => void,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return VisibilityChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import { isEmpty, isEqual } from 'lodash-es';\nimport { reactive, watch } from 'vue';\n\nimport { type Access, accessValues, isAccess } from './access';\nimport { AccessChangedAction, AccessChangingAction } from './actions/access-actions';\nimport ActionsMap from './actions/actions-map';\nimport {\n ContributionChangedAction,\n ContributionChangedActionClassIdentifier,\n} from './actions/contribution-changed-action';\nimport { EnabledChangedAction, EnabledChangingAction } from './actions/enabled-actions';\nimport FieldActionBase from './actions/field-action-base';\nimport { ValidChangedAction } from './actions/valid-changed-action';\nimport { ValueChangedAction, ValueChangedActionClassIdentifier } from './actions/value-changed-action';\nimport { VisibilityChangedAction, VisibilityChangingAction } from './actions/visibility-actions';\nimport { type Container } from './container';\nimport { type ElementSlots } from './element-state';\nimport { AbortEventHandlingException, type Extras, IBindParams } from './field.interface';\nimport {\n currentTransaction,\n type Transaction,\n SentNowhere,\n TxAnnounceValue,\n TxCapture,\n TxRestore,\n TxSettleValidity,\n type TxSnapshot,\n type TxStructuralEvent,\n transactional,\n} from './transaction';\nimport { ValidationError } from './validators/validation-error';\nimport { Validator } from './validators/validator';\nimport { isVisibility, type Visibility, visibilityValues } from './visibility';\n\n/**\n * The bindings made from a declaration, held outside it and weakly: a binding is released with the record it\n * belongs to, and the declaration must not be what keeps it alive. It is what lets a rule registered on an item\n * template reach the rows that already exist - the declaration has no other way to name them.\n */\nconst bindingsMade = new WeakMap<object, Set<WeakRef<FieldBase>>>();\n\n/**\n * The parameter keys that name what to register on an element rather than what it holds. The constructor that\n * receives them registers them and applies the rest, and `bind()` hands its overrides over whole, so they are\n * named here to keep them out of both the element's members and its extended properties.\n */\nconst registrationParams: ReadonlySet<string> = new Set(['validators', 'actions']);\n\n/** a value as an error message names it: a string quoted, anything else as it prints */\nconst describe = (value: unknown) => (typeof value === 'string' ? `'${value}'` : String(value));\n\n/** the accepted values as an error message lists them */\nconst listOf = (values: readonly string[]) => values.map(describe).join(', ');\n\n/**\n * Refuses a parameter object naming `enabled`. `enabled` is read from `access` and has no setter, and a parameter\n * object that reaches an element past the type system - parsed from JSON, typed `any` - would otherwise have it\n * dropped by `bind()` or rejected with a TypeError that does not say what to write instead.\n */\nfunction refuseEnabled(params: object): void {\n if (Object.hasOwn(params, 'enabled')) {\n throw new TypeError(\n `enabled is read from access and cannot be assigned; state access instead: ${listOf(accessValues)}`,\n );\n }\n}\n\n/**\n * How many elements are waiting for the record they belong to. A container that completes a record asks this\n * before it walks anything, so a form built out of elements that answer for themselves alone pays nothing for\n * the mechanism.\n */\nlet incompleteRecords = 0;\n\nexport abstract class FieldBase<T = any, X extends object = Extras> {\n /**\n * Vue's getTargetType answers INVALID for an object that carries __v_skip, so reactive() hands an element back\n * unwrapped and no element is ever behind a proxy of its own. isReactive() reads the second flag, and it stays\n * true because what carries an element's reactivity - its state - is a reactive object.\n *\n * Two consequences for a consumer, both silent. watch(field, cb) with a bare element as the source registers\n * no dependency, because the deep traversal Vue starts for a reactive source stops on __v_skip; the supported\n * form is watch(() => field.value, cb). And readonly(field) hands the element straight back, so the value it\n * returns is the element itself and a write through it reaches the field; what a caller hands out instead is\n * the value, which is frozen, or a computed over it.\n */\n get __v_skip(): boolean {\n return true;\n }\n\n get __v_isReactive(): boolean {\n return true;\n }\n\n /**\n * Names the element's class, which is what a structural comparison of two elements answers on. An element keeps\n * its state in private class fields, so a walk over own keys reaches none of it; lodash reads this tag through\n * Object.prototype.toString before it compares anything, and a tag it does not know ends the comparison there.\n * Two elements are therefore equal only where they are the same element. What they hold is compared as\n * isEqual(a.value, b.value).\n *\n * It is an accessor on the prototype, so an element carries nothing for it, and `Object.prototype.toString`\n * answers `[object Field]` rather than `[object Object]`. Each class states its own name as a literal: a\n * minifier renames the class itself, so reading the constructor's name would report whatever the build called\n * it.\n */\n get [Symbol.toStringTag](): string {\n return 'FormElement';\n }\n\n /**\n * The element's mutable state, in an object beside the element. `#state` is the tracked view of it: a slot read\n * through it inside an effect subscribes the effect to that slot, and a write to the slot re-runs the effect.\n * `#raw` is the same object without the proxy, for the bookkeeping nothing renders from.\n *\n * They are private class fields, so no reflection over the element reaches the state or the parent link it\n * carries, and a subclass reads its own slot type through the accessors below.\n */\n readonly #state: ElementSlots<T>;\n\n readonly #raw: ElementSlots<T>;\n\n constructor(slots: ElementSlots<T>) {\n this.#raw = slots;\n this.#state = reactive(slots) as ElementSlots<T>;\n }\n\n /** the tracked view of this element's state; a subclass narrows the return type to its own slots */\n protected get state(): ElementSlots<T> {\n return this.#state;\n }\n\n /** the untracked view of this element's state; a subclass narrows the return type to its own slots */\n protected get raw(): ElementSlots<T> {\n return this.#raw;\n }\n\n abstract get value(): T;\n abstract set value(newValue: T);\n\n abstract get touched(): boolean;\n abstract set touched(touched: boolean);\n\n /**\n * A new element of this one's class over `data`: same class, same registered actions, same extended properties,\n * and the change history starting over. It is how a declaration is put to work over a record - every row a\n * `List` builds is its item template bound to that row's data - and the element it is called on is what the new\n * one answers `declaration` with.\n *\n * `data` of `undefined` is no data supplied and the new element carries what this one holds; an explicit `null`\n * is data and clears. `overrides` states the rest: `originalValue` is read by key presence, `access` and\n * `visibility` fall back to this element's, and extended properties it names are written over the ones carried\n * over. The new element is detached - no `parent`, no `fieldName` - so it is free to be taken by a container.\n */\n abstract bind(data?: T, overrides?: IBindParams<T, X>): FieldBase<T, X>;\n\n /**\n * Exchanges the data this element holds for `data`, in place. The element is the same instance afterwards - its\n * identity, its actions, its extended properties and its place in whatever container holds it all stand - and it\n * ends up in the state `bind(data)` would have produced: the values are written, the change history starts over\n * and the validators run. It is what recycles one element across records, which is what a virtualised renderer\n * does with the rows it keeps.\n *\n * The element makes no statement of its own about the exchange: no `ValueChangedAction` fires for it, the way\n * none fires for an element that was just built. Its members do announce theirs, and a verdict that moves is\n * announced as always - a rebound element that is invalid says so to the container holding it. A change an\n * open transaction is already owed an announcement for stands: the commit reports the pair measured from\n * where the element was when the transaction opened.\n *\n * The data is measured against the element's `declaration`, so a key a record leaves out is taken from the\n * declaration rather than left as the previous record had it.\n */\n rebind(data: T): this {\n transactional((tx) => {\n tx.touch(this);\n // the baseline of a change the transaction has yet to announce stays where it is: the element is already\n // enrolled to report that change, and moving the baseline to the record it ends up over would erase the\n // report. Both are read before the reset, which enrols the element itself and, on a container, writes the\n // baseline of its own.\n const owed = tx.willAnnounceValue(this);\n const { announcedValue, announcedContribution, validatedValue } = this.#raw;\n this.resetTo(this.declaration, data);\n // with nothing owed, what the element now holds and sends is recorded as announced, so the commit reports no\n // change of either for it\n if (owed) Object.assign(this.#raw, { announcedValue, announcedContribution, validatedValue });\n else this.recordAnnounced();\n });\n return this;\n }\n\n /** contains original field value as was provided at creation */\n get originalValue(): T {\n return this.#state.originalValue;\n }\n\n set originalValue(newValue: T) {\n this.touchState();\n this.#state.originalValue = newValue;\n }\n\n /**\n * The extended properties this element carries: what a consumer attached to it beyond the members the class\n * declares, such as the label, hint or css class a UI layer binds to the input it renders the element with.\n * The read is tracked, so a template rendering off `field.extra.label` re-renders when the property is written.\n *\n * Every property is optional here, whatever `X` states: a parameter object need not carry one and\n * setExtendedValues writes as few as a caller likes, so a property `X` declares as required is present only\n * once something has written it.\n *\n * The object is frozen and setExtendedValues is the way to change it: it is the object a transaction captured,\n * and one written in place would leave a rollback with nothing to put back.\n */\n get extra(): Readonly<Partial<X>> {\n return this.#state.extra as Readonly<Partial<X>>;\n }\n\n /**\n * Writes extended properties. The values given are merged over the ones the element carries, so a write of one\n * property leaves the others standing, and the merged set replaces the object the element held.\n */\n setExtendedValues(values: Partial<X>): void {\n this.touchState();\n this.#state.extra = Object.freeze({ ...this.#raw.extra, ...values });\n }\n\n /**\n * The extended properties a parameter object carries: every key the element does not answer for itself. A key\n * the element answers for at the time the parameters are applied - `value`, `access`, an accessor a subclass\n * adds - is the element's own; a key that only Object.prototype answers for is nobody's declaration and counts\n * as extended, and `validators` and `actions` are neither, since they state what to register on the element.\n *\n * A member a subclass declares as a class field is not among the keys the element answers for: class fields are\n * defined on the instance after the base constructor returns, and the parameters are applied inside it. A\n * subclass that wants a parameter of its own name assigned to it declares that member as an accessor.\n */\n protected extendedOf(params: object): Partial<X> {\n // the accumulator carries no prototype, so a params key of `__proto__` - which is what a parameter object\n // parsed out of JSON can carry - becomes an own property of it instead of reaching the setter Object.prototype\n // holds and replacing the accumulator's prototype, which would make the ownership test below answer for keys\n // nothing put there\n const extended: Record<string, any> = Object.create(null);\n Object.entries(params).forEach(([key, value]) => {\n if (registrationParams.has(key)) return;\n if (!(key in this) || Object.hasOwn(Object.prototype, key)) extended[key] = value;\n });\n return extended as Partial<X>;\n }\n\n /**\n * Applies a parameter object: the members the element answers for are assigned to the element and the rest\n * become its extended properties. Assigning a getter-only member throws a TypeError, which is what a caller\n * naming `valid` or `parent` past the type system gets.\n */\n protected assignParams(params: object): void {\n refuseEnabled(params);\n const extended = this.extendedOf(params);\n Object.entries(params).forEach(([key, value]) => {\n if (Object.hasOwn(extended, key) || registrationParams.has(key)) return;\n (this as any)[key] = value;\n });\n if (!isEmpty(extended)) this.setExtendedValues(extended);\n }\n\n /**\n * Takes this element into the record of the open transaction, where one is open. A write of a single slot that\n * announces nothing calls it instead of opening a transaction of its own: on its own such a write is already\n * atomic, and inside a transaction it has to be part of what a rollback puts back.\n */\n protected touchState(): void {\n currentTransaction()?.touch(this);\n }\n\n /**\n * Records the whole of this element's mutable state, so that a rolled-back transaction can put it back exactly\n * as it found it. The errors array is copied because a validator writes into the array it is handed rather than\n * replacing it, and a subclass copies whatever else it holds by reference the same way.\n *\n * What is not in the snapshot is the action map, which no write touches: an operation that replaces it hands\n * the transaction its own undo instead, so this stays the one shape every element captures.\n */\n protected [TxCapture](): TxSnapshot {\n return { ...this.#raw, errors: [...this.#raw.errors] };\n }\n\n /**\n * Puts a captured state back. It writes through the tracked view, so an effect that ran on the state the\n * transaction produced runs again on the state it is being returned to, and only for the slots that differ.\n *\n * The two validation counters are the slots the element keeps: they count runs that are in flight, and a\n * rollback cannot un-start one. Put back, the counts would no longer match the endValidating calls still to come.\n */\n protected [TxRestore](snapshot: TxSnapshot): void {\n const validating = this.#raw.validatingCount;\n const validatingChildren = this.#raw.validatingChildren;\n Object.assign(this.#state, snapshot);\n this.#state.validatingCount = validating;\n this.#state.validatingChildren = validatingChildren;\n }\n\n /**\n * True while an asynchronous validation is in flight on this element or on anything below it, so a form answers\n * for the whole tree it holds. The answer is a pair of counters rather than a walk: the element's own runs, and\n * how many of its children answer the same question with true. A child that starts running while it was idle,\n * or stops while it was the last one running, moves its container's tally, and a tally that changes the\n * container's own answer moves the one above it - the transition costs the nesting depth and the read costs\n * nothing.\n */\n get validating(): boolean {\n return this.#state.validatingCount > 0 || this.#state.validatingChildren > 0;\n }\n\n /** announces the start of one asynchronous validation run; validators pair it with endValidating */\n beginValidating(): void {\n const wasIdle = !this.validating;\n this.#state.validatingCount++;\n if (wasIdle) this.container?.childValidatingChanged(true);\n }\n\n /** announces the end of one asynchronous validation run */\n endValidating(): void {\n // a stray call is a no-op: the count never goes below zero, and nothing above is told of a stop that the\n // element never started\n if (this.#raw.validatingCount === 0) return;\n this.#state.validatingCount--;\n if (!this.validating) this.container?.childValidatingChanged(false);\n }\n\n /**\n * Records that a child started or stopped answering `validating` with true, and carries the transition further\n * up where it changes this element's own answer. Only a `Container` has children, and it implements this; it is\n * declared here because a child tells its container through it.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected childValidatingChanged(started: boolean): void {}\n\n /**\n * True while an `Action.execute()` at or below this element has yet to settle. An `Action` answers for its own\n * runs; a container answers for the actions below it; anything else answers false, because an element that is\n * not an action has nothing to execute.\n *\n * It states one thing and `validating` states the other, so a form that gates a submit button on the tree being\n * idle reads both.\n */\n get busy(): boolean {\n return false;\n }\n\n /**\n * Resolves once nothing at or below this element is running - no asynchronous validation, no `Action.execute()`\n * that has yet to settle. It is what a submit path awaits instead of polling `validating` and `busy`, and it\n * resolves at once where nothing is running to begin with.\n *\n * It answers for the moment it resolves and makes no promise about the one after: work started later leaves the\n * element running again, so a caller that has to act on a settled tree reads what it needs immediately after\n * awaiting rather than at its leisure.\n */\n settled(): Promise<void> {\n if (!this.validating && !this.busy) return Promise.resolve();\n return new Promise((resolve) => {\n // sync flush, so the promise settles with the write that ended the last run rather than a tick after it\n const stop = watch(\n () => this.validating || this.busy,\n (running) => {\n if (running) return;\n stop();\n resolve();\n },\n { flush: 'sync' },\n );\n });\n }\n\n /**\n * List of errors. The array handed out is the one the element holds, and a validator writes into it in place,\n * so a transaction that is open takes the element into its record here: a rollback that put back everything\n * except the errors would leave a state the form never held.\n *\n * The array and its members are Vue proxies, not the raw instances a validator returned - `field.errors[0] ===\n * myError` is `false` for the very error that produced it. Unwrapping here would lose the tracked read a\n * template needs to re-render when a message behind a `Ref` changes; `toRaw()` compares identity instead.\n */\n get errors(): ValidationError[] {\n this.touchState();\n return this.#state.errors;\n }\n\n set errors(newValue: ValidationError[]) {\n this.touchState();\n this.#state.errors = newValue;\n }\n\n /**\n * The container that holds this element: the Group it is a member of, or the List whose row it is, and\n * undefined while no container holds it. The container writes it; everyone else reads it. The read is tracked,\n * so an effect rendering off the link - `v-if=\"field.parent\"` - re-runs when a container takes the element or\n * releases it.\n *\n * The type is `Container`, which names no members: a sibling lookup states which container it expects, either\n * with `field.parent instanceof Group` or with a cast where the structure guarantees it.\n */\n get parent(): Container | undefined {\n return this.#state.parent;\n }\n\n /**\n * The same link at the type the internals reach through. The hooks a child tells its container things through -\n * childValidatingChanged, childValidityChanged - are declared here, and a protected member is reachable only\n * through the class that declares it; `Container` overrides them, so the link is read as a `FieldBase`.\n */\n private get container(): FieldBase | undefined {\n return this.#state.parent;\n }\n\n /** when member of a Group, fieldName specifies the name of this field. Written by the group, read-only after */\n get fieldName(): string | undefined {\n return this.#state.fieldName;\n }\n\n /**\n * The element this one was declared as: itself for an element built from parameters, and the element it was\n * bound from for a binding - transitively, so a binding of a binding names the same one. Every row a `List`\n * builds from an item template is a binding of it, so a row's member and the template's member it stands for\n * answer with the same element, and an action registered on the template can tell the two apart.\n */\n get declaration(): FieldBase {\n return this.#raw.declaration ?? this;\n }\n\n /** The elements this one holds: a Group's members, a List's rows, none for a leaf. */\n protected get members(): FieldBase[] {\n return [];\n }\n\n /**\n * Every element in this element's subtree, this element included, that was declared as `declaration`. It answers\n * the question a shared action asks when the record it changed in is not the record its targets live in - a form\n * field that every row of a list reacts to - and it costs the subtree, so it is the path taken only when the\n * cheaper one, resolving within a single record, does not apply.\n */\n bindingsOf(declaration: FieldBase): FieldBase[] {\n const canonical = declaration.declaration;\n const found: FieldBase[] = [];\n const visit = (element: FieldBase) => {\n if (element.declaration === canonical) found.push(element);\n element.members.forEach(visit);\n };\n visit(this);\n return found;\n }\n\n /** set while an eager pass over this element is waiting for the record the element belongs to */\n declare protected _recordPending?: boolean;\n\n /**\n * States that an eager pass over this element reached an element it needs and did not find it, because the\n * record this element belongs to was not assembled at the time: a `List` row is built member by member and its\n * members are bound before any of them holds the row, so a validator comparing two of them runs before the\n * row exists. The container that finishes the record runs the pass again, and a pass that still reaches\n * nothing says so again, so the next container above answers for it.\n */\n markRecordIncomplete(): void {\n if (this._recordPending) return;\n this._recordPending = true;\n incompleteRecords++;\n }\n\n /**\n * Runs the eager passes outstanding in `element`'s subtree, now that the record it belongs to is assembled. A\n * container calls it where it has just made a record complete: a Group that has written its members, and a\n * List that has taken a row, which is what gives the row's fields the form above it.\n */\n protected completeRecords(element: FieldBase = this): void {\n if (incompleteRecords === 0) return;\n transactional(() => {\n const visit = (current: FieldBase) => {\n if (current._recordPending) {\n current._recordPending = false;\n incompleteRecords--;\n current.rerunEagerActions();\n }\n current.members.forEach(visit);\n };\n visit(element);\n });\n }\n\n /** Runs this element's eager actions over the value it holds and re-forms the verdict they reach. */\n private rerunEagerActions(): void {\n transactional((tx) => {\n this.boundActions?.triggerEager(this, this.contribution, this.contribution);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * The map an element that was declared rather than bound registers its actions in, absent while it has registered\n * none. A binding holds no map of its own: `boundActions` reads the one its declaration holds.\n */\n declare protected _actions?: ActionsMap;\n\n /**\n * The actions this element answers to, absent where nothing is registered. A binding holds the very map its\n * declaration holds rather than a copy of it, so the slot is read directly: what a trigger costs is one property\n * read, and a rule registered on a `List`'s item template reaches every row through the map they share - the\n * rows built before the registration as much as the ones built after.\n */\n protected get boundActions(): ActionsMap | undefined {\n return this._actions;\n }\n\n /** Records that `binding` was made from this element, so a later registration can reach it. */\n protected noteBinding(binding: FieldBase): void {\n let made = bindingsMade.get(this);\n if (!made) {\n made = new Set();\n bindingsMade.set(this, made);\n }\n made.add(new WeakRef(binding));\n }\n\n /**\n * The bindings made from this element that are still alive, and this element itself. The dead references are\n * dropped as they are found, which is what keeps the set from growing over the life of a long-lived declaration.\n */\n protected get boundElements(): FieldBase[] {\n const declaration = this.declaration;\n const made = bindingsMade.get(declaration);\n const alive: FieldBase[] = [declaration];\n if (!made) return alive;\n made.forEach((ref) => {\n const binding = ref.deref();\n if (!binding) made.delete(ref);\n else alive.push(binding);\n });\n return alive;\n }\n\n /**\n * The map registrations go into: the declaration's, since that is where behaviour lives. The map is made on the\n * first registration and handed to every binding already made from the declaration, so all of them go on reading\n * one map through a slot of their own.\n */\n protected get actions(): ActionsMap {\n const declaration = this.declaration;\n if (!declaration._actions) {\n const map = new ActionsMap();\n declaration.boundElements.forEach((element) => {\n element._actions = map;\n });\n }\n return declaration._actions!;\n }\n\n /**\n * Counts the writes that have changed the value of this element or of anything below it. A container reads it\n * before answering from its value cache, and the read is an ordinary tracked one, so an effect that took a\n * cached value still re-runs when a descendant is written.\n */\n protected get valueVersion(): number {\n return this.#state.valueVersion;\n }\n\n /**\n * Marks the value of this element and of every ancestor as superseded. It walks the parent chain, so it costs\n * the nesting depth: an ancestor rebuilds its value the next time one is asked of it, instead of being walked\n * here for a reader that may never come. The walk also brings each element into the open transaction, so a\n * rollback puts the versions back and no reader is left holding a cache the tree no longer supports.\n */\n protected bumpValueVersion(): void {\n transactional((tx) => {\n tx.touch(this);\n this.#state.valueVersion++;\n let ancestor: FieldBase | undefined = this.parent;\n while (ancestor) {\n tx.touch(ancestor);\n ancestor.#state.valueVersion++;\n ancestor = ancestor.parent;\n }\n });\n }\n\n /**\n * States that this element's value changed and that every container above it therefore holds a different value\n * too. Nothing is announced here: the transaction works out at commit which of the elements enrolled actually\n * ends up holding a different value, and announces those once each.\n *\n * `force` states that the caller already knows this element's value changed - one item more or fewer is a\n * different list whatever the items compare as - so the commit announces it without composing a comparison.\n */\n protected propagateValueChanged(force: boolean = false): void {\n transactional((tx) => {\n tx.markValueChanged(this, force);\n tx.markValidityDirty(this);\n this.parent?.notifyValueChanged();\n });\n }\n\n /**\n * The last step of a construction: it runs inside the transaction the construction is, with the parameters\n * applied and the value in place, before the element records what it was built as.\n *\n * A subclass overrides it to complete what the element was built with. What it writes here is part of the\n * construction rather than a change of it: the element announces no ValueChangedAction, and what the hook\n * leaves is what its eager actions and its validators run over, once. An element whose parameters named no\n * `originalValue` is baselined on the value the hook left and so starts unchanged; one that named a baseline is\n * measured against it, as any element is. A `Field` writes `_value`: the value setter states a change, and\n * this is not one.\n *\n * A container completes itself through its members, and a member carries a construction of its own: the write\n * reaches it as any later one would, so the member announces it and reports itself changed. A member that is to\n * start unchanged is baselined here as well - `this.fields.x.originalValue = this.fields.x.value`.\n *\n * `params` is the parameter object the constructor received, where it received one.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected constructed(params?: object): void {}\n\n /**\n * Re-reads what the next announcements will report as replaced. A contribution is composed only where something\n * listens for it, so the copy is re-read here; a leaf records what it holds at every announcement, so that copy\n * is always current, and a container that skipped composing what nobody was listening for re-reads its own too.\n */\n protected refreshPreviousValue(): void {\n this.#raw.announcedContribution = this.contribution;\n }\n\n /**\n * The verdict validate() records and announces: this element's own errors plus the tally of children that\n * reported themselves invalid, so a container forms it without walking its members. `valid` is the read path\n * and answers over the live errors arrays instead; the two differ only for an error written into a member\n * without a validate() call, which is the documented cost of pushing errors by hand.\n */\n protected get countedValid(): boolean {\n return this.#raw.errors.length === 0 && this.#raw.invalidChildren === 0;\n }\n\n /**\n * Makes this element the container of `child`: it installs the back-reference, records the name a Group holds\n * the child under, and takes the child into the invalid tally. An element belongs to one container at a time,\n * so a child that already carries the link is refused; releaseChild() takes the link away again, and an element\n * released that way can be handed on. The child's state is unreachable from outside FieldBase, so a container\n * writes the two slots through here rather than on the child.\n */\n protected takeChild(child: FieldBase, fieldName?: string): void {\n transactional((tx) => {\n if (child.parent) throw new TypeError('This element already belongs to a container - pass a bind() of it');\n tx.touch(child);\n child.#state.fieldName = fieldName;\n // below an editable container every element keeps the effective access it had on its own, so only a container\n // that narrows it has anything to check again\n const narrowing = this.effectiveAccess !== 'editable';\n const detached = narrowing ? child.effectiveAccessFromHere() : undefined;\n // only a Container calls this, since only a container holds children\n child.#state.parent = this as unknown as Container;\n // the containers above now decide what the child sends, so it is checked again where that moved\n if (detached) child.revalidateWhereChanged(detached);\n this.adoptChild(child);\n });\n }\n\n /** Takes a child into this element's invalid tally; a container calls it once the child's parent link exists. */\n protected adoptChild(child: FieldBase): void {\n transactional((tx) => {\n tx.touch(this);\n if (!child.#raw.valid && child.countsInContainer) this.#raw.invalidChildren++;\n // a run in flight below the child now runs below this element too. The validation counters are outside the\n // snapshot, so the transfer hands the rollback an undo of its own, and that undo reads the child at rollback\n // time: a run that starts below the child while the transaction holds it is one this element counts too, and\n // it is still in flight when the rollback hands the child back\n if (child.validating) this.childValidatingChanged(true);\n tx.whenRolledBack(() => {\n if (child.validating) this.childValidatingChanged(false);\n });\n // the tally moved, so the verdict this element carries may no longer be the one its members support\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Drops a child out of this element's invalid tally and takes its back-reference away. An element keeps no link\n * to a container that no longer holds it: it would go on moving that container's tally, and the link is what\n * stands in the way of the element being taken by another container.\n */\n protected releaseChild(child: FieldBase): void {\n transactional((tx) => {\n tx.touch(this);\n tx.touch(child);\n if (!child.#raw.valid && child.countsInContainer) this.#raw.invalidChildren--;\n // out of a container that narrowed it, the child is on its own again and is checked where that moved\n const attached = this.effectiveAccess !== 'editable' ? child.effectiveAccessFromHere() : undefined;\n // the undo reads the child at rollback time for the same reason adoptChild's does: what this element carries\n // again is the runs the child has in flight when it comes back, not the ones it had when it left\n if (child.validating) this.childValidatingChanged(false);\n tx.whenRolledBack(() => {\n if (child.validating) this.childValidatingChanged(true);\n });\n child.#state.parent = undefined;\n // the name goes with the link: it is the name a container held the element under, and the element belongs to\n // none, so it is as detached as one a bind() produced\n child.#state.fieldName = undefined;\n if (attached) child.revalidateWhereChanged(attached);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Brings this element to the state a fresh binding of `source` carrying `value` would be in: `value` is written\n * where the caller supplied one and `source`'s own value where it did not, the change history - originalValue,\n * touched - starts over and the errors are dropped and re-established by the validators. A container that reuses\n * an element at a position it already holds calls it, so the element is indistinguishable from one built for\n * that position.\n */\n protected resetTo(source: FieldBase, value: any): void {\n transactional(() => {\n const target = value === undefined ? source.value : value;\n const dropped = this.errors.length > 0;\n if (dropped) this.errors = [];\n this.touched = false;\n const assigned = this.value !== target;\n this.value = target;\n this.originalValue = this.value;\n // an assignment that went through ran the validators over the new value. Where it was a no-op they run here\n // if there were errors to drop, and otherwise not at all: the verdict they reached over the value the field\n // still holds is the one that stands.\n this.validate(!assigned && dropped);\n });\n }\n\n /** Resets a member. It is what lets a container reach the reset of a child whose class it does not know. */\n protected resetChild(child: FieldBase, source: FieldBase, value: any): void {\n child.resetTo(source, value);\n }\n\n /**\n * Records a child's new verdict in this element's tally. Only a `Container` has children, and it implements\n * this; it is declared here for the reason `childValidatingChanged` is.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected childValidityChanged(nowValid: boolean): void {}\n\n // default property handlers\n /**\n * How a rendering layer shows this element. It is presentation alone: what the element sends and whether it is\n * validated are its `access`, and no visibility changes either.\n */\n get visibility(): Visibility {\n return this.#state.visibility;\n }\n\n set visibility(newValue: Visibility) {\n const oldValue = this.#state.visibility;\n // writing what the element already holds is not a change, so nothing runs for it: no *Changing* handler, no\n // enrolment in the transaction, no *Changed* event. It is the rule the value setter states as well\n if (newValue === oldValue) return;\n transactional((tx) => {\n const alteredValue = this.boundActions?.trigger(VisibilityChangingAction, this, newValue, oldValue);\n // a handler that ended the run refused the write: nothing is written and nothing is announced\n if (alteredValue instanceof AbortEventHandlingException) return;\n const written = alteredValue ?? newValue;\n if (!isVisibility(written))\n throw new Error(`${describe(written)} is not a visibility: ${listOf(visibilityValues)}`);\n tx.touch(this);\n this.#state.visibility = written;\n this.boundActions?.trigger(VisibilityChangedAction, this, written, oldValue);\n });\n }\n\n /**\n * What this element accepts and what it sends: `'editable'` and `'readonly'` send its value, `'disabled'` sends\n * nothing and `'disabled-null'` sends `null`, and only `'editable'` accepts input. The validators run over what\n * the element sends and only where it is sent at all, as `effectiveAccess` states, so a switch of access runs\n * them again here and below.\n */\n get access(): Access {\n return this.#state.access;\n }\n\n set access(newValue: Access) {\n const oldValue = this.#state.access;\n // as with visibility: what the element already holds is no change, and nothing runs for it\n if (newValue === oldValue) return;\n transactional((tx) => {\n const alteredValue = this.boundActions?.trigger(AccessChangingAction, this, newValue, oldValue);\n // as with visibility: a handler that ended the run refused the write\n if (alteredValue instanceof AbortEventHandlingException) return;\n const written = alteredValue ?? newValue;\n if (!isAccess(written)) throw new Error(`${describe(written)} is not an access: ${listOf(accessValues)}`);\n // a handler that answered with the access the element holds refused the write\n if (written === oldValue) return;\n const wasEnabled = this.enabled;\n const willBeEnabled = written === 'editable';\n if (willBeEnabled !== wasEnabled) {\n // enabled is read from access, so a handler that answers with the enabled the element has refuses the write\n // of the access that would have changed it\n const enabledAnswer = this.boundActions?.trigger(EnabledChangingAction, this, willBeEnabled, wasEnabled);\n if (enabledAnswer instanceof AbortEventHandlingException) return;\n if (enabledAnswer != null && typeof enabledAnswer !== 'boolean') {\n throw new Error(`${describe(enabledAnswer)} is not what an EnabledChangingAction answers with: a boolean`);\n }\n if (enabledAnswer === wasEnabled) return;\n }\n tx.touch(this);\n const oldContribution = this.contribution;\n const counted = this.countsInContainer;\n const below = this.effectiveAccessBelow();\n this.#state.access = written;\n this.revalidateWhereChanged(below);\n // a leaf's validators run at the change, over what it now sends; a container's run at the commit, where what\n // it sends is composed\n if (!this.composesValue) this.boundActions?.triggerEager(this, this.contribution, oldContribution);\n // what the element sends changed, so its contribution and that of every container above it is measured again\n // at the commit; what any of them holds did not change\n this.contributionChanged(tx, counted);\n this.boundActions?.trigger(AccessChangedAction, this, written, oldValue);\n if (this.enabled !== wasEnabled) this.boundActions?.trigger(EnabledChangedAction, this, this.enabled, wasEnabled);\n });\n }\n\n /**\n * The access this element has once the containers above it are taken into account. A container that sends nothing\n * or `null` in place of what it holds sends none of its members, so below a `'disabled'` or `'disabled-null'`\n * container every element is `'disabled'`; below a `'readonly'` one an `'editable'` element is `'readonly'`.\n * Anywhere else it is the element's own access.\n *\n * It is what decides whether the element's validators run: an element that is `'disabled'` here is sent nowhere,\n * so its validators reach no verdict and it carries none of their errors. Anywhere else they run over what the\n * element sends - its value, or `null`.\n */\n get effectiveAccess(): Access {\n const own = this.access;\n const above = this.parent?.effectiveAccess;\n if (above === 'disabled' || above === 'disabled-null') return 'disabled';\n if (above === 'readonly' && own === 'editable') return 'readonly';\n return own;\n }\n\n /**\n * Whether `effectiveAccess` is `'disabled'`, read off the untracked state. A validator asks it on every run, where\n * nothing renders off the answer and a tracked walk up the containers would cost every write a read per level.\n */\n [SentNowhere](): boolean {\n if (this.#raw.access === 'disabled') return true;\n for (let above = this.#raw.parent; above; above = above.#raw.parent) {\n if (above.#raw.access === 'disabled' || above.#raw.access === 'disabled-null') return true;\n }\n return false;\n }\n\n /**\n * True where `access` is `'editable'`: the element accepts input. It reads `access` and nothing else, and it is a\n * statement about input rather than about data - `'readonly'` is not enabled and still sends its value. What an\n * element sends is read from `access`.\n */\n get enabled(): boolean {\n return this.access === 'editable';\n }\n\n /**\n * True where `effectiveAccess` is `'editable'`: this element and every container above it accept input. A\n * rendering layer binds one read instead of walking the parent chain: a container that is not editable states\n * that its section cannot be edited, and the inputs rendered from the members inside it read that here.\n */\n get effectiveEnabled(): boolean {\n return this.effectiveAccess === 'editable';\n }\n\n /** The effective access of this element and of every element below it, read before a change that may move it. */\n private effectiveAccessFromHere(): Map<FieldBase, Access> {\n const seen = this.effectiveAccessBelow();\n seen.set(this, this.effectiveAccess);\n return seen;\n }\n\n /** The effective access of every element below this one, read before a change that may move it. */\n private effectiveAccessBelow(): Map<FieldBase, Access> {\n const seen = new Map<FieldBase, Access>();\n const visit = (element: FieldBase) => {\n element.members.forEach((member) => {\n seen.set(member, member.effectiveAccess);\n visit(member);\n });\n };\n visit(this);\n return seen;\n }\n\n /**\n * Runs the validators again on every element whose effective access moved since `before` was read: one that stops\n * being sent drops their errors, and one that starts being sent is checked over what it now sends.\n */\n private revalidateWhereChanged(before: Map<FieldBase, Access>): void {\n before.forEach((access, element) => {\n if (element.effectiveAccess !== access) element.rerunEagerActions();\n });\n }\n\n /**\n * What this element contributes to its container's `value` or `fullValue`: its own value, `null` in its place, or\n * nothing. It is the one place the rule is stated - every container composes its values by asking it.\n *\n * `fullValue` states everything the form holds, so every element contributes its value there. `value` states\n * what the form sends, and `access` decides it: `'disabled'` leaves the element out and `'disabled-null'` sends\n * `null`, whatever a container holds below it.\n */\n protected serializesAs(purpose: 'value' | 'fullValue'): 'value' | 'null' | 'omit' {\n if (purpose === 'fullValue') return 'value';\n switch (this.access) {\n case 'disabled':\n return 'omit';\n case 'disabled-null':\n return 'null';\n default:\n return 'value';\n }\n }\n\n /** What `child` contributes to this container, asked the way `childComposesValue` asks what it is. */\n protected childSerializesAs(child: FieldBase, purpose: 'value' | 'fullValue'): 'value' | 'null' | 'omit' {\n return child.serializesAs(purpose);\n }\n\n /**\n * What this element sends to its container's `value`: its value where its access sends it, `null` for\n * `'disabled-null'`, and `undefined` for `'disabled'`, whose key or row is left out. It is what the element's\n * validators run over and what `ContributionChangedAction` reports.\n */\n get contribution(): unknown {\n switch (this.serializesAs('value')) {\n case 'omit':\n return undefined;\n case 'null':\n return null;\n default:\n return this.value;\n }\n }\n\n /**\n * What `ValueChangedAction` reports this element as holding: its value. A container holds every member's value\n * whatever the member sends, so it answers with its `fullValue`.\n */\n protected get holding(): any {\n return this.value;\n }\n\n /**\n * Whether the container holding this element counts its verdict: every element that sends something, `null`\n * included. A `'disabled'` element sends nothing, so it is not counted - an error written into it by hand no more\n * than one from a validator, which does not run there.\n */\n private get countsInContainer(): boolean {\n return this.serializesAs('value') !== 'omit';\n }\n\n /**\n * Carries a change of what this element sends: the element is enrolled so the commit measures its contribution\n * and re-forms its verdict, the container's value is built again, and an element that is invalid enters or leaves\n * the container's tally as it starts or stops being counted.\n */\n private contributionChanged(tx: Transaction, wasCounted: boolean): void {\n tx.markValueChanged(this, false);\n tx.markValidityDirty(this);\n this.bumpValueVersion();\n const holder = this.container;\n if (!holder) return;\n const counted = this.countsInContainer;\n if (counted !== wasCounted && !this.#raw.valid) {\n tx.touch(holder);\n // an invalid element that stops being counted is, to the tally, one that turned valid, and the other way round\n holder.childValidityChanged(!counted);\n tx.markValidityDirty(holder);\n }\n this.parent!.notifyValueChanged();\n }\n\n /**\n * True for an element whose value is composed of its members'. The commit builds such a value only where\n * something receives it, compares it by content rather than by identity, and runs the element's own validators\n * with the announcement: a container's validators read the composed value, which exists only once the members\n * have been written. A leaf's validators have run at the write instead, so its announcement carries no eager\n * pass of its own.\n */\n protected get composesValue(): boolean {\n return false;\n }\n\n /**\n * Whether `child` composes its value from members of its own. It is what lets a container tell a nested\n * container from a leaf without knowing the classes below it, the way `resetChild` reaches a reset it does not\n * know the shape of.\n */\n protected childComposesValue(child: FieldBase): boolean {\n return child.composesValue;\n }\n\n /**\n * Announces what this element holds and what it sends, as they became over the transaction. Each pair carried is\n * (now, at the last announcement), so a value that went A -> B -> A within the transaction says nothing, and the\n * events an operation states rather than an element's state - an item added, an item removed - are emitted first,\n * in the order the operations happened.\n *\n * A container's validators read what it sends, which is composed here and nowhere else, so they run first, where\n * that moved; a leaf's have run at the write. `ValueChangedAction` reports what the element holds, and\n * `ContributionChangedAction` what it sends to its container.\n */\n protected [TxAnnounceValue](tx: Transaction, dirty: boolean, force: boolean, structural?: TxStructuralEvent[]): void {\n structural?.forEach((event) => this.boundActions?.trigger(event.actionClass, this, event.item, event.index));\n if (!dirty) return;\n const actions = this.boundActions;\n const composes = this.composesValue;\n const same = (a: unknown, b: unknown) => (composes ? isEqual(a, b) : a === b);\n\n // a container composes what it sends only where its validators read it\n if (composes && actions?.hasEager) {\n const sent = this.contribution;\n const validated = this.#raw.validatedValue;\n if (force || !isEqual(sent, validated)) {\n tx.touch(this);\n this.#raw.validatedValue = sent;\n actions.triggerEager(this, sent, validated);\n }\n }\n\n // what a container holds is only composed where something receives it; a leaf's is its value, read for free.\n // The record of what was announced is written before the event: a handler that changes something while it runs\n // opens a change of its own, and that one is measured against this announcement\n if (!composes || actions?.willTrigger(ValueChangedActionClassIdentifier)) {\n const held = this.holding;\n const announced = this.#raw.announcedValue;\n if (force || !same(held, announced)) {\n tx.touch(this);\n this.#raw.announcedValue = held;\n actions?.trigger(ValueChangedAction, this, held, announced);\n }\n }\n\n if (actions?.willTrigger(ContributionChangedActionClassIdentifier)) {\n const contribution = this.contribution;\n const announced = this.#raw.announcedContribution;\n if (!same(contribution, announced)) {\n tx.touch(this);\n this.#raw.announcedContribution = contribution;\n actions.trigger(ContributionChangedAction, this, contribution, announced);\n }\n }\n }\n\n /**\n * Records what this element holds and sends as what was last announced, so the commit that follows reports no\n * change of either. A construction calls it over the state it ends on, and so does an element brought to the\n * state a fresh binding would be in.\n */\n protected recordAnnounced(): void {\n // a baseline is composed only where something receives the announcement it is measured for; a registration\n // that adds a listener later re-reads it then (refreshPreviousValue), and a leaf's value is read for free\n const actions = this.boundActions;\n if (!this.composesValue || actions?.willTrigger(ValueChangedActionClassIdentifier)) {\n this.#raw.announcedValue = this.holding;\n }\n if (actions?.willTrigger(ContributionChangedActionClassIdentifier))\n this.#raw.announcedContribution = this.contribution;\n if (this.composesValue && actions?.hasEager) this.#raw.validatedValue = this.contribution;\n }\n\n /**\n * Forms the verdict this element ends the transaction with and announces a transition of it. The container is\n * told first, so a handler reads a tally that already includes this verdict, and it is enrolled in the same\n * transaction: its own verdict is composed of its members', so a member that moves without a value change - an\n * asynchronous validator, an error pushed in by hand - is what makes the container re-form its own. The\n * transaction settles the deepest element first, so a container is reached only once its members have decided.\n */\n protected [TxSettleValidity](tx: Transaction): void {\n const oldValid = this.#raw.valid;\n const newValid = this.countedValid;\n if (newValid === oldValid) return;\n tx.touch(this);\n this.#raw.valid = newValid;\n // the verdict goes to the container that holds this element, and a container that released it holds it no\n // longer: the link is gone with the release, so a dropped row moves no tally\n const holder = this.container;\n // an element that sends nothing is kept out of its container's tally, so a verdict it reaches moves nothing above\n if (holder && this.countsInContainer) {\n tx.touch(holder);\n holder.childValidityChanged(newValid);\n tx.markValidityDirty(holder);\n }\n this.boundActions?.trigger(ValidChangedAction, this, newValid, oldValid);\n }\n\n validate(revalidate: boolean = false) {\n transactional((tx) => {\n if (revalidate) this.boundActions?.triggerEager(this, this.contribution, this.contribution);\n tx.markValidityDirty(this);\n });\n }\n\n get valid() {\n // the slot is read rather than the errors getter, which takes the element into an open transaction: reading a\n // verdict changes nothing, and there is nothing for a rollback to put back\n return this.#state.errors.length === 0;\n }\n\n get fullValue(): T {\n return this.value;\n }\n\n get isChanged(): boolean {\n return !isEqual(this.value, this.originalValue);\n }\n\n /**\n * Brings a fresh element into the state a binding of `source` is in: it records what it was declared as, takes\n * on the extended properties and the actions `source` carries, and runs the eager ones over the value it was\n * built with. The extended properties `overrides` states are written over the ones `source` carries, and they\n * are in place before the eager pass, so an action reading one sees what the binding ends up carrying. The\n * actions are the very instances `source` holds - what a binding takes on is data, not behaviour - and each is\n * told about this element as it is taken on, so an action serving several bindings knows all of them.\n */\n protected boundFrom(source: FieldBase<any, X>, newValue: any, oldValue: any, overrides?: object): void {\n if (overrides) refuseEnabled(overrides);\n this.#raw.declaration = source.declaration;\n const extended: Partial<X> = { ...source.extra, ...(overrides && this.extendedOf(overrides)) };\n if (!isEmpty(extended)) this.setExtendedValues(extended);\n const declaration = this.declaration;\n declaration.noteBinding(this);\n // the map is the declaration's own and is taken on rather than copied, so a rule registered on the declaration\n // after this binding was made reaches it too. A declaration with nothing registered has no map, and the one it\n // makes later is handed to this element then\n const actions = declaration._actions;\n if (!actions) return;\n this._actions = actions;\n actions.bindTo(this);\n // the construction recorded no baseline for a listener it did not have yet\n this.recordAnnounced();\n actions.triggerEager(this, newValue, oldValue);\n }\n\n /**\n * Registers the actions a constructor received in its parameters: registration without the eager trigger,\n * because a constructor ends with a single this.actions.triggerEager(...) over the finished value, and an\n * eager action registered here would otherwise also run once per registration, over a half-built field.\n */\n protected registerInitialActions(actions: FieldActionBase[]): void {\n actions.forEach((action) => {\n this.actions.register(action);\n action.boundToBinding(this);\n });\n }\n\n registerAction(action: FieldActionBase): this {\n transactional((tx) => {\n // the baseline of a change the transaction has yet to announce stays where it is: the element is already\n // enrolled to report that change, and moving the baseline to the value it now holds would erase the report\n if (!tx.willAnnounceValue(this)) this.refreshPreviousValue();\n this.actions.register(action);\n this.registered(tx, action);\n });\n return this;\n }\n\n /**\n * Registers `action` so that `before` wraps it: `before` reaches it through the `supr` it is handed, instead of\n * ending the run there. It is how an action is added to a chain someone else built and still sits inside a\n * handler already registered, which registration order alone cannot arrange. `before` has to be registered on\n * this element under the same identifier.\n */\n registerActionBefore(action: FieldActionBase, before: FieldActionBase): this {\n transactional((tx) => {\n if (!tx.willAnnounceValue(this)) this.refreshPreviousValue();\n this.actions.register(action, before);\n this.registered(tx, action);\n });\n return this;\n }\n\n /**\n * Drops `action` from this element and answers whether it held it. The instance goes on serving every other\n * element it was registered on: what is dropped is this element's registration, not the action. A validator\n * withdraws the errors it put on this element as it goes, so the verdict the element reports is the one the\n * validators it still holds reach.\n */\n unregisterAction(action: FieldActionBase): boolean {\n let dropped = false;\n transactional((tx) => {\n const actions = this.boundActions;\n if (!actions) return;\n dropped = actions.unregister(action);\n if (!dropped) return;\n tx.touch(this);\n // a run still in flight was started by a validator this element may no longer hold, and its verdict is one\n // the element must not take on\n if (action instanceof Validator) this.#state.validationEpoch++;\n // the action served the declaration and every binding made from it, so it is released from all of them\n const elements = this.boundElements;\n tx.whenRolledBack(() => {\n actions.register(action);\n elements.forEach((element) => action.boundToBinding(element));\n });\n elements.forEach((element) => action.unregisterFrom(element));\n });\n return dropped;\n }\n\n /**\n * Records that `action` is now registered on this element, and that a rollback has to take that back. The\n * registration is not one of the state slots the snapshot covers, so it hands its own undo in.\n */\n private registered(tx: Transaction, action: FieldActionBase): void {\n // the action serves the declaration, so it serves every binding made from it - the ones that already exist as\n // much as the ones still to be made. An eager action states something about the value each of them holds, so\n // it reaches those values at once rather than waiting for the next change; the group it joined runs whole,\n // because the new action may be wrapped by ones registered before it and its own `supr` reaches those.\n const elements = this.boundElements;\n elements.forEach((element) => {\n action.boundToBinding(element);\n if (action.eager) {\n // what the action ran over is what a container's validators were last run over\n element.#raw.validatedValue = element.contribution;\n this.actions.triggerEagerFor(action.classIdentifier, element, element.contribution, element.originalValue);\n }\n });\n tx.whenRolledBack(() => {\n if (this.boundActions?.unregister(action)) elements.forEach((element) => action.unregisterFrom(element));\n });\n }\n\n triggerAction<T2 extends FieldActionBase>(\n actionClass: (abstract new (...args: any[]) => T2) & { classIdentifier: symbol },\n ...params: any[]\n ): any {\n // an element with no map has nothing registered, and ActionsMap.trigger answers null for exactly that case\n const actions = this.boundActions;\n return actions ? actions.trigger(actionClass, this, ...params) : null;\n }\n\n /**\n * Generation counter of the validators attached to this field. A Validator reads it when a run starts and drops\n * a result whose epoch no longer matches, so a validation still in flight when clearValidators() is called\n * cannot push an error onto a field that no longer has the validator that produced it.\n */\n get validationEpoch(): number {\n return this.#state.validationEpoch;\n }\n\n clearValidators(): void {\n transactional((tx) => {\n tx.touch(this);\n this.#state.validationEpoch++;\n const actions = this.boundActions;\n if (actions) {\n // the release names this element, because the same instance goes on serving every other element it was\n // registered on\n const elements = this.boundElements;\n actions.validators.forEach((validator) => {\n actions.unregister(validator);\n tx.whenRolledBack(() => {\n actions.register(validator);\n elements.forEach((element) => validator.boundToBinding(element));\n });\n // each of them withdraws the errors it put on every element it validated\n elements.forEach((element) => validator.unregisterFrom(element));\n });\n }\n this.errors = [];\n // the errors are gone before the recomputation, so the commit forms the verdict over the cleared state and\n // routes the validity transition through the usual path: the ValidChangedAction fires and the parent\n // re-evaluates\n this.validate();\n });\n }\n}\n","import { isString } from 'lodash-es';\nimport { unref } from 'vue';\n\nimport { resolveInScope } from '../../binding/resolve';\nimport { FieldBase } from '../../field-base';\n\nimport Operator from './operator';\n\n// An operand is a nested Statement, a field whose current value is compared, or a literal of any type. The\n// union with `any` collapses to `any` for the type checker, so the alias documents intent rather than\n// constraining callers; the two shapes that are no operand at all - undefined and a function - are rejected by\n// the constructor.\nexport type OperandType = any | Statement | FieldBase;\n\nfunction XOR(value1: boolean, value2: boolean): boolean {\n return value1 ? !value2 : value2;\n}\n\nexport class Statement {\n private readonly operand1: OperandType;\n\n private readonly operator: Operator;\n\n private readonly operand2: OperandType;\n\n /**\n * An operand is a nested `Statement`, a `FieldBase` whose value is compared, or a literal. `undefined` and a\n * function are neither: they are what a misspelled field name and a field accessor handed over uncalled answer\n * with, and a statement built from one compares nothing and never fires. The position names which of the two\n * operands is at fault, so the error points at the place the name was written.\n */\n private static validateOperand(operand: OperandType, position: 1 | 2): void {\n if (operand === undefined) {\n throw new TypeError(\n `Statement operand ${position} is undefined: an operand is a field, a nested statement or a literal, ` +\n 'and a name resolving to nothing is none of them. Compare against null to test for an unset value.',\n );\n }\n if (typeof operand === 'function') {\n throw new TypeError(\n `Statement operand ${position} is a function: an operand is a field, a nested statement or a literal, ` +\n \"and a function is none of them. An accessor states the field it answers with: group.field('name').\",\n );\n }\n }\n\n /**\n * `NOT` reads one operand, so it is stated with one. Every other operator compares two and takes both, and so\n * does an operator held in a variable - `Operator.fromString()` answers with the type rather than with the\n * constant, and the compiler cannot tell from it which of the two forms is meant.\n *\n * @throws TypeError where an operand the statement reads is undefined or a function.\n */\n constructor(operand1: OperandType, operator: Operator.NOT);\n constructor(operand1: OperandType, operator: Operator, operand2: OperandType);\n constructor(operand1: OperandType, operator: Operator, operand2?: OperandType) {\n Statement.validateOperand(operand1, 1);\n // NOT reads operand1 alone, so whatever stands in the second position is never compared and never rejected\n if (operator !== Operator.NOT) Statement.validateOperand(operand2, 2);\n\n this.operand1 = operand1;\n this.operator = operator;\n this.operand2 = operand2;\n }\n\n /**\n * The value an operand contributes. A field operand names a field of the record the statement is evaluated in:\n * the same statement over a `List` reads row 3's field while row 3 is the record, and a field belonging to no\n * record of the statement's own - a form field above the list - is read where it stands. A record that does not\n * hold the field yet contributes undefined, which is what a half-built row answers with.\n */\n private static valueOf(operand: OperandType, scope?: FieldBase) {\n if (operand instanceof Statement) return operand.evaluate(scope);\n if (operand instanceof FieldBase) {\n const field = scope ? resolveInScope(operand, scope) : operand;\n return field ? unref(field.value) : undefined;\n }\n return operand; // any\n }\n\n get operand1Value() {\n return Statement.valueOf(this.operand1);\n }\n\n get operand2Value() {\n return Statement.valueOf(this.operand2);\n }\n\n /**\n * The result of the statement, over the record `scope` belongs to where one is given and over the fields the\n * statement was built from where it is not.\n */\n evaluate(scope?: FieldBase): boolean {\n const operand1 = Statement.valueOf(this.operand1, scope);\n const operand2 = Statement.valueOf(this.operand2, scope);\n\n switch (this.operator) {\n // logical operators\n // `&&` and `||` evaluate to one of their operands, and the operands are of any type. Without the\n // coercion evaluate() would hand out the operand itself, so `0` or `''` would reach callers that the\n // signature promises a boolean, and consumers comparing results with !== would see a change where the\n // logical value stayed the same.\n case Operator.AND:\n return Boolean(operand1 && operand2);\n case Operator.OR:\n return Boolean(operand1 || operand2);\n case Operator.NAND:\n return !(operand1 && operand2);\n case Operator.NOR:\n return !(operand1 || operand2);\n case Operator.XOR:\n return XOR(Boolean(operand1), Boolean(operand2));\n case Operator.NOT:\n return !operand1;\n\n // comparison operators\n case Operator.EQUALS:\n return operand1 == operand2;\n case Operator.NOT_EQUALS:\n return operand1 != operand2;\n case Operator.LT:\n return operand1 < operand2;\n case Operator.LE:\n return operand1 <= operand2;\n case Operator.GE:\n return operand1 >= operand2;\n case Operator.GT:\n return operand1 > operand2;\n case Operator.IN:\n // `includes` is called on an operand of any type, so its return value is not guaranteed to be a\n // boolean; a missing or non-callable `includes` yields undefined and therefore false. NOT_IN negates\n // exactly this, so a right operand that reports no membership at all is IN false and NOT_IN true.\n return Boolean(operand2?.includes?.(operand1));\n case Operator.NOT_IN:\n return !operand2?.includes?.(operand1);\n case Operator.INCLUDES:\n return isString(operand1) && isString(operand2) && operand1.indexOf(operand2) >= 0;\n case Operator.NOT_INCLUDES:\n return !(isString(operand1) && isString(operand2) && operand1.indexOf(operand2) >= 0);\n\n default:\n throw new Error(`Operator not implemented ${this.operator}`);\n }\n }\n\n /**\n * Recursively collects all fields used in this statement and its nested statements\n * @returns A set of all fields used in this statement\n */\n collectFields(): Set<FieldBase> {\n const fields = new Set<FieldBase>();\n\n function processOperand(op: OperandType) {\n if (op instanceof FieldBase) {\n fields.add(op);\n } else if (op instanceof Statement) {\n // For nested statements, merge their fields with our collection\n const nestedFields = op.collectFields();\n nestedFields.forEach((field) => fields.add(field));\n }\n }\n processOperand(this.operand1);\n processOperand(this.operand2);\n\n return fields;\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ExecuteActionClassIdentifier = Symbol('ExecuteAction');\n\nexport class ExecuteAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, params: any) => any) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ExecuteActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, params: any): any {\n return super.execute(field, supr, params);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ListItemAddedActionClassIdentifier = Symbol('ListItemAddedAction');\n\nexport class ListItemAddedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, item: any, index: number) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ListItemAddedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, item: any, index: number): void {\n return super.execute(field, supr, item, index);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ListItemRemovedActionClassIdentifier = Symbol('ListItemRemovedAction');\n\nexport class ListItemRemovedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, item: any, index: number) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ListItemRemovedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, item: any, index: number): void {\n return super.execute(field, supr, item, index);\n }\n}\n","import { type Access, defaultAccess } from './access';\nimport type { Container } from './container';\nimport type { FieldBase } from './field-base';\nimport type { Group } from './group';\nimport type { ListValue } from './list';\nimport { ValidationError } from './validators/validation-error';\nimport { defaultVisibility, type Visibility } from './visibility';\n\n/**\n * The mutable state of one element, held in an object of its own beside the element rather than in the element's\n * own properties.\n *\n * An element reaches it through two views of that one object, both in private class fields of `FieldBase`:\n * `this.state` is `reactive(slots)` and `this.raw` is the object itself. A slot read through `state` inside a\n * render effect or a computed subscribes that effect to the slot, and a write to the slot re-runs it. The\n * bookkeeping an element does for itself goes through `raw`, which neither records a read nor announces a write.\n * The value cache of a container goes through `raw` in particular: its getter writes the cache while it runs, and\n * a tracked write there costs the reading effect one extra evaluation, and one extra render on mount, for a value\n * it has already built.\n *\n * Being private class fields is what puts the two views out of reach of everything outside `FieldBase`: a private\n * field is absent from `Object.keys`, `JSON.stringify`, `Object.getOwnPropertySymbols` and lodash `getAllKeys` by\n * construction, and needs no per-instance property definition to be. Both `JSON.stringify` and lodash `isEqual`\n * walk their way down a structure over own keys, enumerable symbols included, and the `parent` slot is in the\n * state: reachable, it would take either walker back into the container the element came from.\n *\n * What they do reach on an element is `_actions` once something is registered, `_fields` and the guarded view\n * over it on a `Group`, and `_itemTemplate` on a `List`. All of them lead downwards only.\n */\nexport interface ElementSlots<T = any> {\n /** the value the element was given at construction; isChanged compares against it */\n originalValue: T;\n /**\n * What the last ValueChangedAction reported the element as holding - its value, and a container's fullValue; the\n * next transaction measures its net change against it\n */\n announcedValue: T;\n /**\n * What the last ContributionChangedAction reported the element as contributing to its container: its value,\n * `null`, or `undefined` for nothing\n */\n announcedContribution: unknown;\n /**\n * What a container's own validators last ran over - what it sends; the next transaction runs them where that\n * moved. A leaf's validators run at the write and the access switch, and leave it untouched.\n */\n validatedValue: unknown;\n errors: ValidationError[];\n visibility: Visibility;\n access: Access;\n /** counts the writes that changed the value of the element or of anything below it */\n valueVersion: number;\n /** how many asynchronous validation runs are in flight on this element */\n validatingCount: number;\n /** how many direct children answer `validating` with true; a child that starts or stops running moves it */\n validatingChildren: number;\n /** the container that holds this element, absent while none does; takeChild writes it, releaseChild clears it */\n parent: Container | undefined;\n /** the name the containing Group holds this element under; a List row carries none */\n fieldName: string | undefined;\n /** generation of the validators attached to the element; clearValidators() raises it */\n validationEpoch: number;\n /**\n * The extended properties the element carries, typed by the element's own X parameter. A write replaces the\n * object rather than writing into it, so an effect that read the slot re-runs on the write, and the object a\n * transaction captured is the one a rollback puts back.\n */\n extra: object;\n /**\n * The element this one was bound from, absent on an element that was declared rather than bound. It is what lets\n * an action shared by every binding work out which binding of a second element it means: `declaration` is the\n * canonical one, so a binding of a binding names the element the whole family was declared as.\n */\n declaration: FieldBase | undefined;\n\n // the slots below are the element's own bookkeeping - nothing reads them inside an effect, and they are\n // therefore reached through raw\n\n /** the verdict the last commit announced, which is what a change of validity is measured against */\n valid: boolean;\n /** number of direct children whose last announced verdict was invalid */\n invalidChildren: number;\n}\n\n/** what an element's extended properties start as: one frozen object for all of them, since a write replaces it */\nconst noExtra = Object.freeze({});\n\nexport function elementSlots<T = any>(): ElementSlots<T> {\n return {\n originalValue: undefined!,\n announcedValue: undefined!,\n announcedContribution: undefined,\n validatedValue: undefined,\n errors: [],\n visibility: defaultVisibility,\n access: defaultAccess,\n valueVersion: 0,\n validatingCount: 0,\n validatingChildren: 0,\n parent: undefined,\n fieldName: undefined,\n validationEpoch: 0,\n declaration: undefined,\n extra: noExtra,\n valid: true,\n invalidChildren: 0,\n };\n}\n\n/** what a Field holds beyond the common slots: the value itself, and whether it has been touched */\nexport interface FieldSlots<T = any> extends ElementSlots<T> {\n value: T;\n touched: boolean;\n}\n\nexport function fieldSlots<T = any>(): FieldSlots<T> {\n return { ...elementSlots<T>(), value: undefined!, touched: false };\n}\n\n/**\n * What a container holds beyond the common slots: the object the value getter last built, together with the\n * version of the tree it was built from.\n */\nexport interface ContainerSlots<T = any> extends ElementSlots<T> {\n cachedValue: T;\n cachedValueVersion: number;\n}\n\nexport function containerSlots<T = any>(): ContainerSlots<T> {\n return {\n ...elementSlots<T>(),\n announcedValue: null,\n cachedValue: null,\n cachedValueVersion: -1,\n } as ContainerSlots<T>;\n}\n\n/** what a Group holds beyond the container slots: the names of its members, in the order it took them */\nexport interface GroupSlots<T = any> extends ContainerSlots<T> {\n /**\n * The names the group holds its members under. The member map itself is a plain object beside the state, so\n * this array is what a reader inside an effect depends on: a member added or removed re-runs the effect, and a\n * rolled-back transaction puts the set back with the rest of the slots.\n */\n fieldNames: string[];\n}\n\nexport function groupSlots<T = any>(): GroupSlots<T> {\n return { ...containerSlots<T>(), fieldNames: [] } as GroupSlots<T>;\n}\n\n/** what a List holds beyond the container slots: the rows themselves */\nexport interface ListSlots<R extends FieldBase = Group> extends ContainerSlots<ListValue<R>> {\n rows: R[] | null;\n /**\n * Counts the changes to the set of rows. `items` rebuilds the frozen array it hands out when it moves, and\n * only then: a write inside a row changes what the list serializes without changing which rows it holds.\n */\n rowsVersion: number;\n /** the frozen array `items` last handed out, together with the rows version it was built from */\n cachedItems: readonly R[] | null;\n cachedItemsVersion: number;\n}\n\nexport function listSlots<R extends FieldBase = Group>(): ListSlots<R> {\n return { ...containerSlots<ListValue<R>>(), rows: null, rowsVersion: 0, cachedItems: null, cachedItemsVersion: -1 };\n}\n","import { type FieldSlots, fieldSlots } from './element-state';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\nimport { transactional } from './transaction';\n\nclass Field<T = any, X extends object = Extras> extends FieldBase<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Field';\n }\n\n protected get state(): FieldSlots<T> {\n return super.state as FieldSlots<T>;\n }\n\n protected get raw(): FieldSlots<T> {\n return super.raw as FieldSlots<T>;\n }\n\n /** the value slot itself, without the notifications the value setter carries around a write */\n protected get _value(): T {\n return this.state.value;\n }\n\n protected set _value(newValue: T) {\n this.state.value = newValue;\n }\n\n constructor(params?: IFieldParams<T, X>) {\n super(fieldSlots<T>());\n this.init(params);\n }\n\n /**\n * Applies the constructor parameters. It is a hook so that a subclass needing different parameter handling\n * overrides one method instead of redeclaring the constructor - Action does exactly that.\n *\n * It is called from this constructor, so it runs before a subclass's own class field initializers, which\n * only run once super() returns. An override must therefore work off its parameters alone: members the\n * subclass initializes read as undefined inside it, and anything it writes to such a member is overwritten\n * the moment the initializer runs.\n */\n protected init(params?: IFieldParams<T, X>) {\n transactional(() => {\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // registration precedes the assignment of the remaining parameters, so a *Changing* action supplied here\n // guards them too\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n // an absent value falls back to originalValue, an explicit null does not: null is a value a caller means\n this._value = paramValue !== undefined ? paramValue : this.originalValue;\n }\n this.constructed(params);\n // a field the caller gave no baseline is baselined on the value its construction ends on, which is what the\n // hook above leaves\n if (this.originalValue === undefined) this.originalValue = this._value;\n // the value a construction ends on is the field's first statement about itself rather than a change of one,\n // so it is recorded as announced and the commit that follows says nothing about it\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n get value() {\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n // a field takes the write whatever its access: access decides what the field sends and whether an input\n // accepts typing, and a record loaded into the form reaches every member\n if (oldValue === newValue) return;\n transactional((tx) => {\n tx.touch(this);\n this._value = newValue;\n this.bumpValueVersion();\n // the validators run here rather than at the announcement, because the verdict they reach is what the\n // commit announces. They read what the field sends, which a write changes only where the field sends its\n // value: one that sends nothing or null sends the same after the write\n if (this.serializesAs('value') === 'value') this.boundActions?.triggerEager(this, newValue, oldValue);\n // the handlers hear about the change once the transaction closes, over the value the field ends up holding\n this.propagateValueChanged();\n });\n }\n\n get touched(): boolean {\n return this.state.touched;\n }\n\n set touched(touched: boolean) {\n this.touchState();\n this.state.touched = touched;\n }\n\n bind(data?: T, overrides?: IBindParams<T, X>): this {\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (params?: IFieldParams<T, X>) => this;\n const res = new Ctor({\n // data is what the caller supplied, and undefined is not supplied; an explicit null is, and clears\n value: data !== undefined ? data : this.value,\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<T, X>);\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n return res;\n }\n}\n\nexport { Field };\n\nexport type NullableField<T = any> = Field<T> | null;\n","import { ref, type Ref } from 'vue';\n\nimport { ExecuteAction } from './actions';\nimport { Field } from './field';\nimport { type Extras, IFieldParams } from './field.interface';\nimport { transactional } from './transaction';\n\n/**\n * The value an `Action` holds. Both members are `unknown` because `Action` states the concept and a UI library\n * states what it renders: a subclass declares its value type with `label` and `icon` in whatever shape it renders\n * them - `string | MdString`, a per-breakpoint object - and the accessors below answer at that type, because they\n * read it off `T` rather than fixing one of their own.\n *\n * The consequence for an `Action` built without a type argument is that reading either member answers `unknown`\n * and the reader states what it expects. That is the shape the class is for; an application that renders actions\n * uses the subclass its UI library ships.\n */\nexport interface ActionValue {\n label?: unknown;\n icon?: unknown;\n}\n\n/**\n * How many executions of an action have yet to settle, held outside the action it belongs to and allocated for\n * an action the first time one is asked of it. An action nobody executes and nobody reads `busy` on carries no\n * counter at all, and the ones that do carry a Vue ref: a button rendering off `busy` re-renders when the count\n * moves away from zero and back.\n */\nconst busyCounters = new WeakMap<object, Ref<number>>();\n\n/**\n * The value object where any member of it states something, and undefined where none does. A member holding\n * `null` or `undefined` states nothing, so `{}` and the pair of `undefined`s an action starts from state nothing.\n *\n * `T` is whatever a subclass widened the value to, so an object naming a render style, a name or a set of\n * per-breakpoint options and no label is an object that states something.\n */\nfunction stated<T extends ActionValue>(val: T | undefined): T | undefined {\n if (val == null) return undefined;\n return Object.values(val).some((member) => member != null) ? val : undefined;\n}\n\nexport class Action<\n T extends ActionValue = ActionValue,\n X extends object = Omit<Extras, keyof ActionValue>,\n> extends Field<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Action';\n }\n\n protected init(params?: IFieldParams<T, X>) {\n transactional(() => {\n // an Action's value is always a shaped object, so an action that is handed nothing holds the pair of\n // undefined members rather than undefined itself\n this._value = { label: undefined, icon: undefined } as T;\n if (params) {\n const { value: paramValue, originalValue, validators, actions, ...otherParams } = params;\n // registration precedes the assignment of the remaining parameters, so a *Changing* action supplied here\n // guards them too\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n const val = stated(paramValue);\n const org = stated(originalValue);\n // a value that was stated is kept by identity, so a reactive object passed in stays linked to the action;\n // where none was, the action holds a copy of the baseline, never the frozen baseline itself\n if (val) this._value = val;\n else if (org) this._value = { ...org };\n // the baseline carries exactly the members it was declared with: isChanged is a structural comparison,\n // which reads own-key sets, so an action reads as unchanged from construction, and so does every\n // container above it, where the baseline is shaped like the value it baselines\n if (org) this.originalValue = Object.freeze({ ...org }) as T;\n }\n this.constructed(params);\n // an action nothing declared a baseline for is baselined on the value its construction ends on - the value\n // itself, so the two carry the same members - and that value is what the hook above leaves\n if (this.originalValue === undefined) this.originalValue = this._value;\n // the value a construction ends on is the action's first statement about itself rather than a change of one\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n /**\n * A copy of the value this action holds, carrying one member rewritten. A member handed undefined is dropped\n * from the copy rather than written into it: an own key holding undefined is invisible to a reader and to\n * JSON, but lodash isEqual compares own-key sets, so writing one would leave the action permanently changed\n * against a baseline that never carried the key.\n */\n private valueWith(member: keyof ActionValue, newValue: T[keyof ActionValue]): T {\n const res: ActionValue = { ...this.value };\n if (newValue === undefined) delete res[member];\n else res[member] = newValue;\n return res as T;\n }\n\n get icon(): T['icon'] {\n return this.value.icon;\n }\n\n set icon(newValue: T['icon']) {\n if (this.value.icon === newValue) return;\n this.value = this.valueWith('icon', newValue);\n }\n\n get label(): T['label'] {\n return this.value.label;\n }\n\n /**\n * The two setters hand the value setter a new object rather than writing into the one the action holds, so each\n * is an ordinary value change: the handlers fire and isChanged answers over it.\n * The new object is built only for a member that differs from the one held - the value setter compares by\n * identity and every copy is a new object, so without the comparison here a write of the value already held\n * would announce a change and invalidate the value cache of every container above.\n */\n set label(newValue: T['label']) {\n if (this.value.label === newValue) return;\n this.value = this.valueWith('label', newValue);\n }\n\n /** the counter behind `busy`, allocated for this action the first time it is asked for */\n private get busyRuns(): Ref<number> {\n let runs = busyCounters.get(this);\n if (!runs) {\n runs = ref(0);\n busyCounters.set(this, runs);\n }\n return runs;\n }\n\n /** true from the moment execute() is called until the handler it ran has settled, however it settles */\n get busy(): boolean {\n return this.busyRuns.value > 0;\n }\n\n /**\n * Runs the ExecuteAction chain registered on this action and answers what the chain returned. `busy` stands for\n * the length of the run: the chain is entered synchronously, and the flag is cleared once the value it produced\n * has settled - a handler that returns a promise holds it for as long as that promise takes, and one that\n * rejects clears it as it rejects.\n *\n * The answer is a promise whatever the handler returns, so a handler that throws rejects it rather than throwing\n * out of this call: a caller that does not await the answer and does not attach a catch handler leaves that\n * rejection unhandled. An `AbortEventHandlingException` is the one exception that does not reject: the answer\n * resolves with it, in a synchronous chain as in an asynchronous one.\n */\n async execute(params?: any): Promise<any> {\n const runs = this.busyRuns;\n runs.value++;\n try {\n return await this.triggerAction(ExecuteAction, params);\n } finally {\n runs.value--;\n }\n }\n}\n\nexport type NullableAction = Action | null;\n","<template>\n <render />\n</template>\n\n<script setup lang=\"ts\">\nimport { h, resolveComponent } from 'vue';\n\nimport { ClassTypes, ValidationError } from '../validators';\n\ninterface Props {\n message: string | ValidationError[];\n classes?: ClassTypes;\n}\n\nconst props = defineProps<Props>();\nconst md = resolveComponent('vue-markdown');\nconst htmlElements = new Set([\n 'div',\n 'span',\n 'p',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'section',\n 'article',\n 'aside',\n 'nav',\n 'header',\n 'footer',\n 'main',\n 'figure',\n 'figcaption',\n 'blockquote',\n 'pre',\n 'code',\n 'em',\n 'strong',\n 'small',\n 'mark',\n 'del',\n 'ins',\n 'sub',\n 'sup',\n 'i',\n 'b',\n 'u',\n 's',\n 'a',\n 'img',\n 'button',\n 'input',\n 'textarea',\n 'select',\n 'option',\n 'label',\n 'form',\n 'table',\n 'tr',\n 'td',\n 'th',\n 'thead',\n 'tbody',\n 'tfoot',\n 'ul',\n 'ol',\n 'li',\n 'dl',\n 'dt',\n 'dd',\n]);\n\nconst render = () => {\n if (typeof props.message === 'string') return h('span', { class: props.classes }, props.message);\n const res: ReturnType<typeof h>[] = [];\n props.message.forEach((msg) => {\n switch (msg.componentName) {\n case 'template':\n res.push(h('div', { class: [props.classes, msg.extraClasses] }, msg.componentBody));\n break;\n case 'vue-markdown':\n if (typeof md === 'string') {\n console.warn(\n \"You are using markdown for messages-widget, but you haven't registered a vue-markdown component\",\n );\n res.push(h('div', { class: [props.classes, msg.extraClasses] }, (<any>msg.componentBindings).source));\n } else {\n const componentBindings = <any>msg.componentBindings;\n res.push(\n h(md, {\n class: [props.classes, msg.extraClasses, 'df-messages-widget-markdown'],\n source: componentBindings.source,\n options: componentBindings.options,\n plugins: componentBindings.plugins,\n }),\n );\n }\n break;\n default:\n res.push(\n h(\n htmlElements.has(msg.componentName.toLowerCase()) // only resolve if it's not a common html element\n ? msg.componentName\n : resolveComponent(msg.componentName),\n {\n class: [props.classes, msg.extraClasses],\n ...msg.componentBindings,\n ...(msg.componentBody ? { innerHTML: msg.componentBody } : {}),\n },\n ),\n );\n break;\n }\n });\n return res;\n};\n</script>\n\n<style>\n/* we would like there to be no margins for markdown at the very top and very bottom. the rest of it is fine */\n.df-messages-widget-markdown > :first-child,\n.df-messages-widget-markdown > :last-child {\n margin-top: 0 !important;\n padding-top: 0 !important;\n margin-bottom: 0 !important;\n padding-bottom: 0 !important;\n line-height: 1.35em !important; /* inspired by vitepress' aggressive settings */\n}\n</style>\n","<template>\n <render />\n</template>\n\n<script setup lang=\"ts\">\nimport { h, resolveComponent } from 'vue';\n\nimport { ClassTypes, ValidationError } from '../validators';\n\ninterface Props {\n message: string | ValidationError[];\n classes?: ClassTypes;\n}\n\nconst props = defineProps<Props>();\nconst md = resolveComponent('vue-markdown');\nconst htmlElements = new Set([\n 'div',\n 'span',\n 'p',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'section',\n 'article',\n 'aside',\n 'nav',\n 'header',\n 'footer',\n 'main',\n 'figure',\n 'figcaption',\n 'blockquote',\n 'pre',\n 'code',\n 'em',\n 'strong',\n 'small',\n 'mark',\n 'del',\n 'ins',\n 'sub',\n 'sup',\n 'i',\n 'b',\n 'u',\n 's',\n 'a',\n 'img',\n 'button',\n 'input',\n 'textarea',\n 'select',\n 'option',\n 'label',\n 'form',\n 'table',\n 'tr',\n 'td',\n 'th',\n 'thead',\n 'tbody',\n 'tfoot',\n 'ul',\n 'ol',\n 'li',\n 'dl',\n 'dt',\n 'dd',\n]);\n\nconst render = () => {\n if (typeof props.message === 'string') return h('span', { class: props.classes }, props.message);\n const res: ReturnType<typeof h>[] = [];\n props.message.forEach((msg) => {\n switch (msg.componentName) {\n case 'template':\n res.push(h('div', { class: [props.classes, msg.extraClasses] }, msg.componentBody));\n break;\n case 'vue-markdown':\n if (typeof md === 'string') {\n console.warn(\n \"You are using markdown for messages-widget, but you haven't registered a vue-markdown component\",\n );\n res.push(h('div', { class: [props.classes, msg.extraClasses] }, (<any>msg.componentBindings).source));\n } else {\n const componentBindings = <any>msg.componentBindings;\n res.push(\n h(md, {\n class: [props.classes, msg.extraClasses, 'df-messages-widget-markdown'],\n source: componentBindings.source,\n options: componentBindings.options,\n plugins: componentBindings.plugins,\n }),\n );\n }\n break;\n default:\n res.push(\n h(\n htmlElements.has(msg.componentName.toLowerCase()) // only resolve if it's not a common html element\n ? msg.componentName\n : resolveComponent(msg.componentName),\n {\n class: [props.classes, msg.extraClasses],\n ...msg.componentBindings,\n ...(msg.componentBody ? { innerHTML: msg.componentBody } : {}),\n },\n ),\n );\n break;\n }\n });\n return res;\n};\n</script>\n\n<style>\n/* we would like there to be no margins for markdown at the very top and very bottom. the rest of it is fine */\n.df-messages-widget-markdown > :first-child,\n.df-messages-widget-markdown > :last-child {\n margin-top: 0 !important;\n padding-top: 0 !important;\n margin-bottom: 0 !important;\n padding-bottom: 0 !important;\n line-height: 1.35em !important; /* inspired by vitepress' aggressive settings */\n}\n</style>\n","import { computed, type ComputedRef } from 'vue';\n\nimport { FieldBase } from './field-base';\nimport { type Extras } from './field.interface';\nimport { transactional } from './transaction';\n\n/**\n * The computed behind a container's `valid`, held outside the element it belongs to. A computed refers back to\n * itself through its dependency record, and JSON.stringify and lodash isEqual both walk own enumerable\n * properties, so an element carrying one as a property would be a cycle to either of them.\n */\nconst validReads = new WeakMap<object, ComputedRef<boolean>>();\n\n/** The computed behind a container's `busy`, held outside the element for the same reason `validReads` is. */\nconst busyReads = new WeakMap<object, ComputedRef<boolean>>();\n\n/**\n * A form element that holds other elements and composes its state out of theirs: `Group`, which holds named\n * members, and `List`, which holds rows. Every element's `parent` is a `Container`.\n *\n * What a container answers for over its children is the same whatever holds them: `valid` and `busy` are composed\n * of theirs, `touched` is true where any child is touched and propagates an assignment down, `validate(true)`\n * revalidates every child before the container forms its own verdict, and a child's change of value or verdict\n * reaches the container through `notifyValueChanged()` and the tallies below. How the children are reached - by\n * name or by position - is the subclass's.\n */\nexport abstract class Container<T = any, X extends object = Extras> extends FieldBase<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Container';\n }\n\n /**\n * The children this container holds, read through the tracked view of its state: a verdict or a flag composed\n * over them is formed again when a child is added or removed.\n */\n protected abstract get children(): readonly FieldBase[];\n\n get touched(): boolean {\n return this.children.some((child) => child.touched);\n }\n\n set touched(touched: boolean) {\n transactional(() => {\n this.members.forEach((child) => {\n child.touched = touched;\n });\n });\n }\n\n get valid(): boolean {\n return this.validRead;\n }\n\n get busy(): boolean {\n return this.busyRead;\n }\n\n validate(revalidate: boolean = false) {\n transactional(() => {\n // the children are revalidated first and the container forms its own verdict afterwards, over the finished\n // set: a child that turns valid while a later one is still to be checked announces nothing until the\n // transaction closes, so the container never reports a verdict over a half-revalidated set\n if (revalidate) this.members.forEach((child) => child.validate(true));\n super.validate(revalidate);\n });\n }\n\n /**\n * Records that a child changed its value, so that the transaction in progress works out at commit what this\n * container's own value became and announces it once. The mutation methods call it themselves; you rarely need\n * to.\n */\n notifyValueChanged() {\n this.propagateValueChanged();\n }\n\n protected get composesValue(): boolean {\n return true;\n }\n\n /**\n * A container with nothing listening for what it holds does not compose it at all, so the copy it keeps is from\n * before the changes nobody received. A registration that adds a listener brings it up to date here, and what\n * the listener is then told about is the change that follows it.\n */\n protected refreshPreviousValue(): void {\n super.refreshPreviousValue();\n this.raw.announcedValue = this.holding;\n }\n\n /** A container holds every member's value whatever the member sends: its `fullValue`. */\n protected get holding(): any {\n return this.fullValue;\n }\n\n /**\n * The composed verdict `valid` answers with, memoised by Vue. The walk over the children is what makes an error\n * pushed into one of them visible without a validate() call, and the computed keeps that walk from repeating\n * while nothing it read has moved.\n */\n private get validRead(): boolean {\n let read = validReads.get(this);\n if (!read) {\n read = computed(\n () =>\n this.state.errors.length === 0 &&\n // a child that sends nothing is not the container's to answer for\n this.children.every((child) => child.valid || this.childSerializesAs(child, 'value') === 'omit'),\n );\n validReads.set(this, read);\n }\n return read.value;\n }\n\n /**\n * The composed answer `busy` gives, memoised by Vue. An `Action` counts its executions in a counter of its own,\n * which no container is told about, so the answer is composed over the children instead of tallied; the computed\n * keeps the walk from repeating while nothing it read has moved, and a child that is itself a container answers\n * from its own computed.\n */\n private get busyRead(): boolean {\n let read = busyReads.get(this);\n if (!read) {\n read = computed(() => this.children.some((child) => child.busy));\n busyReads.set(this, read);\n }\n return read.value;\n }\n\n /**\n * Records that a child started or stopped answering `validating` with true, and carries the transition further\n * up where it changes this container's own answer.\n */\n protected childValidatingChanged(started: boolean): void {\n const wasValidating = this.validating;\n this.state.validatingChildren += started ? 1 : -1;\n if (this.validating !== wasValidating) this.parent?.childValidatingChanged(started);\n }\n\n /**\n * Records a child's new verdict in this container's tally. The child reports it as it settles, and the commit\n * settles the deepest element first, so the tally a container reads when its own turn comes is finished. The\n * delta is applied here rather than recomputed by walking the children at commit, which would cost\n * `O(children)` per container and turn a list fill back into the quadratic walk this tally exists to avoid.\n */\n protected childValidityChanged(nowValid: boolean): void {\n this.raw.invalidChildren += nowValid ? -1 : 1;\n }\n}\n","import { isEmpty } from 'lodash-es';\n\nimport { Container } from './container';\nimport { type GroupSlots, groupSlots } from './element-state';\nimport { Field } from './field';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\nimport { transactional, TxCapture, type TxSnapshot } from './transaction';\n\nexport type GenericFieldsInterface = Record<string, FieldBase>;\n/**\n * Converts a field structure into the matching value structure. The indexed access reads each field's value\n * getter, so a nested Group contributes its own value structure and a List contributes its row array; inferring\n * from FieldBase<infer U> instead would pick up the value setter, which is deliberately wider than the getter on\n * Group. Every member may be `null`, because a member whose access is `'disabled-null'` contributes `null` in place\n * of its value.\n */\nexport type FieldsToValues<T extends GenericFieldsInterface> = {\n [K in keyof T]: T[K]['value'] | null;\n};\n\n/**\n * What Group.fullValue reads back. The indexed access reads each field's fullValue getter, so a nested group\n * contributes its own full structure rather than the partial one its `value` builds. Every member is present\n * whatever its access.\n */\nexport type FieldsToFullValues<T extends GenericFieldsInterface> = {\n [K in keyof T]: T[K]['fullValue'];\n};\n\n/**\n * What Group.value reads back: the values of the members that serialize, and `{}` where none does. Every key is\n * optional, because a member whose access is `'disabled'` is left out of the object the group builds.\n */\nexport type GroupValue<T extends GenericFieldsInterface> = Partial<FieldsToValues<T>>;\n/** what Group.value and the Group constructor accept: keys left out are simply not assigned, and null clears */\nexport type GroupValueInput<T extends GenericFieldsInterface> = Partial<FieldsToValues<T>> | null;\n\n/**\n * The groups whose constructor is still taking and writing their members. A member's record is completed once the\n * constructor has written the data it was given, so a rule that reads a sibling runs over that data rather than\n * over the values the members were bound with.\n */\nconst assembling = new WeakSet<object>();\n\n/** the value a group none of whose members serializes reads back; it is frozen like every value a group builds */\nconst emptyGroupValue = Object.freeze({});\n\n/**\n * The guarded view of a group's member map, held outside the group it belongs to. It is a proxy over the very map\n * the group writes into, so an element carrying it as a property would be walked twice by JSON.stringify and by\n * lodash isEqual, both of which go down a structure over own keys.\n */\nconst fieldsViews = new WeakMap<object, GenericFieldsInterface>();\n\n/**\n * The handler behind that view. Every read goes through `track` first, which reads the group's name array - the\n * part of the state that says which members the group holds - so a reader inside an effect re-runs when\n * addField() or removeField() changes the set; the map itself is beside the state, and a write to it would\n * otherwise reach nobody.\n *\n * Every write is refused: a field assigned into the map, or one deleted out of it, would never receive parent,\n * fieldName or change notifications, and the group would go on counting the verdict of a member it no longer\n * holds. addField() and removeField() are the way the set of members changes.\n */\nconst fieldsAreReadOnly = (track: () => number): ProxyHandler<GenericFieldsInterface> => ({\n get(target, key, receiver) {\n track();\n return Reflect.get(target, key, receiver);\n },\n has(target, key) {\n track();\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n track();\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n track();\n return Reflect.getOwnPropertyDescriptor(target, key);\n },\n set(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be assigned: use addField() to give the group a member`);\n },\n defineProperty(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be redefined: use addField() to give the group a member`);\n },\n deleteProperty(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be deleted: use removeField() to take a member out`);\n },\n});\n\nexport class Group<\n T extends GenericFieldsInterface = GenericFieldsInterface,\n X extends object = Extras,\n> extends Container<GroupValue<T>, X> {\n get [Symbol.toStringTag](): string {\n return 'Group';\n }\n\n protected get state(): GroupSlots<GroupValue<T>> {\n return super.state as GroupSlots<GroupValue<T>>;\n }\n\n protected get raw(): GroupSlots<GroupValue<T>> {\n return super.raw as GroupSlots<GroupValue<T>>;\n }\n\n private readonly _fields: T;\n\n constructor(fields: T, params?: IFieldParams<GroupValueInput<T>, X>) {\n super(groupSlots<GroupValue<T>>());\n\n if (!Group.isValidFields(fields)) throw new Error('Invalid fields object provided');\n // the backing map has no prototype: a field may be named after an Object.prototype member, and on an\n // ordinary object a `__proto__` key would go to the inherited setter instead of becoming a field\n this._fields = Object.create(null) as T;\n\n // construction is one transaction: the members are taken and written before anything is announced, and a\n // member that refuses to be taken - one another container already holds - leaves behind no half-built group\n transactional(() => {\n assembling.add(this);\n try {\n Object.entries(fields).forEach(([name, field]) => this.addField(name, field));\n\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // registration precedes the assignment of the remaining parameters, so a *Changing* action supplied here\n // guards them too\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n // an assignment is made only for a value the caller actually supplied, and undefined is not one: spreading\n // an optional property yields an undefined value, and assigning it would push null into every member and\n // then baseline that emptied state as the original, so the group would report itself unchanged over values\n // its members never held. An explicit null is a supplied value and does clear the members.\n if (paramValue !== undefined) this.assignMembers(paramValue as GroupValueInput<T>);\n else if (this.originalValue !== undefined) this.assignMembers(this.originalValue);\n }\n } finally {\n assembling.delete(this);\n }\n\n // the members are in place and hold their values, so this is the record they were promised: a member whose\n // eager pass ran before the group existed - every member of a bound group - gets it here\n this.completeRecords();\n\n this.constructed(params);\n\n // reading value walks every member and builds an object, so it is read once here and the result serves\n // every reader below\n const constructedValue = this.value;\n if (this.originalValue === undefined) this.originalValue = Group.baseline(constructedValue);\n\n // the state a construction ends on is the group's first statement about itself rather than a change of one:\n // recording it as announced is what keeps the commit from reporting the members' assignment as a change of\n // the group, and it is what the first later change of a member is reported against\n this.recordAnnounced();\n\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n /**\n * The name array is copied as well: a rollback puts back the set of members the group held, not the array it\n * went on to hold.\n */\n protected [TxCapture](): TxSnapshot {\n const captured = super[TxCapture]();\n captured.fieldNames = [...this.raw.fieldNames];\n return captured;\n }\n\n /**\n * The copy of a built value that serves as a baseline. The value getter hands out one object per version, and\n * a baseline holding that same object would report every value as its own original.\n */\n private static baseline<V extends GenericFieldsInterface>(value: GroupValue<V>): GroupValue<V> {\n return value == null ? value : { ...value };\n }\n\n /**\n * Takes `field` into this group under `fieldName`. The group ends up holding it exactly as it holds a field the\n * constructor was given: the field carries the back-reference and the name, its verdict counts towards the\n * group's, and a rule of the field's that names another member of the form reaches it here.\n *\n * The change is announced through the ordinary path, so a group whose value the new field adds to says so once\n * the transaction closes, and its verdict is re-formed over the members it now holds. The baseline behind\n * `isChanged` is not rewritten: a group that gains a field holds something its original value does not carry,\n * and reports itself changed until `originalValue` is written.\n *\n * @throws Error where this group already holds a field under `fieldName`.\n * @throws TypeError where `field` already belongs to a container - pass a `bind()` of it instead.\n */\n addField(fieldName: string, field: FieldBase): this {\n transactional((tx) => {\n if (Object.hasOwn(this._fields, fieldName)) {\n throw new Error(`Field ${fieldName} is already in this form`);\n }\n // takeChild refuses a field that another group or list already holds, and installs the back-reference and\n // the name together\n this.takeChild(field, fieldName);\n tx.touch(this);\n Group.setEntry(this._fields, fieldName, field);\n // the map is not part of the state a snapshot covers, so the removal is handed to the transaction as its own\n // undo; the name array is in the state and a rollback puts it back with everything else\n tx.whenRolledBack(() => Group.dropEntry(this._fields, fieldName));\n this.state.fieldNames.push(fieldName);\n // the field now reaches the form this group stands in, so a rule of its own that names a field up there -\n // one no record below could answer - is run over it here. A group still being constructed completes its\n // members once it has written the data it was given.\n if (!assembling.has(this)) this.completeRecords(field);\n this.bumpValueVersion();\n this.notifyValueChanged();\n });\n return this;\n }\n\n /**\n * Takes the field held under `fieldName` out of this group and hands it back, answering undefined where the\n * group holds no field of that name. The field is released whole: the back-reference and the name are gone, its\n * verdict and its runs in flight no longer count towards the group's, and it is free to be taken by another\n * container. What it holds - its value, its errors, the change history behind `isChanged` - is its own to report.\n *\n * The change is announced through the ordinary path, so the group's value and verdict settle over the members it\n * has left. The baseline behind `isChanged` is not rewritten, the same way it is not on `addField`.\n */\n removeField(fieldName: string): FieldBase | undefined {\n let removed: FieldBase | undefined;\n transactional((tx) => {\n if (!Object.hasOwn(this._fields, fieldName)) return;\n const field: FieldBase = this._fields[fieldName];\n tx.touch(this);\n this.releaseChild(field);\n Group.dropEntry(this._fields, fieldName);\n tx.whenRolledBack(() => Group.setEntry(this._fields, fieldName, field));\n this.state.fieldNames.splice(this.state.fieldNames.indexOf(fieldName), 1);\n this.bumpValueVersion();\n this.notifyValueChanged();\n removed = field;\n });\n return removed;\n }\n\n /**\n * Writes one entry of the member map. The map is typed by the fields interface, which names the members a group\n * of that type holds and no others, so both here and in dropEntry it is reached as the plain record it is.\n */\n private static setEntry(fields: GenericFieldsInterface, fieldName: string, field: FieldBase): void {\n (fields as Record<string, FieldBase>)[fieldName] = field;\n }\n\n /** Drops one entry out of the member map. */\n private static dropEntry(fields: GenericFieldsInterface, fieldName: string): void {\n delete (fields as Record<string, FieldBase | undefined>)[fieldName];\n }\n\n private static isValidFields(flds: unknown): flds is Record<string, FieldBase> {\n function isFieldAll(field: unknown): field is FieldBase {\n return field instanceof FieldBase;\n }\n\n return typeof flds === 'object' && flds !== null && Object.entries(flds).every(([, field]) => isFieldAll(field));\n }\n\n static createFromFormData(data: Record<string, any> | null): Group {\n if (data instanceof FieldBase) {\n throw new Error('data is already a Form structure, should be a simple object');\n }\n return new Group(\n data == null ? {} : Object.fromEntries(Object.entries(data).map(([key, value]) => [key, new Field({ value })])),\n );\n }\n\n field<K extends keyof T>(fieldName: K): T[K] | null {\n return this._fields[fieldName] ?? null;\n }\n\n /**\n * The typed map of this group's members. What it hands out is a view over the map the group holds: reading it\n * reaches the members themselves, and every write to it is refused - addField() and removeField() are what\n * change the set. The view is built the first time something asks for it.\n *\n * Reading through it is a tracked read of the set of members, so a template rendering off `group.fields`\n * re-renders when a field is added or removed; what a member itself holds is tracked by that member.\n */\n get fields(): T {\n let view = fieldsViews.get(this);\n if (!view) {\n view = new Proxy(\n this._fields,\n fieldsAreReadOnly(() => this.state.fieldNames.length),\n );\n fieldsViews.set(this, view);\n }\n return view as T;\n }\n\n protected get members(): FieldBase[] {\n return this.raw.fieldNames.map((name) => this._fields[name]);\n }\n\n protected get children(): readonly FieldBase[] {\n // the names are read through the tracked view, so a member added or removed re-forms what is composed over\n // them; the members themselves are reached through the map, which is beside the state\n return this.state.fieldNames.map((name) => this._fields[name]);\n }\n\n get value(): GroupValue<T> {\n // the version is a tracked read and the cache is not, so a reader that is answered from the cache still\n // depends on every write below this group without the walk being repeated for it\n const version = this.valueVersion;\n if (this.raw.cachedValueVersion === version) return this.raw.cachedValue;\n\n // accumulate without a prototype so a field named `__proto__` is stored instead of reassigning the\n // accumulator's prototype; the spread on return hands back an ordinary object\n const val = Object.create(null) as Record<string, any>;\n Object.entries(this._fields).forEach(([name, field]) => {\n switch (this.childSerializesAs(field, 'value')) {\n case 'value':\n val[name] = field.value;\n break;\n case 'null':\n val[name] = null;\n break;\n case 'omit':\n break;\n }\n });\n // the object outlives the read that built it - the next reader is answered with the very same one - so it is\n // frozen: a caller writing into it would change what the group reports without any member holding that value.\n // A group that serializes at all serializes as an object, so one none of whose members contributes reads {}.\n const built = (isEmpty(val) ? emptyGroupValue : Object.freeze({ ...val })) as GroupValue<T>;\n this.raw.cachedValue = built;\n this.raw.cachedValueVersion = version;\n return built;\n }\n\n /**\n * Writes the members that the given value carries. The members are written one by one and the group says\n * nothing in between: the transaction the assignment runs in measures the group's own value and its own verdict\n * once, over the finished set, and announces each at most once.\n */\n private assignMembers(newValue: GroupValueInput<T>) {\n transactional(() => {\n Object.entries(this._fields).forEach(([name, field]) => {\n if (newValue == null || Object.hasOwn(newValue, name)) {\n field.value = newValue == null ? null : newValue[name];\n }\n });\n });\n }\n\n set value(newValue: GroupValueInput<T>) {\n transactional((tx) => {\n this.assignMembers(newValue);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Members are reset one by one rather than assigned as a whole value: the value setter writes only the keys the\n * value carries, while a member the value leaves out has to end up holding what the template gives it. `source`\n * supplies that per member, so a group reset from the template it was bound from matches a fresh binding of it.\n */\n protected resetTo(source: FieldBase, value: any): void {\n const template = source as Group<T>;\n transactional((tx) => {\n tx.touch(this);\n if (this.errors.length) this.errors = [];\n Object.entries(this._fields).forEach(([name, field]) => {\n // a key the value does not carry leaves the member to the template; a null value clears every member,\n // the same way assigning null does\n let memberValue: any;\n if (value === null) memberValue = null;\n else if (value !== undefined && Object.hasOwn(value, name)) memberValue = value[name];\n this.resetChild(field, template.field(name) ?? field, memberValue);\n });\n // a group brought to the state a fresh one would be in makes no statement of its own about the change: the\n // container that reset it announces the whole of it\n this.recordAnnounced();\n this.originalValue = Group.baseline(this.value);\n super.validate(true);\n });\n }\n\n /**\n * Everything the group holds: every member's `fullValue`, whatever the member's access. Where `value` states what\n * the group sends, this states what it holds, and it is what a binding of the group carries.\n */\n get fullValue(): FieldsToFullValues<T> {\n const value = Object.create(null) as Record<string, any>;\n Object.entries(this._fields).forEach(([name, field]) => {\n value[name] = field.fullValue;\n });\n return { ...value } as FieldsToFullValues<T>;\n }\n\n /**\n * States that `res` was built from the members handed to it. A subclass whose constructor takes something other\n * than `(fields, params)` - one that composes its own members and passes them to super - never sees them, and\n * would answer with a binding carrying the declaration's data instead of the record's. That is a difference no\n * reader would find, so it is refused here rather than returned.\n */\n private static assertTookFields(res: Group<any, any>, fields: object, name: string): void {\n // the members are compared by identity rather than by name: a subclass that composes its own set arrives at\n // the same names, and it is the instances carrying the record's data that have to be the ones it took on\n const asked = Object.entries(fields) as [string, FieldBase][];\n const got = res.raw.fieldNames;\n if (asked.length === got.length && asked.every(([key, field]) => res._fields[key] === field)) return;\n throw new TypeError(\n `${name}.bind() built an element that did not take the members it was given, so the binding would carry ` +\n `the declaration's data. A subclass whose constructor does not take (fields, params) has to override ` +\n 'bind() and construct itself.',\n );\n }\n\n bind(data?: GroupValueInput<T>, overrides?: IBindParams<GroupValueInput<T>, X>): Group<T, X> {\n const newFields = Object.create(null) as T;\n Object.entries(this._fields).forEach(([name, field]) => {\n newFields[name as keyof T] = field.bind() as any;\n });\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (fields: T, params?: IFieldParams<GroupValueInput<T>, X>) => Group<T, X>;\n const res = new Ctor(newFields, {\n // data is what the caller supplied, and undefined is not supplied; an explicit null is, and clears. What the\n // group holds is carried rather than what it sends, so a member that sends nothing keeps its data\n value: data !== undefined ? data : (this.fullValue as GroupValueInput<T>),\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<GroupValueInput<T>, X>);\n Group.assertTookFields(res, newFields, this.constructor.name);\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n return res;\n }\n\n /**\n * A record need not name every member: a key it leaves out is taken from the declaration, the same way a member\n * the constructor is given no value for takes the one it was declared with.\n */\n rebind(data: GroupValueInput<T>): this {\n return super.rebind(data as GroupValue<T>);\n }\n}\n\nexport type NullableGroup = Group | null;\n","import { isEqual as structuralEqual, isEqualWith } from 'lodash-es';\n\nimport { FieldBase } from './field-base';\n\n/**\n * Compares `a` against `b`, wherever either side is a `FieldBase`, by comparing what it holds rather than the\n * element itself: a structural comparison of two elements reaches nothing, their state being in private class\n * fields. `undefined` defers to lodash's own structural comparison, which is what lets this reach an element\n * nested inside a plain object or an array — `list.items`, a `Map`, a hand-built record — at any depth.\n */\nfunction customizer(a: unknown, b: unknown): boolean | undefined {\n const aValue = a instanceof FieldBase ? a.value : a;\n const bValue = b instanceof FieldBase ? b.value : b;\n return aValue === a && bValue === b ? undefined : structuralEqual(aValue, bValue);\n}\n\n/**\n * Structural equality that treats a `FieldBase` as what it holds. `isEqual(fieldA, fieldB)` and\n * `isEqual(list.items, other.items)` compare values the way `isEqual(fieldA.value, fieldB.value)` already does,\n * without a call site having to unwrap every element by hand.\n *\n * Two `FieldBase` operands skip `isEqualWith`'s dispatch and compare `.value` directly — about 40% faster than\n * routing the same comparison through the customizer, measured comparing two single-field elements.\n */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (a instanceof FieldBase && b instanceof FieldBase) return structuralEqual(a.value, b.value);\n return isEqualWith(a, b, customizer);\n}\n","import { isPlainObject } from 'lodash-es';\n\nimport { ListItemAddedAction, ListItemRemovedAction } from './actions';\nimport { Container } from './container';\nimport { type ListSlots, listSlots } from './element-state';\nimport { Field } from './field';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\nimport { Group } from './group';\nimport { transactional, TxCapture, type TxSnapshot } from './transaction';\n\n/**\n * What a List of R reads back: the value of each row it sends, `null` for a row whose access is `'disabled-null'`,\n * and `[]` while it sends none\n */\nexport type ListValue<R extends FieldBase = Group> = (R['value'] | null)[];\n/** what List.value and the List constructor accept: an array of rows, or null, which empties the list */\nexport type ListValueInput<R extends FieldBase = Group> = ListValue<R> | null;\n/** what List.fullValue reads back: the full value of every row, whatever its access */\nexport type ListFullValue<R extends FieldBase = Group> = R['fullValue'][];\n\n/** the value a list without rows reads back; it is frozen like every value a list builds */\nconst emptyListValue: readonly any[] = Object.freeze([]);\n\nexport class List<R extends FieldBase = Group, X extends object = Extras> extends Container<ListValue<R>, X> {\n get [Symbol.toStringTag](): string {\n return 'List';\n }\n\n protected get state(): ListSlots<R> {\n return super.state as ListSlots<R>;\n }\n\n protected get raw(): ListSlots<R> {\n return super.raw as ListSlots<R>;\n }\n\n private _itemTemplate?: R;\n\n constructor(itemTemplate?: undefined, params?: IFieldParams<ListValueInput<R>, X>);\n constructor(itemTemplate: R, params?: IFieldParams<ListValueInput<R>, X>);\n constructor(itemTemplate?: R, params?: IFieldParams<ListValueInput<R>, X>) {\n super(listSlots<R>());\n\n this._itemTemplate = itemTemplate;\n\n // construction is one transaction, so the rows are all in place before anything is announced\n transactional(() => {\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // registration precedes the assignment of the remaining parameters, so a *Changing* action supplied here\n // guards them too\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n\n // an assignment is made only for a value the caller actually supplied, and undefined is not one: spreading\n // an optional property yields an undefined value, so a list declared with an originalValue alone takes\n // its rows from that. An explicit null is a supplied value and leaves the list empty, which is the state\n // it starts in.\n if (paramValue !== undefined) this.setValueInternal(paramValue);\n else if (this.originalValue !== undefined) this.setValueInternal(this.originalValue);\n }\n\n this.constructed(params);\n\n if (this.originalValue === undefined) this.originalValue = List.baseline(this.value);\n // the set a construction ends on is the list's first statement about itself rather than a change of one, so\n // the commit that closes the construction says nothing about it\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n /** The row array is copied as well: a rollback puts back the set the list held, not the array it went on to hold. */\n protected [TxCapture](): TxSnapshot {\n const captured = super[TxCapture]();\n captured.rows = this.raw.rows ? [...this.raw.rows] : this.raw.rows;\n return captured;\n }\n\n /**\n * The copy of a built value that serves as a baseline. The value getter hands out one array per version, and a\n * baseline holding that same array would report every value as its own original.\n */\n private static baseline<V extends any[] | null>(value: V): V {\n return (value == null ? value : [...value]) as V;\n }\n\n private processSetValueItem(item: any): R {\n let res: R;\n // an item that is already an element is taken as it is, and data is bound to the item template\n if (item instanceof FieldBase) res = item as R;\n else if (this._itemTemplate) res = this._itemTemplate.bind(item) as R;\n else res = List.elementFor(item) as R;\n\n // an item that already belongs to a container is refused here; one this list released earlier carries no\n // link any more and is taken like any other\n this.takeChild(res);\n // the row now reaches the form this list stands in, so a rule of its own that names a field up there - one no\n // record below could answer - is run over it here\n this.completeRecords(res);\n\n return res;\n }\n\n /**\n * The row a list without an item template builds from `item`: a `Group` of fields from a plain object, a `List`\n * from an array, and a `Field` holding anything else.\n */\n private static elementFor(item: unknown): FieldBase {\n if (isPlainObject(item)) return Group.createFromFormData(item as Record<string, any>);\n if (Array.isArray(item)) return new List(undefined, { value: item });\n return new Field({ value: item });\n }\n\n /**\n * Builds the item that fills a gap left by an insert beyond the end of the list: the item template bound to its\n * own values, or, where the list has no template, an empty element of the kind `item` is built into.\n */\n private createPaddingItem(item: unknown): R {\n if (this._itemTemplate) return this.processSetValueItem(this._itemTemplate.bind());\n if (item instanceof Group || isPlainObject(item)) return this.processSetValueItem({});\n if (item instanceof List || Array.isArray(item)) return this.processSetValueItem([]);\n return this.processSetValueItem(undefined);\n }\n\n /** Records that the set of rows changed, so `items` rebuilds the frozen array it hands out at the next read. */\n private rowsChanged(): void {\n this.state.rowsVersion++;\n }\n\n /** True where `next` is a different set of rows than `previous`: another count, or another row at a position. */\n private static rowsDiffer(previous: FieldBase[] | null, next: FieldBase[] | null): boolean {\n const before = previous ?? [];\n const after = next ?? [];\n return before.length !== after.length || before.some((row, index) => row !== after[index]);\n }\n\n private setValueInternal(newValue: readonly unknown[] | null) {\n // a list holds rows, and nothing but an array states a set of them. The check stands before the transaction\n // opens, so a refused value leaves the rows the list holds exactly as they were.\n if (newValue != null && !Array.isArray(newValue)) {\n throw new TypeError('Invalid value provided: a list takes an array of rows, or null to empty it');\n }\n transactional((tx) => {\n tx.touch(this);\n // the set standing before the write, so that only an assignment that actually changes it makes `items` build\n // a new array: an assignment every row survives leaves the array a reader took as it is\n const held = this.raw.rows;\n // null is the value that clears, the same one Group.value = null writes into every member; without this a\n // list nested in a group would keep its rows while every sibling field was emptied\n if (newValue == null) {\n this.releaseRows();\n this.state.rows = null;\n } else {\n const previous = this.state.rows ?? [];\n // the new set is built beside the one in place and installed whole: writing a row runs its validators, and\n // one reading this list in the middle of the walk must not be shown a position that has yet to be filled\n const rows: R[] = new Array(newValue.length);\n for (let index = 0; index < newValue.length; index++) {\n const item = newValue[index];\n const row = previous[index];\n // a row already standing at this index takes the new item, so its identity survives the assignment and\n // a keyed v-for keeps the component rendering it. It needs an item template: a list without one builds\n // every row from its own data, so two rows need not carry the same members and writing one row's data\n // into another's members would drop whatever they do not have in common. The row is reset rather than\n // assigned, so it ends up as the row built for this position would have been.\n if (row && this._itemTemplate && !(item instanceof FieldBase)) {\n this.resetChild(row, this._itemTemplate, item);\n rows[index] = row;\n } else {\n if (row) this.releaseChild(row);\n rows[index] = this.processSetValueItem(item);\n }\n }\n for (let index = newValue.length; index < previous.length; index++) this.releaseChild(previous[index]);\n this.state.rows = rows;\n }\n if (List.rowsDiffer(held, this.raw.rows)) this.rowsChanged();\n this.bumpValueVersion();\n });\n }\n\n get value(): ListValue<R> {\n // the version is a tracked read and the cache is not, so a reader that is answered from the cache still\n // depends on every write below this list without the walk over its rows being repeated for it\n const version = this.valueVersion;\n if (this.raw.cachedValueVersion === version) return this.raw.cachedValue;\n\n const value: unknown[] = [];\n (this.state.rows ?? []).forEach((row) => {\n switch (this.childSerializesAs(row, 'value')) {\n case 'value':\n value.push(row.value);\n break;\n case 'null':\n value.push(null);\n break;\n case 'omit':\n break;\n }\n });\n // the array outlives the read that built it - the next reader is answered with the very same one - so it is\n // frozen, as is every row object in it; a caller writing into either would change what the list reports\n // without any row holding that value. A list without rows reads [].\n const built = (value.length ? Object.freeze(value) : emptyListValue) as ListValue<R>;\n this.raw.cachedValue = built;\n this.raw.cachedValueVersion = version;\n return built;\n }\n\n set value(newValue: ListValueInput<R>) {\n transactional(() => {\n this.setValueInternal(newValue);\n // an assignment is a statement about the whole list, and it is announced as one without being compared away\n this.propagateValueChanged(true);\n });\n }\n\n /**\n * The rows are taken from `source` where the caller supplied no value of its own, so a list nested in a row that\n * a whole-list assignment reuses ends up holding what the template gives it rather than what it held before.\n */\n protected resetTo(source: FieldBase, value: any): void {\n transactional((tx) => {\n tx.touch(this);\n if (this.errors.length) this.errors = [];\n this.setValueInternal(value === undefined ? (source as List<R>).fullValue : value);\n // a list brought to the state a fresh one would be in makes no statement of its own: the container that\n // reset it announces the whole of it\n this.recordAnnounced();\n this.originalValue = List.baseline(this.value);\n super.validate(true);\n });\n }\n\n bind(data?: ListValueInput<R>, overrides?: IBindParams<ListValueInput<R>, X>): List<R, X> {\n const template = this._itemTemplate?.bind() as R | undefined;\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (itemTemplate?: R, params?: IFieldParams<ListValueInput<R>, X>) => List<R, X>;\n const res = new Ctor(template, {\n // data is what the caller supplied, and undefined is not supplied; an explicit null is, and clears. What the\n // list holds is carried rather than what it sends, so a row that sends nothing keeps its data\n value: [...((data !== undefined ? data : this.fullValue) ?? [])],\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<ListValueInput<R>, X>);\n // a subclass whose constructor does not take (itemTemplate, params) never sees either, so it would answer\n // with a list built from its own declaration rather than from this record. That is a difference no reader\n // would find, so it is refused here rather than returned.\n if (res._itemTemplate !== template) {\n throw new TypeError(\n `${this.constructor.name}.bind() built a list that did not take the item template it was given, so the ` +\n \"binding would carry the declaration's rows. A subclass whose constructor does not take \" +\n '(itemTemplate, params) has to override bind() and construct itself.',\n );\n }\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n return res;\n }\n\n protected get members(): FieldBase[] {\n return this.raw.rows ?? [];\n }\n\n protected get children(): readonly FieldBase[] {\n return this.state.rows ?? [];\n }\n\n /**\n * The full value of every row. Where `value` states what the list sends, this states what the list holds: every\n * row whatever its access, and a group row carrying every field of its own. It is what a binding or a reset\n * carries.\n */\n get fullValue(): ListFullValue<R> {\n return (this.state.rows ?? []).map((row) => row.fullValue);\n }\n\n /**\n * How many rows this list holds. The read is tracked, so a template rendering off it re-renders as rows come and\n * go.\n */\n get length(): number {\n return this.state.rows?.length ?? 0;\n }\n\n /**\n * The rows this list holds, oldest position first. The array is a frozen copy: it states what the list held at\n * the read and nothing writes back through it - `push`, `insert`, `remove` and `clear` are what change the set -\n * so a caller may hold on to it. The rows in it are the live elements, so reading one reports what it holds now.\n *\n * The copy is built once per change of the set and handed to every reader until the next one: a write inside a\n * row changes what the list serializes without changing which rows it holds, and the array a reader took stays\n * the same one across such a write.\n */\n get items(): readonly R[] {\n // the version is a tracked read and the cache is not, so a reader answered from the cache still re-runs when\n // the set of rows changes\n const version = this.state.rowsVersion;\n if (this.raw.cachedItemsVersion !== version) {\n this.raw.cachedItems = Object.freeze([...(this.raw.rows ?? [])]);\n this.raw.cachedItemsVersion = version;\n }\n return this.raw.cachedItems!;\n }\n\n get(index: number): R | undefined {\n return this.state.rows != null ? this.state.rows[index] : undefined;\n }\n\n push(item: any): number {\n return this.insert(item, this.state.rows?.length ?? 0) + 1;\n }\n\n pop(): R | undefined {\n return this.remove((this.state.rows?.length ?? 0) - 1);\n }\n\n remove(index: number): R | undefined {\n let removedItem: R | undefined;\n transactional((tx) => {\n if (this.state.rows == null || index < 0 || this.state.rows.length <= index) return;\n\n // the row array is recorded before the splice, so a rollback puts back the set the list held\n tx.touch(this);\n const row = this.state.rows.splice(index, 1)?.[0];\n if (!row) return;\n\n // the row itself is what leaves the list: releaseChild has taken the back-reference away, so it carries\n // nothing of the list it stood in and is free to be taken by another container, and what it holds - the\n // values it ended up with, its errors, the change history behind isChanged - is the row's to report\n this.releaseChild(row);\n this.rowsChanged();\n this.bumpValueVersion();\n removedItem = row;\n\n // an item removed is a fact about an operation and has no net over a transaction, so it is queued in order\n // rather than compared away, and the commit emits it before the value the removal left behind\n tx.recordStructural(this, { actionClass: ListItemRemovedAction, item: removedItem, index });\n // one item fewer is a different set, so no comparison is needed to establish that the value changed\n this.propagateValueChanged(true);\n });\n\n return removedItem;\n }\n\n insert(item: any, index: number): number {\n let position = 0;\n transactional((tx) => {\n tx.touch(this);\n if (this.state.rows == null) this.state.rows = [];\n // a negative index counts back from the end and stops at the start, the way splice reads it, so the\n // position announced and returned is the one the item actually occupies\n position = index < 0 ? Math.max(this.state.rows.length + index, 0) : index;\n while (this.state.rows.length < position) {\n // if the index is too large for current array size, we add as many as necessary\n const itm = this.createPaddingItem(item);\n // push returns the new length, while the event carries the index of the item that was added\n const idx = this.state.rows.push(itm) - 1;\n this.bumpValueVersion();\n tx.recordStructural(this, { actionClass: ListItemAddedAction, item: itm, index: idx });\n }\n const itm = this.processSetValueItem(item);\n this.state.rows.splice(position, 0, itm);\n\n tx.recordStructural(this, { actionClass: ListItemAddedAction, item: itm, index: position });\n // one item more is a different set, so no comparison is needed to establish that the value changed\n this.rowsChanged();\n this.bumpValueVersion();\n this.propagateValueChanged(true);\n });\n\n return position;\n }\n\n /** Drops every row this list holds out of its tally, so a row that changes its verdict later is not counted. */\n private releaseRows(): void {\n this.state.rows?.forEach((row) => this.releaseChild(row));\n }\n\n clear() {\n transactional((tx) => {\n const hadItems = (this.state.rows?.length ?? 0) > 0;\n tx.touch(this);\n this.releaseRows();\n this.state.rows = null;\n // a list that held nothing holds the same nothing afterwards, so the array `items` hands out stands\n if (hadItems) this.rowsChanged();\n this.bumpValueVersion();\n this.propagateValueChanged(hadItems);\n });\n }\n}\n\nexport type NullableList = List | null;\n","import { unref } from 'vue';\n\nimport { ValueChangedAction } from '../actions';\nimport { bindingsIn, resolveByName, resolveInScope, scopeOf } from '../binding/resolve';\nimport type { FieldBase } from '../field-base';\n\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator, ValidatorBindingState } from './validator';\n\n/**\n * How the field to compare against is named. A field names it directly, a string names it by the name its\n * container holds it under, and a callback works it out from the field being validated. All three answer for the\n * record the validation is running over: handed the field of a `List`'s item template, a row compares against that\n * row's field.\n */\nexport type CompareToTarget = FieldBase | string | ((field: FieldBase) => FieldBase | null | undefined);\n\n/** What the validator remembers about one field it validates. */\ninterface CompareToBindingState<T> extends ValidatorBindingState {\n oldValue: T;\n}\n\nexport default class CompareTo<T = any> extends Validator {\n private readonly otherField: CompareToTarget;\n\n /**\n * The fields this validator is registered on. Registration reaches one element at a time - the rows of a list\n * take the validator on one by one, as they are built from the item template that carries it - so this is what\n * says which of the fields a declaration stands for actually carry the rule, and a field that never took it on\n * is left alone by a change of the compared field.\n */\n private readonly registrations = new WeakSet<FieldBase>();\n\n /**\n * The fields this validator has installed its listener on. A binding of such a field carries the listener too -\n * a binding takes on the actions of the field it was bound from - so the field it was bound from is what is\n * asked about as well, and a list of a thousand rows installs one listener rather than a thousand.\n */\n private readonly listening = new WeakSet<FieldBase>();\n\n /**\n * What the fields this validator was registered on were declared as. One entry stands for every binding of such a\n * field, so a change of a compared field finds the fields of the record that change happened in without a list\n * of a thousand rows being held here.\n */\n private readonly declarations = new Set<FieldBase>();\n\n constructor(\n otherField: CompareToTarget,\n private isValidComparison: (myValue: T, otherValue: T) => boolean,\n message: RenderContentRef,\n ) {\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n this.comparisonState(field).oldValue = oldValue;\n\n const other = this.resolve(field);\n // a record that does not hold the compared field yet - a row still being built - reaches no verdict, and\n // the container that finishes the record runs this pass again over the field it then holds\n if (!other) {\n field.markRecordIncomplete();\n return null;\n }\n this.listenOn(other);\n\n if (!this.isValidComparison(unref(newValue), unref(other.value))) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(message, { newValue, oldValue, field, otherField: other }),\n '',\n 'compare-to',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n this.otherField = otherField;\n }\n\n /** The field `field` is compared against, within the record `field` belongs to. */\n private resolve(field: FieldBase): FieldBase | undefined {\n const other = this.otherField;\n if (typeof other === 'function') return other(field) ?? undefined;\n if (typeof other === 'string') return resolveByName(other, field);\n return resolveInScope(other, scopeOf(field));\n }\n\n /**\n * Makes a change of `other` re-run this comparison. The listener re-runs it over the fields of the record the\n * change happened in rather than over the field that installed it, so the listener a row inherits with the field\n * it was bound from serves that row; and it re-runs this one validator, not the chain around it.\n */\n private listenOn(other: FieldBase): void {\n if (this.listening.has(other) || this.listening.has(other.declaration)) return;\n this.listening.add(other);\n other.registerAction(\n new ValueChangedAction((oField, supr, oNewValue, oOldValue) => {\n supr(oField, oNewValue, oOldValue);\n const scope = scopeOf(oField);\n this.declarations.forEach((declaration) =>\n bindingsIn(declaration, scope).forEach((mine) => {\n // the fields a declaration stands for are the candidates; the ones that took the validator on are the\n // ones re-validated, so a rule written for one row of a list stays that row's rule\n if (!this.registrations.has(mine)) return;\n this.execute(mine, () => null, mine.contribution, this.comparisonState(mine).oldValue);\n }),\n );\n }),\n );\n }\n\n boundToBinding(binding: FieldBase) {\n this.declarations.add(binding.declaration);\n this.registrations.add(binding);\n }\n\n private comparisonState(field: FieldBase): CompareToBindingState<T> {\n return this.bindingState(field) as CompareToBindingState<T>;\n }\n\n protected newBindingState(): CompareToBindingState<T> {\n return { ...super.newBindingState(), oldValue: undefined as T };\n }\n\n unregisterFrom(binding: FieldBase) {\n // the errors this validator put on the binding go with the registration: the base method withdraws them, forms\n // the verdict over what is left and cancels the run in flight, and a binding that no longer carries the rule is\n // dropped from the set the compared field re-validates\n super.unregisterFrom(binding);\n this.registrations.delete(binding);\n }\n}\n","import { truncate } from 'lodash-es';\nimport { type Ref, unref } from 'vue';\n\nimport type { FieldBase } from '../field-base';\n\nimport { translatedMessage } from './translations';\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator } from './validator';\n\n/**\n * The values a field may hold: a fixed list, or a reference or a callback for a list that is filled in or replaced\n * after the validator is built - the options a server answers with, or the ones another field's value leaves open.\n */\nexport type AllowedValues<T> = T[] | Ref<T[]> | (() => T[]);\n\nexport default class InAllowedValues<T = any> extends Validator {\n constructor(allowedValues: AllowedValues<T>, message?: RenderContentRef) {\n const msg = message || translatedMessage('InAllowedValues');\n // the list is read at each validation rather than at construction, so a list that arrives later is the one the\n // value is measured against and the one the message names\n const resolve = (): T[] => {\n const values = unref(allowedValues);\n return typeof values === 'function' ? values() : values;\n };\n const asText = (values: T[]): string => {\n const text = values.join(', ');\n if (text.length <= 60) return text;\n return truncate(text, { length: 40, separator: ', ', omission: `... (${values.length} items total)` });\n };\n\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n const values = resolve();\n if (!values.includes(unref(newValue))) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, {\n newValue,\n oldValue,\n field,\n allowedValues: values,\n allowedAsText: asText(values),\n }),\n '',\n 'in-allowed-values',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { isArray, isObject, isString } from 'lodash-es';\nimport { isRef, unref } from 'vue';\n\nimport type { FieldBase } from '../field-base';\n\nimport { translatedMessage } from './translations';\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator } from './validator';\n\nfunction toLength(a: any): number {\n if (a == null) return 0;\n if (isArray(a)) return a.length;\n if (isString(a)) return a.length;\n if (isObject(a) && Object.getPrototypeOf(a) === Object.prototype) return Object.keys(a).length;\n return String(a).length;\n}\n\n/** How the value is read before its length is taken. */\nexport interface RequiredOptions {\n /**\n * Whether a string is trimmed before it is measured, so that whitespace alone is no value. Defaults to true.\n * Set it to false where the spaces are part of what the field holds.\n */\n trim?: boolean;\n}\n\n/**\n * Tells the two first arguments apart. Every form a message takes is a string, a String subclass, a function, a\n * reference or an object naming a component; an object that is none of those is the options.\n */\nfunction isOptions(arg?: RenderContentRef | RequiredOptions): arg is RequiredOptions {\n return (\n typeof arg === 'object' && arg !== null && !isRef(arg) && !(arg instanceof String) && !('componentName' in arg)\n );\n}\n\nexport default class Required extends Validator {\n constructor(options?: RequiredOptions);\n constructor(message?: RenderContentRef, options?: RequiredOptions);\n constructor(messageOrOptions?: RenderContentRef | RequiredOptions, options?: RequiredOptions) {\n const message = isOptions(messageOrOptions) ? undefined : messageOrOptions;\n const trim = (isOptions(messageOrOptions) ? messageOrOptions : options)?.trim ?? true;\n const msg = message || translatedMessage('Required');\n const validationFn: ValidationFunction = (newValue, oldValue, field: FieldBase) => {\n const value = unref(newValue);\n if (toLength(trim && isString(value) ? value.trim() : value) === 0) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field }),\n '',\n 'required',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import type { FieldBase } from '../field-base';\n\nimport { translatedMessage } from './translations';\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator } from './validator';\n\nexport class MinValue<T = any> extends Validator {\n constructor(minValue: T, message?: RenderContentRef) {\n const msg = message || translatedMessage('MinValue');\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n if (newValue < minValue || newValue === undefined) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, minValue }),\n '',\n 'min',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class MaxValue<T = any> extends Validator {\n constructor(maxValue: T, message?: RenderContentRef) {\n const msg = message || translatedMessage('MaxValue');\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n if (newValue > maxValue || newValue === undefined) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, maxValue }),\n '',\n 'max',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class ValueInRange<T = any> extends Validator {\n constructor(minValue: T, maxValue: T, message?: RenderContentRef) {\n const msg = message || translatedMessage('ValueInRange');\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n if (newValue < minValue || newValue > maxValue || newValue === undefined) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, minValue, maxValue }),\n '',\n 'range',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { isArray, isObject, isString } from 'lodash-es';\n\nimport type { FieldBase } from '../field-base';\n\nimport { translatedMessage } from './translations';\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator } from './validator';\n\nfunction toLength(a: any): number {\n if (a == null) return 0;\n if (isArray(a)) return a.length;\n if (isString(a)) return a.length;\n if (isObject(a) && Object.getPrototypeOf(a) === Object.prototype) return Object.keys(a).length;\n return String(a).length;\n}\n\nexport class MinLength extends Validator {\n constructor(minLength: number, message?: RenderContentRef) {\n const msg = message || translatedMessage('MinLength');\n const validationFn: ValidationFunction = (newValue, oldValue, field: FieldBase) => {\n if (toLength(newValue) < minLength) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, minLength }),\n '',\n 'min-length',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class MaxLength extends Validator {\n constructor(maxLength: number, message?: RenderContentRef) {\n const msg = message || translatedMessage('MaxLength');\n const validationFn: ValidationFunction = (newValue, oldValue, field: FieldBase) => {\n if (toLength(newValue) > maxLength) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, maxLength }),\n '',\n 'max-length',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class LengthInRange extends Validator {\n constructor(minLength: number, maxLength: number, message?: RenderContentRef) {\n const msg = message || translatedMessage('LengthInRange');\n const validationFn: ValidationFunction = (newValue, oldValue, field: FieldBase) => {\n const len = toLength(newValue);\n if (len < minLength || len > maxLength) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, minLength, maxLength }),\n '',\n 'range-length',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { unref } from 'vue';\n\nimport type { FieldBase } from '../field-base';\n\nimport { translatedMessage } from './translations';\nimport { RenderContentRef, ValidationErrorRenderContent } from './validation-error';\nimport { ValidationFunction, Validator } from './validator';\n\nexport default class Pattern extends Validator {\n constructor(pattern: RegExp, message?: RenderContentRef) {\n const msg = message || translatedMessage('Pattern');\n const validationFn: ValidationFunction = (newValue, oldValue, field: FieldBase) => {\n if (!pattern.test(String(unref(newValue)))) {\n return [\n new ValidationErrorRenderContent(\n this.replacePlaceholders(msg, { newValue, oldValue, field, pattern }),\n '',\n 'pattern',\n ),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","export * from './validator';\nexport { default as CompareTo, type CompareToTarget } from './validator-compare-to';\nexport { default as InAllowedValues, type AllowedValues } from './validator-in-allowed-values';\nexport { default as Required, type RequiredOptions } from './validator-required';\nexport * from './validator-min-max-range';\nexport * from './validator-min-max-range-length';\nexport { default as Pattern } from './validator-pattern';\n","import { Container } from './container';\nimport { FieldBase } from './field-base';\nimport { type GenericFieldsInterface, Group } from './group';\nimport { List } from './list';\nimport { transaction } from './transaction';\n\n/** a member of the form in the shape a view hands it out: the view of a container, the value of anything else */\ntype Slot<E> = E extends Container ? View<E> : E extends FieldBase ? E['value'] : never;\n\n/** the data keys of a group's view */\ntype GroupData<F extends GenericFieldsInterface> = {\n // a container is replaced through `$value`, so its key is read-only; a field's key reads and writes its value\n readonly [K in keyof F as F[K] extends Container ? K : never]: Slot<F[K]>;\n} & {\n -readonly [K in keyof F as F[K] extends Container ? never : K]: Slot<F[K]>;\n};\n\n/** what a list's view takes as a row: the data a row is built from, an element, or the view of one */\ntype RowInput<R extends FieldBase> = R['value'] | R | View<R>;\n\n/** the array a list's view is: every read an array has, and the mutations taken as the list's own operations */\ntype ListData<R extends FieldBase> = Omit<Slot<R>[], 'push' | 'unshift' | 'splice' | 'fill' | 'copyWithin'> & {\n push(...items: RowInput<R>[]): number;\n unshift(...items: RowInput<R>[]): number;\n splice(start: number, deleteCount?: number, ...items: RowInput<R>[]): Slot<R>[];\n};\n\n/**\n * An element seen as its data: the members of a group, or the rows of a list, as plain properties, and the element\n * itself as `$`. See `view()`.\n */\nexport type View<E extends FieldBase> = (E extends Group<infer F, any>\n ? GroupData<F>\n : E extends List<infer R, any>\n ? ListData<R>\n : unknown) & { readonly $: E };\n\n/** the views made so far, one per element, and the element behind each */\nconst views = new WeakMap<FieldBase, object>();\nconst elements = new WeakMap<object, FieldBase>();\n\n/** the array methods that move rows: a view carries them out as the list's own operations, rows included */\nconst listMutations = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin']);\n\nfunction isIndex(key: string | symbol): key is string {\n return typeof key === 'string' && /^(0|[1-9]\\d*)$/.test(key);\n}\n\n/** the element a view stands for, or the argument itself where it is not a view */\nfunction unwrap<T>(item: T): T | FieldBase {\n return (typeof item === 'object' && item !== null && elements.get(item as object)) || item;\n}\n\n/** a member read through a view: a container as its view, anything else as its value */\nfunction slotOf(element: FieldBase): unknown {\n return element instanceof Container ? view(element) : element.value;\n}\n\n/** writes a member through a view: its value, whatever it is */\nfunction writeSlot(element: FieldBase, value: unknown): void {\n element.value = unwrap(value) instanceof FieldBase ? (unwrap(value) as FieldBase).value : value;\n}\n\n/** the keys a view answers to on behalf of Vue and the language rather than as data */\nfunction special(key: string | symbol): { answered: boolean; value?: unknown } {\n // reactive() leaves the view as it is, and a template reads through it: every read already reaches the tracked\n // state of the element behind it\n if (key === '__v_skip') return { answered: true, value: true };\n if (typeof key === 'string' && key.startsWith('__v_')) return { answered: true, value: undefined };\n // a view is never a thenable: `await` hands it back as it is\n if (key === 'then') return { answered: true, value: undefined };\n return { answered: false };\n}\n\nfunction groupHandler(group: Group<any, any>): ProxyHandler<object> {\n const memberOf = (key: string | symbol) =>\n typeof key === 'string' && key !== '$' ? (group.field(key) ?? undefined) : undefined;\n const dataKeys = () => Object.keys(group.fields);\n return {\n get(target, key) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return group;\n if (key === Symbol.toStringTag) return 'View';\n const element = memberOf(key);\n return element ? slotOf(element) : undefined;\n },\n set(target, key, value) {\n if (key === '$') throw new TypeError('$ is the element a view stands for, and cannot be replaced');\n const element = memberOf(key);\n if (!element) throw new TypeError(`${String(key)} is not a member of this group - use $addField() to add one`);\n writeSlot(element, value);\n return true;\n },\n has(target, key) {\n return key === '$' || (typeof key === 'string' && dataKeys().includes(key));\n },\n ownKeys() {\n return dataKeys();\n },\n getOwnPropertyDescriptor(target, key) {\n if (typeof key !== 'string' || !dataKeys().includes(key)) return undefined;\n return { value: slotOf(group.fields[key]), writable: true, enumerable: true, configurable: true };\n },\n deleteProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be deleted from a view - use $removeField() to take a member out`);\n },\n defineProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be defined on a view`);\n },\n };\n}\n\nfunction listView(list: List<any, any>): unknown[] {\n // the rows a view shows, in order: every row the list holds, whatever it sends\n const shown = (): FieldBase[] => [...list.items];\n // the position in the list a view's index stands for; an index past the last shown row appends\n const positionOf = (index: number): number => {\n const rows = shown();\n return index < rows.length ? list.items.indexOf(rows[index]) : list.length;\n };\n const clamp = (index: number, length: number) => (index < 0 ? Math.max(length + index, 0) : Math.min(index, length));\n\n /** puts `rows` in place of the shown rows, keeping every row element and its state */\n const reorder = (rows: FieldBase[]) =>\n transaction(() => {\n const shownRows = shown();\n const order = list.items.map((row) => {\n const at = shownRows.indexOf(row);\n return at === -1 ? row : rows[at];\n });\n while (list.length) list.pop();\n order.forEach((row) => list.push(row));\n });\n\n const mutations: Record<string, (...args: any[]) => unknown> = {\n push: (...items: unknown[]) => {\n transaction(() => items.forEach((item) => list.push(unwrap(item))));\n return shown().length;\n },\n pop: () => {\n const rows = shown();\n if (!rows.length) return undefined;\n const slot = slotOf(rows[rows.length - 1]);\n list.remove(list.items.indexOf(rows[rows.length - 1]));\n return slot;\n },\n shift: () => {\n const rows = shown();\n if (!rows.length) return undefined;\n const slot = slotOf(rows[0]);\n list.remove(list.items.indexOf(rows[0]));\n return slot;\n },\n unshift: (...items: unknown[]) => {\n transaction(() => {\n const at = positionOf(0);\n items.forEach((item, offset) => list.insert(unwrap(item), at + offset));\n });\n return shown().length;\n },\n splice: (start: number, deleteCount?: number, ...items: unknown[]) => {\n const removed: unknown[] = [];\n transaction(() => {\n const rows = shown();\n const from = clamp(Math.trunc(start) || 0, rows.length);\n const count =\n deleteCount === undefined ? rows.length - from : Math.max(0, Math.min(deleteCount, rows.length - from));\n rows.slice(from, from + count).forEach((row) => {\n removed.push(slotOf(row));\n list.remove(list.items.indexOf(row));\n });\n const at = positionOf(from);\n items.forEach((item, offset) => list.insert(unwrap(item), at + offset));\n });\n return removed;\n },\n sort: (compare?: (a: unknown, b: unknown) => number) => {\n const rows = shown();\n const sorted = rows\n .map((row) => ({ row, slot: slotOf(row) }))\n .sort((a, b) => {\n if (compare) return compare(a.slot, b.slot);\n const x = String(a.slot);\n const y = String(b.slot);\n return x < y ? -1 : x > y ? 1 : 0;\n })\n .map(({ row }) => row);\n reorder(sorted);\n return proxy;\n },\n reverse: () => {\n reorder([...shown()].reverse());\n return proxy;\n },\n fill: () => {\n throw new TypeError('fill() is not available on a list view - assign $value instead');\n },\n copyWithin: () => {\n throw new TypeError('copyWithin() is not available on a list view - assign $value instead');\n },\n };\n\n let proxy: unknown[];\n const handler: ProxyHandler<unknown[]> = {\n get(target, key, receiver) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return list;\n if (key === 'length') return shown().length;\n if (isIndex(key)) {\n const row = shown()[Number(key)];\n return row ? slotOf(row) : undefined;\n }\n if (typeof key === 'string' && listMutations.has(key)) return mutations[key];\n // every other array member reads the view through its length and its indices\n return Reflect.get(target, key, receiver);\n },\n set(target, key, value) {\n if (key === '$') throw new TypeError('$ is the element a view stands for, and cannot be replaced');\n if (key === 'length') {\n const length = Number(value);\n const rows = shown();\n if (length > rows.length) throw new TypeError('a list view grows by push(), not by its length');\n transaction(() => rows.slice(length).forEach((row) => list.remove(list.items.indexOf(row))));\n return true;\n }\n if (isIndex(key)) {\n const index = Number(key);\n const rows = shown();\n if (index < rows.length) writeSlot(rows[index], value);\n else list.insert(unwrap(value), positionOf(rows.length) + (index - rows.length));\n return true;\n }\n throw new TypeError(`${String(key)} cannot be set on a list view`);\n },\n has(target, key) {\n if (key === '$' || key === 'length') return true;\n if (isIndex(key)) return Number(key) < shown().length;\n return Reflect.has(target, key);\n },\n ownKeys() {\n return [...shown().map((_, index) => String(index)), 'length'];\n },\n getOwnPropertyDescriptor(target, key) {\n if (key === 'length') return { value: shown().length, writable: true, enumerable: false, configurable: false };\n if (!isIndex(key) || Number(key) >= shown().length) return undefined;\n return { value: slotOf(shown()[Number(key)]), writable: true, enumerable: true, configurable: true };\n },\n deleteProperty() {\n throw new TypeError('rows cannot be deleted from a list view - use splice() or pop()');\n },\n defineProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be defined on a list view`);\n },\n };\n proxy = new Proxy<unknown[]>([], handler);\n return proxy;\n}\n\nfunction fieldHandler(field: FieldBase): ProxyHandler<object> {\n return {\n get(target, key) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return field;\n return undefined;\n },\n set(target, key) {\n throw new TypeError(`${String(key)} cannot be set on the view of a field - its value is $.value`);\n },\n has(target, key) {\n return key === '$';\n },\n ownKeys() {\n return [];\n },\n };\n}\n\n/** a group member whose name a view cannot hand out as a data key */\nfunction refuseReservedNames(group: Group<any, any>): void {\n Object.keys(group.fields).forEach((name) => {\n if (name === '$' || name === 'then' || name.startsWith('__v_')) {\n throw new TypeError(\n `A view cannot hold a member named ${name}: $ is the element the view stands for, and then and __v_* ` +\n 'are read by the language and by Vue',\n );\n }\n });\n}\n\n/**\n * The element seen as its data. A group's members and a list's rows are plain properties of the view - a field as\n * its value, a container as its own view - and `$` is the element itself: `view.$.valid`,\n * `view.$.access = 'readonly'`, `view.$.registerAction(...)`.\n *\n * A member reads what the element holds, by the rule `fullValue` follows: every member is there whatever its access,\n * so a disabled field reads and writes like any other. Every read goes\n * through the element's tracked state, so an effect reading `view.address.city` re-runs when that field changes and\n * not when another one does.\n *\n * A list's view is an array: it reads like one, and `push`, `pop`, `shift`, `unshift`, `splice`, `sort` and\n * `reverse` are carried out as the list's own operations, so every row keeps its element and its state.\n *\n * One element has one view: `view(element) === view(element)`, and `view()` of a view hands it back.\n */\nexport function view<V extends View<any>>(of: V): V;\n// eslint-disable-next-line no-redeclare\nexport function view<E extends FieldBase>(element: E): View<E>;\n// eslint-disable-next-line no-redeclare\nexport function view<E extends FieldBase>(element: E): View<E> {\n if (elements.has(element)) return element as unknown as View<E>;\n const made = views.get(element);\n if (made) return made as View<E>;\n\n let proxy: object;\n if (element instanceof Group) {\n refuseReservedNames(element);\n proxy = new Proxy({}, groupHandler(element));\n } else if (element instanceof List) {\n proxy = listView(element);\n } else {\n proxy = new Proxy({}, fieldHandler(element));\n }\n views.set(element, proxy);\n elements.set(proxy, element);\n return proxy as View<E>;\n}\n","export { type Access, accessValues, defaultAccess, isAccess } from './access';\nexport { type Visibility, visibilityValues, defaultVisibility, isVisibility } from './visibility';\n\nexport * from './actions';\nexport * from './action';\nexport * from './components';\nexport * from './container';\nexport * from './field';\nexport * from './field.interface';\nexport * from './field-base';\nexport * from './group';\nexport * from './is-equal';\nexport * from './list';\n// the symbols behind the participation protocol stay in the module: what a consumer needs is the entry point\nexport { transaction, type TransactionControl } from './transaction';\nexport * from './validators';\nexport * from './view';\n","import * as Form from './index-individual';\n\nexport * from './index-individual';\nexport { default as forms, type FormsConfig, getConfig, setConfig } from './config';\n\nexport default Form;\n"],"mappings":";;;;;;;;;;;GAkBa,IAAkC,OAAO,OAAO;CAAC;CAAY;CAAY;CAAY;AAAe,CAAC,GAGrG,KAAwB;AAGrC,SAAgB,GAAS,GAAiC;CACxD,OAAQ,EAAoC,SAAS,CAAK;AAC5D;;;ACdA,IAAa,IAA0C,OAAO,OAAO;CAAC;CAAQ;CAAa;CAAU;AAAU,CAAC,GAGnG,IAAgC;AAG7C,SAAgB,EAAa,GAAqC;CAChE,OAAQ,EAAwC,SAAS,CAAK;AAChE;;;ACfA,IAA8B,IAA9B,MAA8C;CAC5C,WAAkB,kBAA0B;EAC1C,MAAU,MAAM,kCAAkC;CACpD;CAEA,IAAW,kBAA0B;EACnC,OAAa,KAAK,YAAa;CACjC;CAEA;CAQA,yBAA0B,IAAI,QAAqB;CAEnD,YAAY,GAA4B;EACtC,KAAK,aAAa;CACpB;CAOA,MAAmB,GAAa,GAAkB;EAEhD,OADK,KAAK,OAAO,IAAI,CAAG,KAAG,KAAK,OAAO,IAAI,GAAK,EAAK,CAAC,GAC/C,KAAK,OAAO,IAAI,CAAG;CAC5B;CAEA,QAAQ,GAAkB,GAA0B,GAAG,GAAoB;EACzE,OAAO,KAAK,WAAW,GAAO,GAAM,GAAG,CAAM;CAC/C;CAEA,IAAI,QAAQ;EACV,OAAO;CACT;CAQA,eAAe,GAAoB,CAAC;CASpC,eAAe,GAAoB,CAAC;AACtC,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visibility.ts","../src/plugins/devtools/api.ts","../src/plugins.ts","../src/transaction.ts","../src/actions/field-action-base.ts","../src/field.interface.ts","../src/element-state.ts","../src/validators/error-policy.ts","../src/actions/value-changed-action.ts","../src/validators/validation-error.ts","../src/validators/validator.ts","../src/actions/actions-map.ts","../src/resolve.ts","../src/actions/conditional/conditional-statement-action.ts","../src/actions/conditional/operator.ts","../src/actions/access-actions.ts","../src/actions/contribution-changed-action.ts","../src/actions/enabled-actions.ts","../src/actions/valid-changed-action.ts","../src/actions/visibility-actions.ts","../src/field-base.ts","../src/actions/conditional/statement.ts","../src/actions/execute-action.ts","../src/actions/submit-action.ts","../src/actions/reject-action.ts","../src/actions/list-item-added-action.ts","../src/actions/list-item-removed-action.ts","../src/field.ts","../src/action.ts","../src/container.ts","../src/list.ts","../src/group.ts","../src/is-equal.ts","../src/validators/validator-compare-to.ts","../src/validators/value-checks.ts","../src/validators/validator-in-allowed-values.ts","../src/validators/validator-required.ts","../src/validators/validator-min-max-range.ts","../src/validators/validator-min-max-range-length.ts","../src/validators/validator-pattern.ts","../src/validators/index-validators.ts","../src/view.ts","../src/index-individual.ts","../src/index.ts"],"sourcesContent":["/**\n * What a form element accepts and what it sends. The four values follow HTML: `'editable'` and `'readonly'` send\n * the element's value, as an `<input>` and an `<input readonly>` are submitted, `'disabled'` sends nothing, as an\n * `<input disabled>` is omitted, and `'disabled-null'` sends `null` in place of the element's value.\n *\n * | access | accepts input | sends to its container's `value` |\n * |-------------------|---------------|----------------------------------------|\n * | `'editable'` | yes | its value |\n * | `'readonly'` | no | its value |\n * | `'disabled'` | no | nothing: the key or row is left out |\n * | `'disabled-null'` | no | `null` |\n *\n * An element that sends nothing is not counted in its container's validity. `fullValue` contains every element\n * whatever its access.\n */\nexport type Access = 'editable' | 'readonly' | 'disabled' | 'disabled-null';\n\n/** every access, in the order of the table above */\nexport const accessValues: readonly Access[] = Object.freeze(['editable', 'readonly', 'disabled', 'disabled-null']);\n\n/** The default access of an element. */\nexport const defaultAccess: Access = 'editable';\n\n/** Returns whether `value` is one of the four accesses. */\nexport function isAccess(value: unknown): value is Access {\n return (accessValues as readonly unknown[]).includes(value);\n}\n","/**\n * How a rendering layer shows a form element. It affects presentation only: what an element sends and whether it\n * is validated are determined by `access`, and visibility changes neither.\n *\n * - `'full'`: rendered and shown\n * - `'invisible'`: rendered and keeps its space in the layout, but is not painted (`visibility: hidden`)\n * - `'hidden'`: rendered but not displayed, taking no space (`display: none`)\n * - `'suppress'`: not rendered at all\n */\nexport type Visibility = 'full' | 'invisible' | 'hidden' | 'suppress';\n\n/** every visibility, from shown to not rendered */\nexport const visibilityValues: readonly Visibility[] = Object.freeze(['full', 'invisible', 'hidden', 'suppress']);\n\n/** The default visibility of an element. */\nexport const defaultVisibility: Visibility = 'full';\n\n/** Returns whether `value` is one of the four visibilities. */\nexport function isVisibility(value: unknown): value is Visibility {\n return (visibilityValues as readonly unknown[]).includes(value);\n}\n","/**\n * Vue devtools support. In development every root element is listed in a \"vue-forms\" inspector, grouped by the file\n * or the component that constructed it, and shown in the inspector of that component. The devtools are a plugin\n * built on the plugin hooks (`onElementCreated`, `onElementAdopted`, `onCommit`); the library installs it on the\n * first element built in development. In a production build (`process.env.NODE_ENV === 'production'`, which the\n * application's bundler replaces) every function here is empty, and the bundler drops the registry and the devtools\n * plugin. The condition is written out in every function: a bundler removes a branch over the replaced expression,\n * not one over a constant that holds it.\n */\nimport type { FieldBase } from '../../field-base';\nimport { installPlugin, type Plugin } from '../../plugins';\n\nimport * as registry from './registry';\nimport type { DevtoolsRegistration, StateDescription } from './registry';\n\nexport type { DevtoolsRegistration, StateDescription };\n\n/** What `configureDevtools()` sets. A member left out keeps its setting. */\nexport interface DevtoolsOptions {\n /**\n * Whether the devtools record and list elements. Defaults to true. While false, nothing is recorded or listed;\n * an element built while false is not listed after it is set back to true.\n */\n enabled?: boolean;\n /**\n * Which root elements are listed: `'opt-out'` (default) every one that is not hidden, `'opt-in'` only those\n * named with `describeState()`.\n */\n registration?: DevtoolsRegistration;\n /**\n * Whether the stack is captured when a root element is constructed, to show the file that constructed it.\n * Defaults to true. While false, an element's file is the one `describeState()` gives, or none.\n */\n location?: boolean;\n}\n\nlet enabled = true;\nlet location = true;\nlet uninstall: (() => void) | undefined;\nlet loaded = false;\n\n/** Loads the inspector once, and adds the app of the component that constructed `element` to it. */\nfunction load(element: FieldBase): void {\n if (!loaded) {\n loaded = true;\n void import('./plugin').then((plugin) => {\n plugin.install();\n registry.listed().forEach(({ element: listed }) => plugin.installFor(listed));\n });\n } else {\n void import('./plugin').then((plugin) => plugin.installFor(element));\n }\n}\n\nconst devtools: Plugin = {\n setup(context) {\n registry.useContext(context);\n },\n onElementCreated(element, binding) {\n // a binding is part of its declaration's definition and is never listed, so nothing is recorded for it\n if (binding) return;\n registry.noteElement(element, location);\n load(element);\n },\n onElementAdopted(element) {\n registry.forgetLocation(element);\n },\n onCommit() {\n registry.noteChange();\n },\n};\n\n/** Installs the devtools plugin unless it is installed or turned off. Called on every element's construction. */\nexport function installDevtools(): void {\n if (process.env.NODE_ENV !== 'production') {\n if (enabled && !uninstall) uninstall = installPlugin(devtools);\n }\n}\n\n/**\n * Names `element` for the devtools and lists it in opt-in mode. `name` replaces the element's class and number,\n * `file` the file found from the constructing code. Does nothing in a production build.\n */\nexport function describeState(element: FieldBase, description: StateDescription): void {\n if (process.env.NODE_ENV !== 'production') registry.describe(element, description);\n}\n\n/** Leaves `element` out of the devtools, or lists it again with `hidden` false. Does nothing in production. */\nexport function hideState(element: FieldBase, hidden = true): void {\n if (process.env.NODE_ENV !== 'production') registry.setHidden(element, hidden);\n}\n\n/** Sets what the devtools record and list. Does nothing in production. */\nexport function configureDevtools(options: DevtoolsOptions): void {\n if (process.env.NODE_ENV !== 'production') {\n if (options.location !== undefined) location = options.location;\n if (options.registration !== undefined) registry.setRegistration(options.registration);\n if (options.enabled !== undefined) {\n enabled = options.enabled;\n if (!enabled) {\n uninstall?.();\n uninstall = undefined;\n }\n registry.setEnabled(enabled);\n }\n }\n}\n","import type { FieldBase } from './field-base';\nimport { installDevtools } from './plugins/devtools/api';\nimport type { Transaction } from './transaction';\n\n/**\n * The method a `Field` implements for `PluginContext.changeInPlace`. It is keyed by a symbol the package does not\n * export, so it is not part of the documented API of `Field`.\n */\nexport const ChangeInPlace = Symbol('Field.changeInPlace');\n\n/** What `installPlugin()` passes to a plugin's `setup()`. */\nexport interface PluginContext {\n /**\n * Makes a write into the value a field holds a change of the field. It opens a transaction, or joins the open one,\n * and in it:\n *\n * 1. where this is the first such write since the field's last announcement, records `copy()` as the old value;\n * 2. calls `write()`;\n * 3. registers `undo()` for a rollback;\n * 4. runs the field's validators and enrols the field, so the commit fires `ValueChangedAction` with the value\n * the field holds and the recorded old value.\n *\n * `element` is a `Field`; any other element throws a `TypeError`.\n */\n changeInPlace(element: FieldBase, write: () => void, undo: () => void, copy: () => unknown): void;\n /**\n * True for an element that is part of another element's definition: a binding (an element built by `bind()`,\n * such as a row of a `List`) or a `List`'s item template.\n */\n isInternal(element: FieldBase): boolean;\n}\n\n/**\n * A plugin. Every hook is optional. The value hooks of the installed plugins run as a pipeline in the order of\n * installation: the first receives the value being written, each following one receives the previous one's result,\n * and the last result is stored.\n */\nexport interface Plugin {\n /** Called once by `installPlugin()`, with the context the plugin's other hooks use. */\n setup?(context: PluginContext): void;\n /**\n * Called on every write of the value a `Field` holds: construction, the `value` setter and `rebind()`. A rollback\n * restores the stored value without calling it. `ValueChangedAction` and `field.value` receive the stored value.\n */\n onSetValue?(value: unknown, element: FieldBase): unknown;\n /** Called on every write of `originalValue` of any element, a container's included. */\n onSetOriginalValue?(value: unknown, element: FieldBase): unknown;\n /**\n * Called at the start of every element's construction, before its parameters are applied. `binding` is true for\n * an element `bind()` builds, a row of a `List` included. The hooks run in the order of installation.\n */\n onElementCreated?(element: FieldBase, binding: boolean): void;\n /**\n * Called when a container takes `element` as its member, once the transaction that took it commits. Not called\n * where the transaction is rolled back.\n */\n onElementAdopted?(element: FieldBase): void;\n /** Called after every committed transaction, once its changes are announced. Not called after a rollback. */\n onCommit?(): void;\n}\n\nconst installed: Plugin[] = [];\nlet valueHooks: Plugin[] = [];\nlet originalValueHooks: Plugin[] = [];\nlet createdHooks: Plugin[] = [];\nlet adoptedHooks: Plugin[] = [];\nlet commitHooks: Plugin[] = [];\n\n/** the item templates of the lists built so far */\nconst itemTemplates = new WeakSet<FieldBase>();\n/** greater than zero while bind() constructs an element */\nlet bindingDepth = 0;\n\nconst context: PluginContext = {\n changeInPlace(element, write, undo, copy) {\n const target = element as unknown as Partial<Record<typeof ChangeInPlace, (...args: unknown[]) => void>>;\n const change = target[ChangeInPlace];\n if (typeof change !== 'function') throw new TypeError('changeInPlace: the element is not a Field');\n change.call(element, write, undo, copy);\n },\n isInternal(element) {\n return element.declaration !== element || itemTemplates.has(element);\n },\n};\n\nfunction collect() {\n valueHooks = installed.filter((plugin) => plugin.onSetValue);\n originalValueHooks = installed.filter((plugin) => plugin.onSetOriginalValue);\n createdHooks = installed.filter((plugin) => plugin.onElementCreated);\n adoptedHooks = installed.filter((plugin) => plugin.onElementAdopted);\n commitHooks = installed.filter((plugin) => plugin.onCommit);\n}\n\n/**\n * Installs `plugin` for every element, including the ones already built: a hook runs on the next write. A plugin\n * installed twice runs twice. Returns a function that uninstalls it; values stored while it was installed are kept\n * as they are.\n */\nexport function installPlugin(plugin: Plugin): () => void {\n installed.push(plugin);\n collect();\n plugin.setup?.(context);\n return () => {\n const index = installed.indexOf(plugin);\n if (index < 0) return;\n installed.splice(index, 1);\n collect();\n };\n}\n\n/** The value a `Field` stores for `value`: the result of the installed `onSetValue` pipeline. */\nexport function pipeValue<T>(element: FieldBase, value: T): T {\n let result: unknown = value;\n for (const plugin of valueHooks) result = plugin.onSetValue!(result, element);\n return result as T;\n}\n\n/** The value an element stores for `originalValue`: the result of the installed `onSetOriginalValue` pipeline. */\nexport function pipeOriginalValue<T>(element: FieldBase, value: T): T {\n let result: unknown = value;\n for (const plugin of originalValueHooks) result = plugin.onSetOriginalValue!(result, element);\n return result as T;\n}\n\n/** Constructs an element as a binding: `onElementCreated` receives `binding` true for it. Called by `bind()`. */\nexport function asBinding<R>(build: () => R): R {\n bindingDepth++;\n try {\n return build();\n } finally {\n bindingDepth--;\n }\n}\n\n/** Records a list's item template, which `PluginContext.isInternal` reports. Called by `List`. */\nexport function noteItemTemplate(element: FieldBase): void {\n itemTemplates.add(element);\n}\n\n/** Runs the `onElementCreated` hooks. Called by the `FieldBase` constructor. */\nexport function elementCreated(element: FieldBase): void {\n // the devtools plugin is installed on the first element built in development; the condition is written out so\n // that a production build drops the call and, with it, the devtools modules\n if (process.env.NODE_ENV !== 'production') installDevtools();\n const binding = bindingDepth > 0;\n for (const plugin of createdHooks) plugin.onElementCreated!(element, binding);\n}\n\n/**\n * Runs the `onElementAdopted` hooks once `tx` commits. Called by a container when it takes a member; nothing is\n * registered while no plugin has the hook.\n */\nexport function elementAdopted(tx: Transaction, element: FieldBase): void {\n if (adoptedHooks.length === 0) return;\n tx.whenCommitted(() => {\n for (const plugin of adoptedHooks) plugin.onElementAdopted!(element);\n });\n}\n\n/** Runs the `onCommit` hooks. Called by a transaction after its commit. */\nexport function committed(): void {\n for (const plugin of commitHooks) plugin.onCommit!();\n}\n","import type FieldActionBase from './actions/field-action-base';\nimport type { FieldBase } from './field-base';\nimport { committed } from './plugins';\n\n/**\n * A transaction is the unit in which an observer sees a change. Every mutating operation runs inside one: if the\n * caller has not opened one, the operation is its own transaction, so a single write is atomic without any action\n * at the call site.\n *\n * Writes are applied to the element immediately; only the announcement is deferred. At commit the net changes are\n * compared against the state the elements last announced and each is announced once, so a value that goes\n * A -> B -> A within one transaction is not announced. Validators run while the transaction is open, because the\n * commit announces their result; every other action fires at commit.\n *\n * A transaction cannot span an await: transaction() throws when the callback returns a thenable. Two overlapping\n * transactions therefore cannot exist, and an asynchronous validator that settles later opens its own transaction.\n */\n\n/** the slots of one element as they were when the transaction first modified it */\nexport type TxSnapshot = Record<string, any>;\n\n/** a ListItemAddedAction or ListItemRemovedAction waiting for the commit that will emit it */\nexport interface TxStructuralEvent {\n actionClass: (abstract new (...args: any[]) => FieldActionBase) & { classIdentifier: symbol };\n item: any;\n index: number;\n}\n\n/**\n * The protocol a transaction uses to call its participants. The members are symbol-keyed, so a consumer cannot\n * reach them by name or collide with them, and they are on the prototype, so a walk over an element's own keys\n * does not find them.\n */\nexport const TxCapture = Symbol('Transaction.capture');\n/** read by a validator before it runs: whether the element is not sent at all, read without tracking */\nexport const SentNowhere = Symbol('FieldBase.sentNowhere');\nexport const TxRestore = Symbol('Transaction.restore');\nexport const TxAnnounceValue = Symbol('Transaction.announceValue');\nexport const TxSettleValidity = Symbol('Transaction.settleValidity');\nexport const TxAnnounceFlags = Symbol('Transaction.announceFlags');\n\ninterface TxParticipantElement {\n readonly parent: FieldBase | undefined;\n [TxCapture](): TxSnapshot;\n [TxRestore](snapshot: TxSnapshot): void;\n [TxAnnounceValue](tx: Transaction, dirty: boolean, force: boolean, structural?: TxStructuralEvent[]): void;\n [TxSettleValidity](tx: Transaction): void;\n [TxAnnounceFlags](): void;\n}\n\n/** FieldBase declares the four members above as protected, which keeps them out of the documented API */\nfunction hooks(element: FieldBase): TxParticipantElement {\n return element as unknown as TxParticipantElement;\n}\n\ninterface Participant {\n element: FieldBase;\n /** the element's state before the transaction, captured the first time the transaction modified the element */\n snapshot?: TxSnapshot;\n /** the commit determines whether this element's value changed and announces it if it did */\n valueDirty: boolean;\n /** the caller has established that the value changed, so the commit announces it without comparing */\n forceValue: boolean;\n /** the commit recomputes this element's validity and announces a change of it */\n validityDirty: boolean;\n /** the commit announces the net change of this element's access, enabled and visibility */\n flagsDirty: boolean;\n structural?: TxStructuralEvent[];\n}\n\n/** the number of containers above an element; the commit announces the deepest first */\nfunction depthOf(element: FieldBase): number {\n let depth = 0;\n let ancestor = element.parent;\n while (ancestor) {\n depth++;\n ancestor = ancestor.parent;\n }\n return depth;\n}\n\nexport class Transaction {\n private readonly participants = new Map<FieldBase, Participant>();\n\n /** what a rollback restores beyond the state slots, newest last */\n private readonly undo: (() => void)[] = [];\n\n /** work the commit runs after the change is complete, in registration order */\n private readonly settled: (() => void)[] = [];\n\n /** true once the transaction has been rolled back; a run started inside it then announces nothing */\n private unwound = false;\n\n /** the depth the current announcement pass is processing, -1 while no pass runs */\n private passDepth = -1;\n\n /** set when, during a pass, an element is enrolled at or below the depth being processed */\n private restartPass = false;\n\n /** true for a transaction that was rolled back */\n get rolledBack(): boolean {\n return this.unwound;\n }\n\n private participant(element: FieldBase): Participant {\n let entry = this.participants.get(element);\n if (!entry) {\n entry = { element, valueDirty: false, forceValue: false, validityDirty: false, flagsDirty: false };\n this.participants.set(element, entry);\n }\n return entry;\n }\n\n /**\n * Records the state of an element the first time the transaction modifies it. The snapshot contains all of the\n * mutable state, not only the part being written: a partial restore would leave the element in a state the form\n * never had.\n */\n touch(element: FieldBase): void {\n const entry = this.participant(element);\n if (!entry.snapshot) entry.snapshot = hooks(element)[TxCapture]();\n }\n\n /** Enrols an element whose value the commit announces. `force` skips the comparison. */\n markValueChanged(element: FieldBase, force: boolean): void {\n const entry = this.participant(element);\n entry.valueDirty = true;\n if (force) entry.forceValue = true;\n this.noteDepth(element);\n }\n\n /** Enrols an element whose access or visibility changed; the commit announces the net change. */\n markFlagsDirty(element: FieldBase): void {\n this.participant(element).flagsDirty = true;\n this.noteDepth(element);\n }\n\n /** Enrols an element whose validity the commit recomputes. */\n markValidityDirty(element: FieldBase): void {\n this.participant(element).validityDirty = true;\n this.noteDepth(element);\n }\n\n /**\n * Queues an event that describes an operation, not a state. Added and removed items have no net result over a\n * transaction, so they are neither compared nor merged: the commit emits them in the order they happened.\n */\n recordStructural(element: FieldBase, event: TxStructuralEvent): void {\n const entry = this.participant(element);\n (entry.structural ??= []).push(event);\n this.noteDepth(element);\n }\n\n /** True if the commit has a pending value announcement for this element. */\n willAnnounceValue(element: FieldBase): boolean {\n return this.participants.get(element)?.valueDirty ?? false;\n }\n\n /**\n * Registers an undo step for state outside the element's state slots. The snapshot covers the slots, which is\n * everything a regular write modifies; an operation that replaces anything else registers its own undo here, so\n * the snapshot does not have to include it.\n */\n whenRolledBack(work: () => void): void {\n this.undo.push(work);\n }\n\n /**\n * Registers work that runs after the transaction commits, and not at all if it is rolled back. An operation uses\n * it to defer a step that cannot be undone (for example, cancelling work in flight) until its change is\n * committed.\n */\n whenCommitted(work: () => void): void {\n this.settled.push(work);\n }\n\n /**\n * Records that an element at or below the depth of the running pass has been enrolled. The pass then stops and\n * restarts over the pending entries, so the new element is processed before the containers above it: an element\n * a handler writes is announced before the container whose composed value includes that write. The depth is\n * computed only while a pass runs; outside a pass it has no effect.\n */\n private noteDepth(element: FieldBase): void {\n if (this.passDepth < 0) return;\n if (depthOf(element) >= this.passDepth) this.restartPass = true;\n }\n\n /**\n * Restores every element the transaction modified to its state before the transaction. Nothing is announced, so\n * an observer sees no change. A rollback does not undo side effects, such as a server call a handler made during\n * the transaction.\n */\n rollback(): void {\n this.unwound = true;\n const entries = [...this.participants.values()].reverse();\n entries.forEach((entry) => {\n if (entry.snapshot) hooks(entry.element)[TxRestore](entry.snapshot);\n });\n this.participants.clear();\n // newest first, so an element written twice ends in the state before the earlier write\n for (let index = this.undo.length - 1; index >= 0; index--) this.undo[index]();\n this.undo.length = 0;\n // the change was not committed, so the work registered with whenCommitted does not run\n this.settled.length = 0;\n }\n\n /**\n * Announces the transaction's changes: access, enabled and visibility first, then values, then validity, because\n * a container's validators run with its value announcement and the validity pass reports their result. Every pass\n * runs deepest first (field, then row, then list), the order in which the change propagates.\n *\n * A handler may write while the commit runs; its writes join this transaction, so the passes repeat until nothing\n * is dirty.\n */\n commit(): void {\n for (;;) {\n if (this.announceFlags()) continue;\n if (this.announceValues()) continue;\n if (this.settleValidity()) continue;\n break;\n }\n // everything is announced and the change is committed, so the work registered with whenCommitted runs here\n for (let index = 0; index < this.settled.length; index++) this.settled[index]();\n this.settled.length = 0;\n committed();\n }\n\n /**\n * The dirty participants a pass visits, one bucket per nesting depth; within a depth they keep enrolment order.\n * A nesting depth is a small integer, so bucketing replaces a comparison sort: a whole-list assignment enrols one\n * participant per field, and a comparison sort of those would cost more than the announcement itself.\n */\n private buckets(pick: (entry: Participant) => boolean): (Participant[] | undefined)[] {\n const buckets: (Participant[] | undefined)[] = [];\n this.participants.forEach((entry) => {\n if (!pick(entry)) return;\n const depth = depthOf(entry.element);\n (buckets[depth] ??= []).push(entry);\n });\n return buckets;\n }\n\n /**\n * Runs one pass over the dirty participants, deepest bucket first; the caller repeats it until it returns false.\n * The buckets are built once, and the pass stops as soon as a handler enrols an element at or below the depth\n * being processed: that element is not in the current bucket, and continuing would process the containers above\n * it first. The caller's next pass builds new buckets that include it at its depth.\n */\n private pass(pick: (entry: Participant) => boolean, visit: (entry: Participant) => void): boolean {\n const buckets = this.buckets(pick);\n if (!buckets.length) return false;\n for (let depth = buckets.length - 1; depth >= 0; depth--) {\n const bucket = buckets[depth];\n if (!bucket) continue;\n this.passDepth = depth;\n this.restartPass = false;\n try {\n for (let index = 0; index < bucket.length; index++) {\n if (this.restartPass) return true;\n const entry = bucket[index];\n // a handler that ran earlier in this pass may have cleared the entry's pending flags\n if (pick(entry)) visit(entry);\n }\n } finally {\n this.passDepth = -1;\n }\n if (this.restartPass) return true;\n }\n return true;\n }\n\n private announceValues(): boolean {\n return this.pass(\n (entry) => entry.valueDirty || entry.structural !== undefined,\n (entry) => {\n const { structural } = entry;\n const dirty = entry.valueDirty;\n const force = entry.forceValue;\n entry.structural = undefined;\n entry.valueDirty = false;\n entry.forceValue = false;\n hooks(entry.element)[TxAnnounceValue](this, dirty, force, structural);\n },\n );\n }\n\n private announceFlags(): boolean {\n return this.pass(\n (entry) => entry.flagsDirty,\n (entry) => {\n entry.flagsDirty = false;\n hooks(entry.element)[TxAnnounceFlags]();\n },\n );\n }\n\n private settleValidity(): boolean {\n return this.pass(\n (entry) => entry.validityDirty,\n (entry) => {\n entry.validityDirty = false;\n hooks(entry.element)[TxSettleValidity](this);\n },\n );\n }\n}\n\n/** the transaction every mutating operation currently joins; undefined while none is open */\nlet current: Transaction | undefined;\n\n/** the handle of the open transaction, which a nested call that joins it also receives */\nlet currentHandle: TransactionHandle | undefined;\n\n/** The open transaction, for the bookkeeping an element does only while one is open. */\nexport function currentTransaction(): Transaction | undefined {\n return current;\n}\n\n/**\n * Thrown to unwind the transaction from the point of the call. It is a signal, not an error: transaction() catches\n * it, rolls back and returns undefined, and no failure is reported.\n */\nclass RollbackSignal {}\n\nexport interface TransactionControl {\n /**\n * Undoes everything the transaction has done and ends it, announcing nothing. It unwinds from the point of the\n * call, so no code after it runs. There are no savepoints: a nested call rolls back the whole transaction it\n * joined, not only its own part.\n *\n * @throws TypeError if the transaction the handle belongs to has already closed.\n */\n rollback(): never;\n}\n\n/**\n * The handle a transaction passes to the callbacks that take part in it. It becomes invalid when the transaction\n * closes: a handle kept after that refers to a transaction that no longer exists, and using it to roll back the\n * transaction open at that time would roll back an unrelated operation.\n */\nclass TransactionHandle implements TransactionControl {\n private open = true;\n\n /**\n * Set by `rollback()`. The signal it throws can be caught by a `try`/`catch` in the application's code; the\n * transaction reads this flag when the callback returns and rolls back all the same.\n */\n rollbackRequested = false;\n\n rollback(): never {\n if (!this.open) {\n throw new TypeError(\n 'this transaction handle is spent: the transaction that handed it out has closed. A handle is only ' +\n 'usable inside the call that received it.',\n );\n }\n this.rollbackRequested = true;\n throw new RollbackSignal();\n }\n\n close(): void {\n this.open = false;\n }\n}\n\nfunction rejectThenable(result: unknown): void {\n if (result != null && typeof (result as PromiseLike<unknown>).then === 'function') {\n throw new TypeError(\n 'a transaction may not be asynchronous: the callback returned a thenable. Do the awaiting outside and open ' +\n 'a transaction for each synchronous part.',\n );\n }\n}\n\n/**\n * Runs `fn` as one atomic change. Its writes are applied to the elements immediately, and the resulting events are\n * announced once, at the end, for the net result.\n *\n * A call made while a transaction is open joins it: nothing is committed until the outermost call returns. An\n * exception thrown from `fn` rolls back the whole transaction and is rethrown; `tx.rollback()` rolls it back\n * without an error, and the call returns undefined.\n *\n * The handle `fn` receives is usable only for the duration of that call; calling it afterwards throws a TypeError.\n *\n * @throws TypeError immediately if `fn` returns a thenable: a transaction cannot span an await.\n */\nexport function transaction<R>(fn: (tx: TransactionControl) => R): R | undefined {\n if (current) {\n const joined = fn(currentHandle!);\n rejectThenable(joined);\n return joined;\n }\n\n const tx = new Transaction();\n const handle = new TransactionHandle();\n current = tx;\n currentHandle = handle;\n try {\n const result = fn(handle);\n rejectThenable(result);\n if (handle.rollbackRequested) throw new RollbackSignal();\n tx.commit();\n return result;\n } catch (error) {\n // the commit may have announced part of the change before the throw; the state is restored regardless, and\n // what a handler did with the events it already received is a side effect no snapshot covers\n tx.rollback();\n if (error instanceof RollbackSignal) return undefined;\n throw error;\n } finally {\n current = undefined;\n currentHandle = undefined;\n handle.close();\n }\n}\n\n/**\n * Runs a mutating operation inside the open transaction, or opens one for the operation if none is open. Every\n * mutation in the library goes through this function.\n */\nexport function transactional<R>(fn: (tx: Transaction) => R): R {\n if (current) return fn(current);\n return transaction(() => fn(current!)) as R;\n}\n","import type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\nimport { currentTransaction } from '@/transaction';\n\n/**\n * Marks an action that runs outermost in its chain: `ActionsMap` keeps it above every action registered without\n * the mark, so a handler that does not call `supr` cannot keep it from running. The package does not export it.\n */\nexport const Outermost = Symbol('FieldActionBase.outermost');\n\ntype ActionExecutor = (field: FieldBase, supr: FieldActionExecute, ...params: any[]) => any;\n\nexport default abstract class FieldActionBase {\n public static get classIdentifier(): symbol {\n throw new Error('classIdentifier must be declared');\n }\n\n public get classIdentifier(): symbol {\n return (<any>this.constructor).classIdentifier;\n }\n\n private readonly executorFn: ActionExecutor;\n\n /**\n * The per-element state of this action. An action instance is shared (a `List` row has the same instances as\n * the item template), so state about the element it runs over is stored per element: a validation result, a\n * sequence number, a listener it installed. The keys are weak, so the state for a row is released with the row.\n */\n private readonly states = new WeakMap<object, any>();\n\n constructor(executorFn: ActionExecutor) {\n this.executorFn = executorFn;\n }\n\n /**\n * Returns this action's state for `key`, created by `init` on first access. The key is the element the action\n * runs over, or the record that element belongs to if the state concerns the whole record.\n */\n protected state<S>(key: object, init: () => S): S {\n if (!this.states.has(key)) this.states.set(key, init());\n return this.states.get(key) as S;\n }\n\n /**\n * Drops this action's state for `key`, so the next `state()` call creates it again. A rollback of the operation\n * that dropped it puts it back.\n */\n protected forgetState(key: object): void {\n if (!this.states.has(key)) return;\n const state = this.states.get(key);\n this.states.delete(key);\n currentTransaction()?.whenRolledBack(() => this.states.set(key, state));\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, ...params: any[]): any {\n return this.executorFn(field, supr, ...params);\n }\n\n get eager() {\n return false;\n }\n\n /**\n * Called when this action is bound to `binding`. It runs once per element the action is registered on, bindings\n * of that element included: a binding uses the action instances of its declaration, and each is called with the\n * binding.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n boundToBinding(binding: FieldBase) {}\n\n /**\n * Called when `binding` no longer has this action; an override removes what running the action left on it. It\n * receives one element because the same instance stays registered on other elements. It runs inside the\n * operation that removes the registration, so a rollback of that operation restores both the registration and\n * what this method removed.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n unregisterFrom(binding: FieldBase) {}\n\n /**\n * Called when `binding` is reset to a new binding of its declaration: a member of a bound group, or a `List` row\n * reused for another record. An override drops what it keeps about the element's state before the reset; the\n * element's eager actions other than the validators run again once the reset holds every new value, before the\n * baseline is recorded.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n resetBinding(binding: FieldBase) {}\n}\n","import type { Access } from './access';\nimport type FieldActionBase from './actions/field-action-base';\nimport type { FieldBase } from './field-base';\nimport { type ValidationError } from './validators/validation-error';\nimport type { Visibility } from './visibility';\n\nexport interface IFieldConstructorActionsList {\n actions?: FieldActionBase[];\n validators?: FieldActionBase[];\n}\n\n/**\n * Parameters accepted by field constructors and by bind overrides.\n *\n * Only writable members are listed. valid, validating, busy, pending, fullValue, isChanged, enabled and\n * effectiveEnabled are getter-only, so assigning them throws a TypeError. So are parent and fieldName: only a\n * container writes the slots behind them, when it takes an element, so the type rejects them.\n */\nexport type IFieldConstructorParams<T = any> = {\n value: T;\n originalValue: T;\n access: Access;\n visibility: Visibility;\n touched: boolean;\n errors: ValidationError[];\n} & IFieldConstructorActionsList;\n\n/**\n * The default type of an element's extended properties. It is declared empty, to be augmented: the rendering\n * layer declares the properties it renders elements with, and every element in the application then has those\n * properties without a type argument at any construction site.\n *\n * ```ts\n * declare module '@dynamicforms/vue-forms' {\n * interface Extras {\n * label?: string;\n * hint?: string;\n * cssClass?: string;\n * }\n * }\n * ```\n *\n * There is one interface per application, so two packages that declare a property of the same name must give it\n * the same type; declaration merging rejects a second declaration with a different type.\n *\n * An explicit X type argument replaces this interface, so an element with both is `Field<string, Extras & Local>`.\n */\nexport interface Extras {}\n\n/**\n * What an element's constructor accepts: the element's own parameters and the extended properties its X parameter\n * declares.\n *\n * X is excluded from inference, so an element has the properties X declares (`Extras` if no type argument is\n * given), and a parameter object with any other key is rejected as an excess property.\n *\n * The two parts are made partial separately. With `Partial<A & X>`, T would be inferred through a mapped type over\n * an intersection, which infers one member of a union instead of the union: `new Field({ value:\n * someStringOrNumber })` would be a Field<string>.\n */\nexport type IFieldParams<T = any, X extends object = Extras> = Partial<IFieldConstructorParams<T>> &\n Partial<NoInfer<X>>;\n\n/**\n * What bind() accepts in addition to the data: the three members a binding otherwise copies from the element it\n * is bound from, and the extended properties. `validators` and `actions` are omitted because a binding uses the\n * declaration's, and `touched` and `errors` because the binding sets them itself as it validates.\n */\nexport type IBindParams<T = any, X extends object = Extras> = Partial<\n Pick<IFieldConstructorParams<T>, 'originalValue' | 'access' | 'visibility'>\n> &\n Partial<NoInfer<X>>;\n\n/**\n * Thrown from a handler to end the current run. The trigger returns the exception itself, not `null`, so a caller\n * can distinguish a run a handler ended from one that reached no handler; a setter that triggers a `*Changing*`\n * handler cancels the write when it receives it. The trigger returns the exception directly if the chain ran\n * synchronously, and as the resolution of the returned promise if a handler in it was asynchronous.\n */\nexport class AbortEventHandlingException extends Error {}\n\nexport type FieldActionExecute<T = any> = (field: FieldBase<T>, ...params: any[]) => any;\n","import { type Access, defaultAccess } from './access';\nimport type { Container } from './container';\nimport type { FieldBase } from './field-base';\nimport type { Group } from './group';\nimport type { ListValue } from './list';\nimport { ValidationError } from './validators/validation-error';\nimport { defaultVisibility, type Visibility } from './visibility';\n\n/**\n * The mutable state of one element, held in a separate object, not in the element's own properties.\n *\n * An element accesses it through two views of that object, both in private class fields of `FieldBase`:\n * `this.state` is `reactive(slots)` and `this.raw` is the object itself. A slot read through `state` inside a\n * render effect or a computed subscribes that effect to the slot, and a write to the slot re-runs it. The element's\n * internal bookkeeping goes through `raw`, which neither tracks a read nor triggers on a write. This includes a\n * container's value cache: its getter writes the cache while it runs, and a tracked write there would cost the\n * reading effect one extra evaluation, and one extra render on mount, for a value already built.\n *\n * As private class fields, the two views are not accessible outside `FieldBase`: a private field is absent from\n * `Object.keys`, `JSON.stringify`, `Object.getOwnPropertySymbols` and lodash `getAllKeys` without any per-instance\n * property definition. `JSON.stringify` and lodash `isEqual` both walk a structure over own keys, enumerable\n * symbols included, and the `parent` slot is in the state: if reachable, it would lead either walk back into the\n * element's container.\n *\n * The own properties those walks do reach on an element are `_actions` once something is registered, `_fields` on\n * a `Group`, and `_itemTemplate` on a `List`. All of them lead downwards only.\n */\nexport interface ElementSlots<T = any> {\n /** the value the element was given at construction; isChanged compares against it */\n originalValue: T;\n /**\n * The value the last ValueChangedAction reported for the element (its value; a container's fullValue); the next\n * transaction compares its net change against it\n */\n announcedValue: T;\n /**\n * What the last ContributionChangedAction reported the element as sending to its container: its value, `null`,\n * or `undefined` for nothing\n */\n announcedContribution: unknown;\n /**\n * What a container's own validators last ran over (what it sends); the next transaction runs them again if that\n * changed. A leaf's validators run at the write and at an access change that changes what it sends, and do not\n * use this slot.\n */\n validatedValue: unknown;\n errors: ValidationError[];\n visibility: Visibility;\n access: Access;\n /** counts the writes that changed the value of the element or of any element below it */\n valueVersion: number;\n /** the number of asynchronous validation runs in flight on this element */\n validatingCount: number;\n /** the number of direct children whose `validating` is true; updated when a child starts or stops validating */\n validatingChildren: number;\n /** the container that holds this element, or undefined; takeChild writes it, releaseChild clears it */\n parent: Container | undefined;\n /** the name the containing Group holds this element under; undefined for a List row */\n fieldName: string | undefined;\n /** generation of the validators attached to the element; clearValidators() raises it */\n validationEpoch: number;\n /**\n * The element's extended properties, typed by the element's X parameter. A write replaces the object instead of\n * modifying it, so an effect that read the slot re-runs on the write, and a rollback restores the object the\n * transaction captured.\n */\n extra: object;\n /**\n * The declaration this element was bound from; undefined on an element that was not bound. An action shared by\n * every binding uses it to determine which binding of a second element applies: the slot holds the canonical\n * declaration, so a binding of a binding refers to the original declaration.\n */\n declaration: FieldBase | undefined;\n\n // the slots below are the element's internal bookkeeping: nothing reads them inside an effect, so they are\n // accessed through raw\n\n /**\n * The access and the visibility the last commit announced, recorded by the first write of either in a\n * transaction and cleared once the commit announced the net change; undefined while no change is pending.\n */\n announcedAccess: Access | undefined;\n announcedVisibility: Visibility | undefined;\n /** the validity the last commit announced; a change of validity is detected against it */\n valid: boolean;\n /** the number of direct children whose last announced validity was invalid */\n invalidChildren: number;\n /**\n * What the element held when its errors of an origin other than `'validator'` were written, which a `touched`\n * write compares against for the errors removed on `'edit'`. `NoErrorsBaseline` while there is none to compare\n * against, and `ChangedSinceErrors` where the value changed before one was recorded.\n */\n errorsBaseline: unknown;\n}\n\n/** `errorsBaseline` of an element with nothing recorded to compare against */\nexport const NoErrorsBaseline = Symbol('FieldBase.noErrorsBaseline');\n\n/** `errorsBaseline` of an element whose value changed after its errors were written, before a baseline was recorded */\nexport const ChangedSinceErrors = Symbol('FieldBase.changedSinceErrors');\n\n/** the initial extended properties: one frozen object shared by all elements, since a write replaces it */\nconst noExtra = Object.freeze({});\n\nexport function elementSlots<T = any>(): ElementSlots<T> {\n return {\n originalValue: undefined!,\n announcedValue: undefined!,\n announcedContribution: undefined,\n announcedAccess: undefined,\n announcedVisibility: undefined,\n validatedValue: undefined,\n errors: [],\n visibility: defaultVisibility,\n access: defaultAccess,\n valueVersion: 0,\n validatingCount: 0,\n validatingChildren: 0,\n parent: undefined,\n fieldName: undefined,\n validationEpoch: 0,\n declaration: undefined,\n extra: noExtra,\n valid: true,\n invalidChildren: 0,\n errorsBaseline: NoErrorsBaseline,\n };\n}\n\n/** what a Field holds beyond the common slots: the value itself, and whether it has been touched */\nexport interface FieldSlots<T = any> extends ElementSlots<T> {\n value: T;\n touched: boolean;\n}\n\nexport function fieldSlots<T = any>(): FieldSlots<T> {\n return { ...elementSlots<T>(), value: undefined!, touched: false };\n}\n\n/**\n * What a container holds beyond the common slots: the object the value getter last built, and the version of the\n * tree it was built from.\n */\nexport interface ContainerSlots<T = any> extends ElementSlots<T> {\n cachedValue: T;\n cachedValueVersion: number;\n}\n\nexport function containerSlots<T = any>(): ContainerSlots<T> {\n return {\n ...elementSlots<T>(),\n announcedValue: null,\n cachedValue: null,\n cachedValueVersion: -1,\n } as ContainerSlots<T>;\n}\n\n/** what a Group holds beyond the container slots: the names of its members, in the order they were added */\nexport interface GroupSlots<T = any> extends ContainerSlots<T> {\n /**\n * The names the group holds its members under. The member map is a plain object outside the reactive state, so\n * a reader inside an effect depends on this array: adding or removing a member re-runs the effect, and a rollback\n * restores the names with the other slots.\n */\n fieldNames: string[];\n}\n\nexport function groupSlots<T = any>(): GroupSlots<T> {\n return { ...containerSlots<T>(), fieldNames: [] } as GroupSlots<T>;\n}\n\n/** what a List holds beyond the container slots: the rows themselves */\nexport interface ListSlots<R extends FieldBase = Group> extends ContainerSlots<ListValue<R>> {\n rows: R[] | null;\n /**\n * Counts the changes to the set of rows. `items` rebuilds its frozen array only when this changes: a write\n * inside a row changes what the list sends without changing which rows it holds.\n */\n rowsVersion: number;\n /** the frozen array `items` last returned, and the rows version it was built from */\n cachedItems: readonly R[] | null;\n cachedItemsVersion: number;\n}\n\nexport function listSlots<R extends FieldBase = Group>(): ListSlots<R> {\n return { ...containerSlots<ListValue<R>>(), rows: null, rowsVersion: 0, cachedItems: null, cachedItemsVersion: -1 };\n}\n\n/** Key of the `Action` method that lists its `ExecuteAction` handlers; `Container` calls it, and the package does not\n * export it. */\nexport const ExecuteHandlers = Symbol('Action.executeHandlers');\n\n/** Key of the `List` method that reorders the rows in place; `view()` calls it, and the package does not export it. */\nexport const ReorderRows = Symbol('List.reorderRows');\n\n/**\n * Key of the `FieldBase` method that starts counting one asynchronous validation run and returns the function that\n * ends it. A validator calls it; the package does not export it.\n */\nexport const BeginValidating = Symbol('FieldBase.beginValidating');\n\n/** Key of the `FieldBase` getter for the generation counter of its validators; the package does not export it. */\nexport const ValidationEpoch = Symbol('FieldBase.validationEpoch');\n\n/**\n * Key of the `FieldBase` method that recomputes the validity of every element in its subtree that holds an error\n * of an origin other than `'validator'`, after the rules over those errors may have changed. `ErrorPolicy` calls\n * it; the package does not export it.\n */\nexport const ErrorPoliciesChanged = Symbol('FieldBase.errorPoliciesChanged');\n\n/**\n * Key of the `FieldBase` method that removes, in its subtree, the errors whose rule removes them on `'submit'`.\n * `SubmitAction` calls it; the package does not export it.\n */\nexport const RemoveErrorsOnSubmit = Symbol('FieldBase.removeErrorsOnSubmit');\n","import { shallowRef } from 'vue';\n\nimport FieldActionBase from '../actions/field-action-base';\nimport { ErrorPoliciesChanged } from '../element-state';\nimport type { FieldBase } from '../field-base';\nimport { transactional } from '../transaction';\n\nimport type { ErrorOrigin } from './validation-error';\n\n/**\n * When an element removes an error by itself:\n *\n * - `'change'`: when the element's value changes. A container's value changes with any member or row below it, and\n * when a member or a row is added, removed or written a different `access`.\n * - `'edit'`: when `touched = true` is written on the element or on an element below it, and the element's value\n * differs from the value it held when the error was written.\n * - `'submit'`: when a `SubmitAction` whose target is the element or a container above it sends the target's value.\n * - `'never'`: only the code that wrote the error removes it.\n */\nexport type ErrorRemoval = 'change' | 'edit' | 'submit' | 'never';\n\n/** The values of `ErrorRemoval`. */\nexport const errorRemovals: readonly ErrorRemoval[] = Object.freeze(['change', 'edit', 'submit', 'never']);\n\n/** How the errors of one origin are treated. */\nexport interface ErrorPolicyRule {\n /** Whether an error of the origin makes its element, and every container above it, invalid. */\n readonly validEffect: boolean;\n /** When an element removes an error of the origin by itself. */\n readonly removeOn: ErrorRemoval;\n}\n\n/** A rule per origin. `'validator'` has no rule: a validator replaces its own errors and they always count. */\nexport type ErrorPolicies = Readonly<Partial<Record<Exclude<ErrorOrigin, 'validator'>, ErrorPolicyRule>>>;\n\nconst ErrorPolicyClassIdentifier = Symbol('ErrorPolicy');\n\n/** The rule of an origin no `ErrorPolicy` and no default names. */\nconst fallbackRule: ErrorPolicyRule = Object.freeze({ validEffect: true, removeOn: 'never' });\n\nconst builtInDefaults: ErrorPolicies = Object.freeze({\n server: Object.freeze({ validEffect: true, removeOn: 'edit' }),\n});\n\nlet defaults: ErrorPolicies = builtInDefaults;\n\n/**\n * Raised whenever a rule may have changed for some element: an `ErrorPolicy` registered or unregistered, the\n * defaults set. A validity that reads a rule reads this too, so it is recomputed after such a change.\n */\nconst rulesVersion = shallowRef(0);\n\n/**\n * The number of elements an `ErrorPolicy` was bound to and not unregistered from. A binding that is released without\n * an unregistration stays counted, so the count is an upper bound; only zero is read. While it is zero, the rule of\n * an error does not depend on the element's position, so a container that takes or releases an element does not\n * recompute the validity below it.\n */\nlet positionalRules = 0;\n\n/** Whether some element has an `ErrorPolicy`, so that moving an element can change the rules over its errors. */\nexport function rulesArePositional(): boolean {\n return positionalRules > 0;\n}\n\n/** Records that a rule may have changed; read by every validity that reads a rule. */\nexport function readRulesVersion(): void {\n void rulesVersion.value;\n}\n\nconst describe = (value: unknown) => (typeof value === 'string' ? `'${value}'` : String(value));\n\n/** Throws a TypeError for a rule or an origin an `ErrorPolicy` or the defaults cannot take. */\nfunction checkPolicies(policies: ErrorPolicies): void {\n if (policies === null || typeof policies !== 'object') {\n throw new TypeError(`${describe(policies)} is not an object of rules keyed by origin`);\n }\n Object.entries(policies).forEach(([origin, rule]) => {\n if (origin === 'validator') {\n throw new TypeError(\"'validator' has no rule: a validator replaces its own errors and they always count\");\n }\n if (rule === null || typeof rule !== 'object') {\n throw new TypeError(`The rule for ${describe(origin)} is not an object of validEffect and removeOn`);\n }\n if (typeof rule.validEffect !== 'boolean') {\n throw new TypeError(`validEffect for ${describe(origin)} is ${describe(rule.validEffect)}, not a boolean`);\n }\n if (!errorRemovals.includes(rule.removeOn)) {\n throw new TypeError(\n `removeOn for ${describe(origin)} is ${describe(rule.removeOn)}, not one of ` +\n errorRemovals.map(describe).join(', '),\n );\n }\n if (rule.validEffect && rule.removeOn === 'submit') {\n throw new TypeError(\n `The rule for ${describe(origin)} combines validEffect: true with removeOn: 'submit': an error that makes ` +\n 'the target invalid refuses the submit that would remove it',\n );\n }\n });\n}\n\n/** A frozen copy of `policies`, each rule frozen. */\nfunction frozen(policies: ErrorPolicies): ErrorPolicies {\n const copy: Record<string, ErrorPolicyRule> = Object.create(null);\n Object.entries(policies).forEach(([origin, rule]) => {\n copy[origin] = Object.freeze({ validEffect: rule!.validEffect, removeOn: rule!.removeOn });\n });\n return Object.freeze(copy);\n}\n\n/**\n * Sets the rules of the origins in `policies` for every element without an `ErrorPolicy` that names them. An origin\n * not in `policies` keeps its rule. The built-in rules are `{ validEffect: true, removeOn: 'edit' }` for `'server'`\n * and `{ validEffect: true, removeOn: 'never' }` for every other origin.\n *\n * Returns a function that restores the rules in force before the call. `valid` reflects a change at once; the\n * validity an element announces through `ValidChangedAction` is recomputed at its next validity change, so the\n * defaults are set before forms are built. Throws a TypeError for a rule `ErrorPolicy` refuses.\n */\nexport function setDefaultErrorPolicies(policies: ErrorPolicies): () => void {\n checkPolicies(policies);\n const previous = defaults;\n defaults = Object.freeze({ ...defaults, ...frozen(policies) });\n rulesVersion.value++;\n return () => {\n defaults = previous;\n rulesVersion.value++;\n };\n}\n\n/** The rule of `origin` where no `ErrorPolicy` names it. */\nexport function defaultRule(origin: ErrorOrigin): ErrorPolicyRule {\n return (defaults as Record<string, ErrorPolicyRule>)[origin] ?? fallbackRule;\n}\n\n/**\n * The rules of the error origins for the element it is registered on and every element below it. An element takes\n * the rule of an origin from the nearest `ErrorPolicy` that names it, on itself or on a container above it; an\n * origin no such policy names takes the rule `setDefaultErrorPolicies` set.\n *\n * ```typescript\n * login.registerAction(new ErrorPolicy({ server: { validEffect: false, removeOn: 'submit' } }));\n * ```\n *\n * Its registration is shared by the element's bindings, as every action's is. Registering or unregistering it\n * recomputes the validity of the elements below it; an error it now removes stays until the event that removes\n * it. The constructor throws a TypeError for a rule of `'validator'`, a `validEffect` that is not a boolean, a\n * `removeOn` that is not an `ErrorRemoval`, and `validEffect: true` with `removeOn: 'submit'`, since such an error\n * refuses the submit that would remove it. Registering it beside another `ErrorPolicy` that names one of its\n * origins throws a TypeError.\n */\nexport class ErrorPolicy extends FieldActionBase {\n readonly policies: ErrorPolicies;\n\n constructor(policies: ErrorPolicies) {\n checkPolicies(policies);\n // no event triggers it; the chain argument is never called\n super((field, supr, ...params) => supr(field, ...params));\n this.policies = frozen(policies);\n }\n\n static get classIdentifier() {\n return ErrorPolicyClassIdentifier;\n }\n\n boundToBinding(binding: FieldBase) {\n positionalRules++;\n this.rulesChanged(binding);\n }\n\n unregisterFrom(binding: FieldBase) {\n positionalRules--;\n this.rulesChanged(binding);\n }\n\n private rulesChanged(binding: FieldBase) {\n rulesVersion.value++;\n transactional(() => binding[ErrorPoliciesChanged]());\n }\n}\n\n/** The rule `policy` states for `origin`, or undefined. */\nexport function ruleIn(policy: ErrorPolicy, origin: ErrorOrigin): ErrorPolicyRule | undefined {\n return (policy.policies as Record<string, ErrorPolicyRule>)[origin];\n}\n\n/**\n * Throws a TypeError where `action` is an `ErrorPolicy` and `registered`, the actions of the element it is being\n * registered on, holds another policy naming one of its origins. `ActionsMap` calls it before it registers anything.\n */\nexport function checkRegistration(action: FieldActionBase, registered: readonly FieldActionBase[]): void {\n if (!(action instanceof ErrorPolicy)) return;\n const origins = Object.keys(action.policies);\n registered.forEach((other) => {\n if (other === action || !(other instanceof ErrorPolicy)) return;\n const shared = origins.find((origin) => ruleIn(other, origin) !== undefined);\n if (shared !== undefined) {\n throw new TypeError(`An ErrorPolicy for ${describe(shared)} is already registered on this element`);\n }\n });\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nexport const ValueChangedActionClassIdentifier = Symbol('ValueChangedAction');\n\nexport class ValueChangedAction<T = any> extends FieldActionBase {\n constructor(executorFn: (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ValueChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import { isEqual } from 'lodash-es';\n\n/**\n * The source of an error. `'validator'` is an error a validator produced, `'server'` one the server returned and\n * `'application'` one the application's code computed and wrote into `errors`. Any other string is an\n * application-defined origin.\n *\n * Every origin but `'validator'` has a rule stating whether its errors count toward validity and when an element\n * removes them; see `ErrorPolicy`.\n */\nexport type ErrorOrigin = 'validator' | 'server' | 'application' | (string & {});\n\n/**\n * The content of an error: what failed, the values it failed with, an English sentence describing it, and its\n * origin. An error the application builds from a server's response has the same content, so a renderer converts\n * validator and server errors to text with one function.\n */\nexport interface ErrorDescription {\n /** Machine-readable identifier of what failed, in snake_case. */\n readonly code: string;\n /** The values of the failure, such as `minValue` for `min_value`. */\n readonly params: Readonly<Record<string, unknown>>;\n /** The failure in English, plain text, with `params` substituted. */\n readonly detail: string;\n /** The origin of the error; see `ValidationError.origin`. */\n readonly origin: ErrorOrigin;\n}\n\n/**\n * An error on an element. It is data: the library does not render it. A renderer chooses the text for `code` and\n * `params` and falls back to `detail`.\n */\nexport class ValidationError implements ErrorDescription {\n /**\n * @param code Machine-readable identifier of what failed, in snake_case.\n * @param params The values of the failure, such as `minValue` for `min_value`.\n * @param detail The failure in English, plain text. Stored as given.\n * @param statedOrigin The origin of the error, if its author sets it; see `origin`.\n */\n constructor(\n public readonly code: string,\n public readonly params: Readonly<Record<string, unknown>>,\n public readonly detail: string,\n private readonly statedOrigin?: ErrorOrigin,\n ) {}\n\n /**\n * The origin its author set. Otherwise `'validator'` for an error a validator produced (a validator stamps every\n * error it puts on a field) and `'application'` for one written into `errors` by any other code.\n */\n get origin(): ErrorOrigin {\n if (this.statedOrigin !== undefined) return this.statedOrigin;\n return typeof (this as { source?: unknown }).source === 'symbol' ? 'validator' : 'application';\n }\n\n /**\n * True if `other` has the same class, code, params, detail and stated origin. If a new run produces an error for\n * which this is true, the validator keeps the instance the field already holds, so an unchanged error is not\n * replaced in `field.errors`.\n */\n sameAs(other: ValidationError): boolean {\n return (\n Object.getPrototypeOf(this) === Object.getPrototypeOf(other) &&\n this.code === other.code &&\n this.detail === other.detail &&\n this.statedOrigin === other.statedOrigin &&\n isEqual(this.params, other.params)\n );\n }\n}\n","import { ValueChangedAction } from '../actions/value-changed-action';\nimport { BeginValidating, ValidationEpoch } from '../element-state';\nimport { type FieldBase } from '../field-base';\nimport { FieldActionExecute } from '../field.interface';\nimport { currentTransaction, SentNowhere, transaction, transactional } from '../transaction';\n\nimport { ValidationError } from './validation-error';\n\nexport type ValidationFunctionResult = ValidationError[] | null;\n/**\n * The validation of a value. `signal` aborts when the result of this call will no longer be applied: a newer run\n * over the same field, the validator's removal from the field once that removal is committed, a rolled-back\n * transaction. An asynchronous check passes it to the work it starts, so that work is cancelled. A function with\n * nothing to cancel ignores it.\n */\nexport type ValidationFunction<T = any> = (\n newValue: T,\n oldValue: T,\n field: FieldBase<T>,\n signal: AbortSignal,\n) => ValidationFunctionResult | Promise<ValidationFunctionResult>;\n\ninterface SourceProp {\n source: symbol;\n}\n\n/** The validator's state for one field it is registered on; a subclass extends it. */\nexport interface ValidatorBindingState {\n run: number;\n /** cancels the asynchronous run in flight over the field; undefined while no run is pending */\n abandon?: () => void;\n}\n\n/**\n * The `code` and `detail` a built-in validator uses on its error in place of its own. A `detail` requires a `code`:\n * a renderer chooses the text by the code, so a detail under the validator's own code is not shown where the\n * renderer has a text for that code.\n */\nexport type ValidationErrorOptions =\n | {\n /** The error's `code`. Defaults to the validator's own, such as `required`. */\n code?: string;\n detail?: never;\n }\n | {\n /** The error's `code`. */\n code: string;\n /** The error's English `detail`, plain text. `{name}` placeholders are replaced with the error's `params`. */\n detail?: string;\n };\n\nconst ValidatorClassIdentifier = Symbol('Validator');\n\n/** Replaces each `{name}` placeholder in `template` with `params[name]`; one without a matching param stays. */\nfunction interpolate(template: string, params: Record<string, unknown>): string {\n // one pass over the template, so a substituted value that contains a placeholder is not substituted again\n return template.replace(/\\{(\\w+)\\}/g, (placeholder, name: string) =>\n Object.hasOwn(params, name) ? String(params[name]) : placeholder,\n );\n}\n\n/**\n * Validator is a specialized action that performs validation when a field's value changes.\n * It automatically adds/removes validation errors from the field's errors array.\n */\nexport class Validator<T = any> extends ValueChangedAction {\n private readonly source: symbol;\n\n /**\n * Creates a new validator\n * @param validationFn Function that validates the field value and returns errors or null\n */\n constructor(validationFn: ValidationFunction<T>) {\n const executor = (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: T, oldValue: T) => {\n const runs = this.bindingState(field);\n // the pending run over this field, which this run replaces\n const superseded = runs.abandon;\n const run = ++runs.run;\n const epoch = field[ValidationEpoch];\n // the transaction this run started in: if it is rolled back, the run's result is not applied, because the\n // value it examined was rolled back\n const startedIn = currentTransaction();\n // a result is applied only if no newer run has started for this field, the field still has the validators it\n // had when the run started, the change that started it was not rolled back, and the run was not cancelled.\n // Cancellation is the only condition that does not read the field: the run's work has been aborted, so its\n // result is discarded\n let abandoned = false;\n const isCurrent = () =>\n !abandoned && runs.run === run && field[ValidationEpoch] === epoch && !startedIn?.rolledBack;\n\n // the work a validation function starts is cancelled when isCurrent becomes false; a run for which isCurrent\n // is still true is not cancelled\n const controller = new AbortController();\n const abandon = () => {\n if (isCurrent()) return;\n abandoned = true;\n if (runs.abandon === abandon) runs.abandon = undefined;\n controller.abort();\n };\n // this run now has the newest number, so the run it replaces is no longer current and its signal aborts\n superseded?.();\n\n // an element that is not sent is not validated: the run produces no errors and removes this validator's\n // errors\n const errors = field[SentNowhere]() ? [] : validationFn(newValue, oldValue, field, controller.signal) || [];\n\n // replacing this validator's errors and recomputing validity are one change: a run that settles after the\n // operation that started it opens its own transaction here, and one that settles during it joins the open\n // transaction\n const processErrors = (err: ValidationFunctionResult) =>\n transaction(() => {\n const mine = err?.map((e) => this.claim(e)) ?? [];\n for (let i = field.errors.length - 1; i >= 0; i--) {\n const error = field.errors[i] as ValidationError & SourceProp;\n if (error.source === this.source) {\n const idx = mine.findIndex((e) => e.sameAs(error));\n if (idx >= 0) mine.splice(idx, 1);\n else field.errors.splice(i, 1);\n }\n }\n\n if (mine.length > 0) field.errors.push(...mine);\n field.validate(); // recompute the field's validity\n });\n\n if (errors instanceof Promise) {\n // only a pending run can be cancelled; a rollback of the transaction reverts the change this run examines,\n // so it cancels the run\n runs.abandon = abandon;\n startedIn?.whenRolledBack(abandon);\n const endValidating = field[BeginValidating]();\n errors\n .then(\n (err) => {\n if (isCurrent()) processErrors(err);\n },\n (reason) => {\n // a rejection replaces this validator's errors with one `validation_failed` error, so the field is\n // invalid and the form cannot be submitted until a later run of the validator succeeds. The error has\n // this validator's source stamp, so the next successful run removes it like any other error of its\n // own. The error message says only that the check did not complete, so the reason is logged.\n if (isCurrent()) {\n processErrors([new ValidationError('validation_failed', {}, 'Validation could not be completed')]);\n console.error('Validation failed', reason);\n }\n },\n )\n .finally(() => {\n if (runs.abandon === abandon) runs.abandon = undefined;\n endValidating();\n })\n // applying a result fires ValidChangedAction; this catch logs an exception thrown by a handler, which\n // would otherwise be an unhandled rejection\n .catch((error) => console.error('Validation failed', error));\n } else processErrors(errors);\n return supr(field, newValue, oldValue); // Continue the action chain\n };\n\n super(executor);\n\n // a unique symbol for this validator instance\n this.source = Symbol(this.constructor.name);\n }\n\n /**\n * Returns the error instance this validator owns and may later remove: the argument itself if it has no\n * ownership stamp or already has this validator's, and a copy if it belongs to another validator. The stamp is\n * not configurable, so an instance owned by one validator cannot be reassigned to another; the copy allows one\n * error instance to be shared between validators, and keeps the prototype and every own property, including the\n * non-enumerable ones, so it renders like the original.\n */\n private claim(error: ValidationError): ValidationError {\n const owner = (error as ValidationError & Partial<SourceProp>).source;\n if (owner === this.source) return error;\n\n const stamp: PropertyDescriptor = { value: this.source, enumerable: false, configurable: false };\n if (owner === undefined) {\n Object.defineProperty(error, 'source', stamp);\n return error;\n }\n const descriptors = Object.getOwnPropertyDescriptors(error) as Record<string, PropertyDescriptor>;\n return Object.create(Object.getPrototypeOf(error), { ...descriptors, source: stamp });\n }\n\n static get classIdentifier() {\n return ValidatorClassIdentifier;\n }\n\n get eager() {\n return true;\n }\n\n /**\n * Removes this validator from `field`: the errors it put there are removed and validity is recomputed over the\n * remaining validators. Otherwise the field would stay invalid on an error no validator removes.\n *\n * A run in flight over the field is cancelled when the removal is committed, not earlier: a rollback restores the\n * validator and its epoch, and the run, still active, then applies its result. Cancelling at the removal would\n * leave the field valid over an unchecked value after a rollback.\n */\n unregisterFrom(field: FieldBase) {\n transactional((tx) => {\n tx.whenCommitted(() => this.abandonRun(field));\n for (let i = field.errors.length - 1; i >= 0; i--) {\n if ((field.errors[i] as ValidationError & SourceProp).source === this.source) field.errors.splice(i, 1);\n }\n field.validate();\n });\n }\n\n /**\n * Cancels the asynchronous run in flight over `field`, if any. It is called after the validator is removed from\n * the field: the field's validation epoch has changed, so the run's result is discarded and its signal aborts.\n */\n protected abandonRun(field: FieldBase): void {\n this.bindingState(field).abandon?.();\n }\n\n /**\n * The validator's state for one of the fields it validates. One instance may be registered on several fields\n * (every row of a list has the same instances as the item template), so each field has its own state. A subclass\n * extends it by overriding `newBindingState`.\n */\n protected bindingState(field: FieldBase<any>): ValidatorBindingState {\n return this.state(field, () => this.newBindingState());\n }\n\n /**\n * The initial state for a field. `run` is the sequence number of the newest run over that field: every execution\n * takes the next number and a result is applied only while its number is the newest, so a slow run cannot\n * overwrite the result of a faster one that started after it.\n */\n protected newBindingState(): ValidatorBindingState {\n return { run: 0 };\n }\n\n /**\n * Returns the error a built-in validator reports: `code` and `detail` from `options` if set, the validator's own\n * otherwise, with `params` substituted into the detail.\n */\n protected errorFor(\n options: ValidationErrorOptions | undefined,\n code: string,\n detail: string,\n params: Record<string, unknown>,\n ): ValidationError {\n return new ValidationError(options?.code ?? code, params, interpolate(options?.detail ?? detail, params));\n }\n}\n","import { type FieldBase } from '../field-base';\nimport { AbortEventHandlingException } from '../field.interface';\nimport { checkRegistration } from '../validators/error-policy';\nimport { Validator } from '../validators/validator';\n\nimport FieldActionBase, { Outermost } from './field-action-base';\n\n/**\n * The actions one declaration has registered, in registration order. A trigger walks them from the end backwards\n * and skips the ones registered under another identifier, so the newest registration of an identifier is its\n * outermost handler and calls the earlier ones through its `supr` argument. A handler that does not call `supr`\n * ends the run, and one that calls it may transform the result.\n *\n * The array is the only index. An element has few actions, and a linear walk over a few entries is faster and\n * smaller than a keyed lookup.\n */\nexport default class ActionsMap {\n /**\n * Every action registered here, in registration order. Unregistering replaces the array instead of modifying it,\n * so a run in progress finishes on the array it started with and the removal takes effect from the next trigger.\n */\n private actions: FieldActionBase[] = [];\n\n /**\n * Registers `action`. It becomes the outermost handler of its identifier, or, if `before` is given, is inserted\n * at the position of `before`, so `before` wraps it and calls it through `supr`. This adds an action to an\n * existing chain inside a handler that is already registered. Throws if `before` is not registered here under the\n * same identifier, and a TypeError for an `ErrorPolicy` naming an origin another one registered here names.\n */\n register(action: FieldActionBase, before?: FieldActionBase): void {\n if (!(action instanceof FieldActionBase)) throw new Error('Invalid action type');\n // read here, so a class without a classIdentifier is refused at registration, before it is in the chain\n void action.classIdentifier;\n checkRegistration(action, this.actions);\n const at = before ? this.actions.indexOf(before) : -1;\n if (before && (before.classIdentifier !== action.classIdentifier || at < 0)) {\n throw new Error('Action to register before is not registered under the same identifier');\n }\n if (at >= 0) {\n this.actions.splice(at, 0, action);\n return;\n }\n // an action marked Outermost goes on top of the chain; any other goes directly below the outermost ones of its\n // identifier, so it is the newest of the rest and cannot keep them from running\n const pinned = (action as any)[Outermost]\n ? -1\n : this.actions.findIndex(\n (registered) => (registered as any)[Outermost] && registered.classIdentifier === action.classIdentifier,\n );\n if (pinned < 0) this.actions.push(action);\n else this.actions.splice(pinned, 0, action);\n }\n\n /** Unregisters `action` and returns whether it was registered here. */\n unregister(action: FieldActionBase): boolean {\n if (!this.actions.includes(action)) return false;\n this.actions = this.actions.filter((registered) => registered !== action);\n return true;\n }\n\n /** True if any action is registered under `identifier`. */\n willTrigger(identifier: symbol): boolean {\n return this.actions.some((action) => action.classIdentifier === identifier);\n }\n\n /** True if any eager action is registered, under any identifier. */\n get hasEager(): boolean {\n return this.actions.some((action) => action.eager);\n }\n\n /** Runs the actions registered under `ActionClass` and returns the result of the outermost one. */\n trigger<T extends FieldActionBase>(\n ActionClass: (abstract new (...args: any[]) => T) & { classIdentifier: symbol },\n field: FieldBase,\n ...params: any[]\n ): any {\n return this.run(ActionClass.classIdentifier, false, field, params);\n }\n\n /**\n * Runs the eager actions of every identifier, each identifier's group separately. A group starts at its outermost\n * eager action, the last one registered under that identifier. The rules run before the validators: a rule can\n * change the element's access or value, so after one ran the validators receive what the element sends then, in\n * place of the first parameter.\n */\n triggerEager(field: FieldBase, ...params: any[]): void {\n const ruled = this.runEager((action) => !(action instanceof Validator), field, params);\n const validatorParams = ruled ? [field.contribution, ...params.slice(1)] : params;\n this.runEager((action) => action instanceof Validator, field, validatorParams);\n }\n\n /**\n * Runs the eager actions other than the validators, as `triggerEager` does: the rules that set an element's flags\n * or values from its record.\n */\n triggerEagerRules(field: FieldBase, ...params: any[]): void {\n this.runEager((action) => !(action instanceof Validator), field, params);\n }\n\n /** Runs the eager groups whose actions `include` accepts; returns whether any ran. */\n private runEager(include: (action: FieldActionBase) => boolean, field: FieldBase, params: any[]): boolean {\n let ran = false;\n const actions = this.actions;\n for (let index = actions.length - 1; index >= 0; index--) {\n const action = actions[index];\n if (!action.eager || !include(action)) continue;\n // the group runs once, from its outermost eager action; the earlier ones are called through supr\n if (ActionsMap.outermostEager(actions, index)) {\n ran = true;\n try {\n const result = this.walk(actions, index, action.classIdentifier, true, field, params);\n // an abort from an asynchronous handler arrives as a rejection, which the catch below does not receive; it\n // is handled here so it is not reported as unhandled. Any other rejection is rethrown.\n if (ActionsMap.isPromise(result)) {\n result.then(undefined, (error: unknown) => {\n if (!(error instanceof AbortEventHandlingException)) throw error;\n });\n }\n } catch (error) {\n // an abort ends only its own group; the other groups are separate rules and still run\n if (!(error instanceof AbortEventHandlingException)) throw error;\n }\n }\n }\n return ran;\n }\n\n /** Runs only the eager actions registered under `identifier`. */\n triggerEagerFor(identifier: symbol, field: FieldBase, ...params: any[]): any {\n return this.run(identifier, true, field, params);\n }\n\n /** The registered actions with `identifier`, in registration order. */\n ofClass(identifier: symbol): FieldActionBase[] {\n return this.actions.filter((action) => action.classIdentifier === identifier);\n }\n\n /** The validators registered here, in registration order. */\n get validators(): Validator[] {\n return this.actions.filter((action): action is Validator => action instanceof Validator);\n }\n\n /**\n * Binds every action in this map to `owner`. A binding uses its declaration's map, so this notifies the actions\n * already in it of the new element, as registering an action binds it to the existing elements.\n */\n bindTo(owner: FieldBase): void {\n this.actions.forEach((action) => action.boundToBinding(owner));\n }\n\n /** Tells every action in this map that `owner` is reset to a new binding of its declaration. */\n resetBinding(owner: FieldBase): void {\n this.actions.forEach((action) => action.resetBinding(owner));\n }\n\n /** True if no eager action of the same identifier follows `index`, so `index` is the group's entry point. */\n private static outermostEager(actions: FieldActionBase[], index: number): boolean {\n const identifier = actions[index].classIdentifier;\n for (let above = actions.length - 1; above > index; above--) {\n if (actions[above].eager && actions[above].classIdentifier === identifier) return false;\n }\n return true;\n }\n\n /**\n * True if `value` is a promise, which a walk through an asynchronous handler returns. The test checks the type,\n * not a `then` member: a handler may return a value object with a `then` member, and calling it would replace the\n * result with that call's return value.\n */\n private static isPromise(value: any): value is Promise<any> {\n return value instanceof Promise;\n }\n\n /**\n * Returns an abort as a value on the asynchronous path as well. If a handler in the chain is asynchronous, the\n * walk returns a promise and an abort arrives as its rejection; this converts it to a resolution, so the promise\n * the trigger returns resolves to the exception. Any other rejection is passed on.\n */\n private static answerAbort(value: any): any {\n if (!ActionsMap.isPromise(value)) return value;\n return value.then(undefined, (error: unknown) => {\n if (error instanceof AbortEventHandlingException) return error;\n throw error;\n });\n }\n\n /**\n * Runs a group from its outermost action. An abort ends the run and is returned, not thrown: the caller receives\n * the exception directly if the chain ran synchronously, and as the resolution of the returned promise otherwise.\n * This distinguishes an aborted run from one that reached no handler and from one whose handler returned null.\n */\n private run(identifier: symbol, eagerOnly: boolean, field: FieldBase, params: any[]): any {\n const actions = this.actions;\n try {\n return ActionsMap.answerAbort(this.walk(actions, actions.length - 1, identifier, eagerOnly, field, params));\n } catch (error) {\n if (error instanceof AbortEventHandlingException) return error;\n throw error;\n }\n }\n\n /**\n * Walks from `index` backwards to the first action of `identifier` and calls it with a `supr` that continues at\n * the action before it. Actions registered under other identifiers are skipped, so the array needs no grouping;\n * a closure is created only for each level the run reaches and lives only for the run.\n */\n private walk(\n actions: FieldActionBase[],\n index: number,\n identifier: symbol,\n eagerOnly: boolean,\n field: FieldBase,\n params: any[],\n ): any {\n let at = index;\n while (at >= 0 && (actions[at].classIdentifier !== identifier || (eagerOnly && !actions[at].eager))) at--;\n if (at < 0) return null;\n const supr = (next: FieldBase, ...rest: any[]) => this.walk(actions, at - 1, identifier, eagerOnly, next, rest);\n return actions[at].execute(field, supr, ...params);\n }\n}\n","import type { FieldBase } from './field-base';\nimport type { Group } from './group';\n\n/**\n * Resolution of one element against another element's record.\n *\n * An action instance is shared: every row a `List` builds from an item template has the same action instances as\n * the item template, and only the data differs per row. An action that reads a second element (a statement\n * comparing two fields, a validator comparing a password with its confirmation) must find the second element that\n * belongs to the row it runs over. The structure determines it: the element the action was declared against and the\n * record it runs in identify the second element together.\n */\n\n/**\n * Returns the record an element belongs to: the `List` row that holds it, or the top of its container chain if no\n * row does. A List holds a row without a name and a `Group` names every member, so a record begins at the first\n * element without a `fieldName`.\n */\nexport function scopeOf(element: FieldBase): FieldBase {\n let current = element;\n while (current.fieldName !== undefined && current.parent) current = current.parent;\n return current;\n}\n\n/**\n * Returns the member of `record` whose declaration is `declaration`, or `undefined` if the record holds none. It is\n * located by path: the record is walked down the names that lead from the declaration's own record to the\n * declaration.\n */\nfunction memberOf(record: FieldBase, declaration: FieldBase): FieldBase | undefined {\n let resolved: FieldBase | undefined = record;\n for (const name of pathOf(declaration)) {\n resolved = (resolved as Group).field?.(name) ?? undefined;\n if (!resolved) return undefined;\n }\n return resolved?.declaration === declaration ? resolved : undefined;\n}\n\n/** The names leading from an element's record down to the element. */\nfunction pathOf(element: FieldBase): string[] {\n const path: string[] = [];\n let current = element;\n while (current.fieldName !== undefined && current.parent) {\n path.unshift(current.fieldName);\n current = current.parent;\n }\n return path;\n}\n\n/**\n * Returns the element that corresponds to `declaration` within `scope`:\n * - the member `scope` holds at the same position, if that member's declaration is `declaration`;\n * - `declaration` itself, if it belongs to a record other than `scope`'s and is therefore the one element every\n * record reads (a form field above a list, or a field of another row referenced explicitly);\n * - `undefined`, if `scope` is a record of the same kind that is not built yet; the caller resolves again once it\n * is.\n */\nexport function resolveInScope(declaration: FieldBase, scope: FieldBase): FieldBase | undefined {\n const withinRecord = memberOf(scope, declaration);\n if (withinRecord) return withinRecord;\n\n // the record holds no member with this declaration, so it belongs to an enclosing record. A list nested in a row\n // makes that record one per row (an order's total, read by the lines of that order), so each enclosing container\n // is searched before the element is treated as one that every record reads\n let enclosing = scope.parent;\n while (enclosing) {\n const bound = memberOf(scopeOf(enclosing), declaration);\n if (bound) return bound;\n enclosing = enclosing.parent;\n }\n\n // no enclosing container holds a binding of it either. Either it is the one element every record reads (a form\n // field above a list), or the record has the same declaration and is still being assembled\n return scopeOf(declaration) === scopeOf(scope.declaration) ? undefined : declaration;\n}\n\n/**\n * Returns every element that corresponds to `declaration` when something changes in `scope`:\n * - the one member of that record, if the record holds one;\n * - if the element belongs to a record above (a form field the rows of a list read), each of its bindings inside\n * `scope`, because a change there applies to all of them;\n * - if `scope` contains no binding, the element itself, which is the case for a form without records below it.\n * For a record still being assembled it returns an empty array, and the assignment that completes the record\n * resolves again.\n */\nexport function bindingsIn(declaration: FieldBase, scope: FieldBase): FieldBase[] {\n const resolved = resolveInScope(declaration, scope);\n if (!resolved) return [];\n if (resolved !== declaration) return [resolved];\n const found = scope.bindingsOf(declaration);\n return found.length > 0 ? found : [declaration];\n}\n\n/**\n * Returns the element named `name` in the nearest container above `element` that holds one, or `undefined` if no\n * container does. A row is searched before the form containing the list, so a rule that refers to a name reads\n * the row it runs over.\n */\nexport function resolveByName(name: string, element: FieldBase): FieldBase | undefined {\n let container = element.parent;\n while (container) {\n const member = (container as Group).field?.(name);\n if (member) return member;\n container = container.parent;\n }\n return undefined;\n}\n","import type { Access } from '../../access';\nimport { type FieldBase } from '../../field-base';\nimport { FieldActionExecute } from '../../field.interface';\nimport { bindingsIn, scopeOf } from '../../resolve';\nimport { currentTransaction } from '../../transaction';\nimport type { Visibility } from '../../visibility';\nimport { Outermost } from '../field-action-base';\nimport { ValueChangedAction } from '../value-changed-action';\n\nimport { Statement } from './statement';\n\nconst ConditionalStatementActionClassIdentifier = Symbol('ConditionalStatementAction');\n\ntype ConditionalExecutorFn = (field: FieldBase, currentResult: boolean, previousResult: boolean | undefined) => void;\n\n/** The action's state for one target: the last result applied to it. */\ninterface ConditionalTargetState {\n lastResult: boolean | undefined;\n}\n\nexport class ConditionalStatementAction extends ValueChangedAction {\n private readonly statement: Statement;\n\n private readonly conditionalExecutor: ConditionalExecutorFn;\n\n /**\n * The declarations of the elements this action was registered on. It holds declarations, not the elements, so one\n * entry covers every row of a list; a result is applied to the element that corresponds to the declaration within\n * the record the change happened in.\n */\n private readonly declarations = new Set<FieldBase>();\n\n /**\n * The elements this action was registered on. Registration happens one element at a time (the rows of a list\n * receive the action one by one, as they are built from the item template), so this set determines which of the\n * elements of a declaration the action controls.\n */\n private readonly registrations = new WeakSet<FieldBase>();\n\n constructor(statement: Statement, executorFn: ConditionalExecutorFn) {\n // the element the action fires for determines the record: an eager pass over one row's field re-evaluates the\n // statement over that row and applies it to that row's targets. A pass that finds no target runs over an\n // element whose record is still being built, and the container that completes it runs the pass again\n super((field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => {\n if (!this.applyIn(scopeOf(field))) field.markRecordIncomplete();\n return supr(field, newValue, oldValue);\n });\n\n this.statement = statement;\n this.conditionalExecutor = executorFn;\n\n // one listener per field the statement reads, however many records the field has: the listener receives the\n // field that changed, which determines the record to re-evaluate. A listener per record would add one handler\n // to the field's chain for every row of a list. It runs outermost in the field's chain, so a handler that does\n // not call supr does not keep it from running\n this.relay = new ValueChangedAction((source: FieldBase, supr: FieldActionExecute, ...params: any[]) => {\n this.applyFrom(source);\n return supr(source, ...params);\n });\n (this.relay as any)[Outermost] = true;\n this.listen();\n }\n\n /**\n * The listener on the fields the statement reads. The constructor installs it; it is removed when the action is\n * taken off its last element and installed again when the action is next registered.\n */\n private readonly relay: ValueChangedAction;\n\n /** The number of elements the action is registered on; the relay is removed when it drops to zero. */\n private registered = 0;\n\n private listening = false;\n\n private listen(): void {\n if (this.listening) return;\n this.listening = true;\n this.statement.collectFields().forEach((field) => field.registerAction(this.relay));\n }\n\n static get classIdentifier() {\n return ConditionalStatementActionClassIdentifier;\n }\n\n get eager() {\n return true;\n }\n\n boundToBinding(binding: FieldBase) {\n this.declarations.add(binding.declaration);\n if (!this.registrations.has(binding)) this.registered++;\n this.registrations.add(binding);\n this.listen();\n }\n\n /** Forgets the result last applied to `binding`, so the next pass applies the statement over its new flags. */\n resetBinding(binding: FieldBase) {\n this.forgetState(binding);\n }\n\n unregisterFrom(binding: FieldBase) {\n if (this.registrations.delete(binding)) this.registered--;\n // taken off the last element, the action has nothing left to apply, and the listener it installed on the fields\n // the statement reads is removed with it\n if (this.registered === 0 && this.listening) {\n // a rollback re-registers the relay first and the action on its element after it (newest undo first), so the\n // flag is restored in between and the re-registered action does not install the relay a second time\n currentTransaction()?.whenRolledBack(() => {\n this.listening = true;\n });\n this.listening = false;\n this.statement.collectFields().forEach((field) => field.unregisterAction(this.relay));\n }\n }\n\n /**\n * The elements of `scope` this action controls: for each of its declarations, the corresponding elements within\n * that record that the action is registered on. A row of a list the action is not registered on is skipped.\n */\n private targetsIn(scope: FieldBase): FieldBase[] {\n const targets: FieldBase[] = [];\n this.declarations.forEach((declaration) =>\n bindingsIn(declaration, scope).forEach((target) => {\n if (this.registrations.has(target)) targets.push(target);\n }),\n );\n return targets;\n }\n\n /**\n * Re-evaluates the statement over one record and applies the result to every target whose last applied result\n * differs, so a target registered after the result was applied to another one in the same record receives it.\n * The result is recorded before the executor runs, because an executor that writes a value re-enters through that\n * value's eager pass, which must see the result being applied. Returns whether the record contains a target for\n * this action; false means the record is not assembled yet.\n */\n private applyIn(scope: FieldBase): boolean {\n const targets = this.targetsIn(scope);\n if (targets.length === 0) return false;\n const currentResult = this.statement.evaluate(scope);\n targets.forEach((target) => {\n const state = this.state(target, (): ConditionalTargetState => ({ lastResult: undefined }));\n if (currentResult === state.lastResult) return;\n const previousResult = state.lastResult;\n state.lastResult = currentResult;\n this.conditionalExecutor(target, currentResult, previousResult);\n });\n return true;\n }\n\n /**\n * Re-evaluates the records affected by a change of `source`. A change of an element in the targets' record\n * affects only that record, so one row of a list does not affect another; a change of an element above them (a\n * form field every row reads) affects every record below it, or the record the action was declared in if there\n * is no record below it.\n */\n private applyFrom(source: FieldBase): void {\n const scopes = new Set<FieldBase>();\n this.targetsIn(scopeOf(source)).forEach((target) => scopes.add(scopeOf(target)));\n scopes.forEach((scope) => this.applyIn(scope));\n }\n}\n\n// Derived classes for visibility, access, and value changes\n\n/**\n * Sets the visibility of the elements it is registered on from the statement's result: `whenTrue` while the\n * statement is true, `whenFalse` otherwise. Visibility affects presentation only; what the elements send is\n * determined by their access.\n */\nexport class ConditionalVisibilityAction extends ConditionalStatementAction {\n constructor(statement: Statement, whenTrue: Visibility = 'full', whenFalse: Visibility = 'suppress') {\n super(statement, (field: FieldBase, currentResult) => {\n field.visibility = currentResult ? whenTrue : whenFalse;\n });\n }\n}\n\n/**\n * Sets the access of the elements it is registered on from the statement's result: `whenTrue` while the statement\n * is true, `whenFalse` otherwise.\n */\nexport class ConditionalAccessAction extends ConditionalStatementAction {\n constructor(statement: Statement, whenTrue: Access = 'editable', whenFalse: Access = 'disabled') {\n super(statement, (field, currentResult) => {\n field.access = currentResult ? whenTrue : whenFalse;\n });\n }\n}\n\nexport class ConditionalValueAction<T> extends ConditionalStatementAction {\n constructor(statement: Statement, trueValue: T) {\n super(statement, (field, currentResult) => {\n if (currentResult) field.value = trueValue;\n });\n }\n}\n","/**\n * The operators of a `Statement`. A backend can send a condition composed of them, which sets the visibility of\n * form elements.\n */\nenum Operator {\n // Logic Operators\n NOT = 0,\n OR = 1,\n AND = 2,\n XOR = 3,\n NAND = 4,\n NOR = 5,\n\n // Comparators (comparison operators)\n EQUALS = -1,\n NOT_EQUALS = -2,\n GT = -3,\n LT = -4,\n GE = -5,\n LE = -6,\n IN = -7,\n NOT_IN = -8,\n INCLUDES = -9,\n NOT_INCLUDES = -10,\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, no-redeclare\nnamespace Operator {\n export function fromString(operator: string): Operator {\n const op = operator.toLowerCase();\n if (op === 'not') return Operator.NOT;\n if (op === 'or') return Operator.OR;\n if (op === 'and') return Operator.AND;\n if (op === 'xor') return Operator.XOR;\n if (op === 'nand') return Operator.NAND;\n if (op === 'nor') return Operator.NOR;\n\n if (op === 'equals') return Operator.EQUALS;\n if (['not_equals', 'not-equals', 'not equals'].includes(op)) return Operator.NOT_EQUALS;\n if (op === 'gt') return Operator.GT;\n if (op === 'lt') return Operator.LT;\n if (op === 'ge') return Operator.GE;\n if (op === 'le') return Operator.LE;\n if (op === 'in') return Operator.IN;\n if (['not_in', 'not-in', 'not in'].includes(op)) return Operator.NOT_IN;\n if (op === 'includes') return Operator.INCLUDES;\n if (['not_includes', 'not-includes', 'not includes'].includes(op)) return Operator.NOT_INCLUDES;\n throw new Error(`Unrecognised operator ${op}`);\n }\n\n /** `mode` as an operator: a number that is an operator value, or a name `fromString()` parses; else throws. */\n export function fromAny(mode: any): Operator {\n const input = typeof mode === 'number' ? mode : Operator.fromString(mode as string);\n if (Object.values(Operator).includes(input)) return input;\n throw new Error(`Unrecognised operator ${mode}`);\n }\n\n /** Whether `operator` is an operator or the name of one; an unknown name is not, and does not throw. */\n export function isDefined(operator: number | string): boolean {\n if (typeof operator === 'number') return Object.values(Operator).includes(operator);\n try {\n return Object.values(Operator).includes(Operator.fromString(operator));\n } catch {\n return false;\n }\n }\n\n /** Whether `operator` is a logic operator (`NOT` … `NOR`) rather than a comparison. */\n // c8 reports the next line as a branch with one uncovered path, whatever the line contains\n export function isLogicOperator(operator: Operator): boolean {\n return operator >= 0;\n }\n}\n\nObject.freeze(Operator);\n\nexport default Operator;\n","import FieldActionBase from './field-action-base';\n\nimport type { Access } from '@/access';\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst AccessChangingActionClassIdentifier = Symbol('AccessChangingAction');\n\n/**\n * Fires before an element's `access` is written. A handler returns the access to write instead, or throws\n * `AbortEventHandlingException` to cancel the write.\n */\nexport class AccessChangingAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access) => Access) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return AccessChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access): Access {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst AccessChangedActionClassIdentifier = Symbol('AccessChangedAction');\n\n/** Fires after an element's `access` has been written. */\nexport class AccessChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return AccessChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Access, oldValue: Access): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nexport const ContributionChangedActionClassIdentifier = Symbol('ContributionChangedAction');\n\n/**\n * Fires when what an element sends to its container's `value` changed over a transaction: the element's value if\n * its access sends it, `null` for `'disabled-null'`, and `undefined` for `'disabled'`, whose key or row is omitted.\n * The parameters are (contribution now, contribution at the last announcement).\n *\n * `ValueChangedAction` reports what the element holds; this action reports what it sends. A write into a\n * `'disabled'` field changes what the field holds and not what it sends, so it fires only `ValueChangedAction`;\n * changing a field's access changes what it sends and not what it holds, so it fires only this action. A container\n * holds its `fullValue` and sends its `value`, so a change of a member's access fires this action on the\n * containers above, and not `ValueChangedAction`.\n */\nexport class ContributionChangedAction<T = any> extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: unknown, oldValue: unknown) => void,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ContributionChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase<T>, supr: FieldActionExecute<T>, newValue: unknown, oldValue: unknown): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst EnabledChangingActionClassIdentifier = Symbol('EnabledChangingAction');\n\n/**\n * Fires before a write of `access` that would change `enabled`: a change into or out of `'editable'`. It fires\n * after `AccessChangingAction`, for the access that would be written. `enabled` is read from `access`, so the\n * return value cannot set it: returning the current value of `enabled`, or throwing\n * `AbortEventHandlingException`, cancels the write of `access`; returning the new value, `null` or `undefined`\n * allows it.\n */\nexport class EnabledChangingAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => boolean,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return EnabledChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): boolean {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst EnabledChangedActionClassIdentifier = Symbol('EnabledChangedAction');\n\n/**\n * Fires after a write of `access` changed `enabled`: a change into or out of `'editable'`. It fires after\n * `AccessChangedAction`; a change between two accesses that are not `'editable'` does not fire it.\n */\nexport class EnabledChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return EnabledChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ValidChangedActionClassIdentifier = Symbol('ValidChangedAction');\n\nexport class ValidChangedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ValidChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: boolean, oldValue: boolean): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\nimport type { Visibility } from '@/visibility';\n\nconst VisibilityChangingActionClassIdentifier = Symbol('VisibilityChangingAction');\n\nexport class VisibilityChangingAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility) => Visibility,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return VisibilityChangingActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility): Visibility {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n\nconst VisibilityChangedActionClassIdentifier = Symbol('VisibilityChangedAction');\n\nexport class VisibilityChangedAction extends FieldActionBase {\n constructor(\n executorFn: (field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility) => void,\n ) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return VisibilityChangedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, newValue: Visibility, oldValue: Visibility): void {\n return super.execute(field, supr, newValue, oldValue);\n }\n}\n","import { isEmpty, isEqual } from 'lodash-es';\nimport { reactive, toRaw, watch } from 'vue';\n\nimport { type Access, accessValues, isAccess } from './access';\nimport { AccessChangedAction, AccessChangingAction } from './actions/access-actions';\nimport ActionsMap from './actions/actions-map';\nimport {\n ContributionChangedAction,\n ContributionChangedActionClassIdentifier,\n} from './actions/contribution-changed-action';\nimport { EnabledChangedAction, EnabledChangingAction } from './actions/enabled-actions';\nimport FieldActionBase from './actions/field-action-base';\nimport { ValidChangedAction } from './actions/valid-changed-action';\nimport { ValueChangedAction, ValueChangedActionClassIdentifier } from './actions/value-changed-action';\nimport { VisibilityChangedAction, VisibilityChangingAction } from './actions/visibility-actions';\nimport { type Container } from './container';\nimport {\n BeginValidating,\n ChangedSinceErrors,\n type ElementSlots,\n ErrorPoliciesChanged,\n NoErrorsBaseline,\n RemoveErrorsOnSubmit,\n ValidationEpoch,\n} from './element-state';\nimport { AbortEventHandlingException, type Extras, IBindParams } from './field.interface';\nimport { elementAdopted, elementCreated, pipeOriginalValue } from './plugins';\nimport {\n currentTransaction,\n type Transaction,\n SentNowhere,\n TxAnnounceValue,\n TxCapture,\n TxRestore,\n TxAnnounceFlags,\n TxSettleValidity,\n type TxSnapshot,\n type TxStructuralEvent,\n transactional,\n} from './transaction';\nimport {\n defaultRule,\n ErrorPolicy,\n type ErrorPolicyRule,\n readRulesVersion,\n ruleIn,\n rulesArePositional,\n} from './validators/error-policy';\nimport { type ErrorOrigin, ValidationError } from './validators/validation-error';\nimport { Validator } from './validators/validator';\nimport { isVisibility, type Visibility, visibilityValues } from './visibility';\n\n/**\n * The bindings made from a declaration, held outside it and weakly: a binding is released with the record it\n * belongs to, and the declaration does not keep it alive. A rule registered on an item template reaches the rows\n * that already exist through this map; the declaration holds no other reference to them.\n */\nconst bindingsMade = new WeakMap<object, Set<WeakRef<FieldBase>>>();\n\n/**\n * The parameter keys that name what to register on an element. The constructor registers them and applies the\n * other keys, and `bind()` passes its overrides on whole, so these keys are listed here to keep them out of both\n * the element's members and its extended properties.\n */\nconst registrationParams: ReadonlySet<string> = new Set(['validators', 'actions']);\n\n/**\n * Whether `key` names an accessor (a getter, a setter or both) declared on `element`'s prototype chain below\n * `Object.prototype`. A construction parameter with such a key is assigned to the element; any other key is an\n * extended property.\n */\nfunction accessorOf(element: object, key: string): boolean {\n for (let proto = Object.getPrototypeOf(element); proto && proto !== Object.prototype;) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n if (descriptor) return descriptor.get !== undefined || descriptor.set !== undefined;\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n}\n\n/** formats a value for an error message: a string quoted, anything else through String() */\nconst describe = (value: unknown) => (typeof value === 'string' ? `'${value}'` : String(value));\n\n/** formats the accepted values as a list for an error message */\nconst listOf = (values: readonly string[]) => values.map(describe).join(', ');\n\n/** Whether a rule governs `error`: every origin but `'validator'` has one. */\nconst ruled = (error: ValidationError) => error.origin !== 'validator';\n\n/** What an element with `access` sends: its value, `null` or nothing. `'editable'` and `'readonly'` send the same. */\nconst sendsAs = (access: Access) => (access === 'disabled' ? 'omit' : access === 'disabled-null' ? 'null' : 'value');\n\n/**\n * Throws a TypeError for a parameter object that contains `enabled`. `enabled` is read from `access` and has no\n * setter. Without this check, a parameter object that bypasses the type system (parsed from JSON, typed `any`)\n * has the key dropped by `bind()`, or rejected with a TypeError that does not name `access` as the replacement.\n */\nfunction refuseEnabled(params: object): void {\n if (Object.hasOwn(params, 'enabled')) {\n throw new TypeError(\n `enabled is read from access and cannot be assigned; state access instead: ${listOf(accessValues)}`,\n );\n }\n}\n\n/**\n * The number of elements waiting for the record they belong to. A container that completes a record reads this\n * before it walks anything, so a form in which no element waits for its record does no walk.\n */\nlet incompleteRecords = 0;\n\n/** The elements the reset in progress has reset, each after its members; null outside a reset. */\nlet resetElements: FieldBase[] | null = null;\n\nexport abstract class FieldBase<T = any, X extends object = Extras> {\n /**\n * Vue's getTargetType returns INVALID for an object that has __v_skip, so reactive() returns an element\n * unwrapped and no element is wrapped in a proxy of its own. isReactive() reads the second flag, which is true\n * because the element's state, which holds its reactivity, is a reactive object.\n *\n * Two consequences for a consumer, neither of which raises an error. watch(field, cb) with a bare element as the\n * source registers no dependency, because Vue's deep traversal of a reactive source stops on __v_skip; use\n * watch(() => field.value, cb). readonly(field) returns the element itself, so a write through the result\n * reaches the field; to pass a read-only view, pass the value (which is frozen) or a computed over it.\n */\n get __v_skip(): boolean {\n return true;\n }\n\n get __v_isReactive(): boolean {\n return true;\n }\n\n /**\n * The tag that a structural comparison of two elements uses. An element keeps its state in private class fields,\n * so a walk over own keys reaches none of it. lodash reads this tag through Object.prototype.toString before it\n * compares anything and stops at a tag it does not recognise, so two elements are equal only if they are the\n * same element. The package's own `isEqual` compares an element by the value it holds.\n *\n * It is an accessor on the prototype, so it adds no own property to an element, and `Object.prototype.toString`\n * returns `[object Field]` instead of `[object Object]`. Each class declares its name as a literal, because a\n * minifier renames the class and the constructor's name would be the minified one.\n */\n get [Symbol.toStringTag](): string {\n return 'FormElement';\n }\n\n /**\n * The element's mutable state, in an object beside the element. `#state` is the tracked view of it: a slot read\n * through it inside an effect subscribes the effect to that slot, and a write to the slot re-runs the effect.\n * `#raw` is the same object without the proxy, used for bookkeeping that nothing renders from.\n *\n * Both are private class fields, so reflection over the element does not reach the state or the parent link in\n * it. A subclass reads its own slot type through the accessors below.\n */\n readonly #state: ElementSlots<T>;\n\n readonly #raw: ElementSlots<T>;\n\n constructor(slots: ElementSlots<T>) {\n this.#raw = slots;\n this.#state = reactive(slots) as ElementSlots<T>;\n elementCreated(this);\n }\n\n /** the tracked view of this element's state; a subclass narrows the return type to its own slots */\n protected get state(): ElementSlots<T> {\n return this.#state;\n }\n\n /** the untracked view of this element's state; a subclass narrows the return type to its own slots */\n protected get raw(): ElementSlots<T> {\n return this.#raw;\n }\n\n abstract get value(): T;\n abstract set value(newValue: T);\n\n abstract get touched(): boolean;\n abstract set touched(touched: boolean);\n\n /**\n * Returns a new element of this one's class over `data`, with the same registered actions and extended\n * properties and a new change history. Every row a `List` builds is its item template bound to that row's data.\n * The new element's `declaration` is the element `bind()` is called on.\n *\n * `data` of `undefined` means no data: the new element holds what this one holds. An explicit `null` is data and\n * clears the value. In `overrides`, `originalValue` is applied when the key is present, `access` and `visibility`\n * default to this element's, and the extended properties given are written over the copied ones. The new element\n * is detached (no `parent`, no `fieldName`), so a container can take it.\n */\n abstract bind(data?: T, overrides?: IBindParams<T, X>): FieldBase<T, X>;\n\n /**\n * Replaces the data this element holds with `data`, in place. The instance, its actions, its extended properties\n * and its position in its container are unchanged, and the element ends in the state `bind(data)` produces: the\n * values are written, the change history starts over and the validators run. A virtualised renderer uses it to\n * reuse one element across records.\n *\n * No `ValueChangedAction` fires for the element itself, as for a newly built element. Its members announce their\n * changes, and a change of validity is announced as usual: a rebound element that is invalid updates the invalid\n * count of its container. If an open transaction already has a pending value change for the element, the commit\n * announces it with the value the element had when the transaction opened as the old value.\n *\n * A member of a `Group` whose key is missing from `data` takes the `originalValue` of the corresponding member of\n * the group's `declaration`: for a group that is its own declaration, the member's own baseline. A key missing\n * from the data never takes the value of the previous record.\n *\n * The element keeps its `access` and `visibility`. A member reset from an element other than itself (a member of\n * a bound group, a reused `List` row) takes them from that element, see `resetChild`.\n */\n rebind(data: T): this {\n transactional((tx) => {\n tx.touch(this);\n // the baseline of a change the transaction has yet to announce is kept: the element is already enrolled to\n // announce that change, and moving the baseline to the new record would cancel the announcement. Both are\n // read before the reset, which enrols the element and, on a container, writes its own baseline.\n const owed = tx.willAnnounceValue(this);\n const { announcedValue, announcedContribution, validatedValue } = this.#raw;\n this.asReset(() => {\n this.resetTo(this.declaration, data);\n resetElements?.push(this);\n });\n // with no pending change, what the element now holds and sends is recorded as announced, so the commit\n // announces no change of either\n if (owed) Object.assign(this.#raw, { announcedValue, announcedContribution, validatedValue });\n else this.recordAnnounced();\n });\n return this;\n }\n\n /** contains original field value as was provided at creation */\n get originalValue(): T {\n return this.#state.originalValue;\n }\n\n set originalValue(newValue: T) {\n this.touchState();\n this.#state.originalValue = pipeOriginalValue(this, newValue);\n }\n\n /**\n * The extended properties of this element: properties a consumer attached beyond the members the class declares,\n * such as the label, hint or css class a UI layer binds to the input it renders for the element. The read is\n * tracked, so a template that reads `field.extra.label` re-renders when the property is written.\n *\n * Every property is optional here, whatever `X` declares: a parameter object need not contain any, and\n * setExtendedValues can write any subset, so a property `X` declares as required is present only after it has\n * been written.\n *\n * The object is frozen; change it with setExtendedValues. A transaction captures this object, so an in-place\n * write would leave a rollback with no previous state to restore.\n */\n get extra(): Readonly<Partial<X>> {\n return this.#state.extra as Readonly<Partial<X>>;\n }\n\n /**\n * Writes extended properties. The given values are merged over the existing ones, so a write of one property\n * keeps the others, and the merged object replaces the one the element held.\n */\n setExtendedValues(values: Partial<X>): void {\n this.touchState();\n this.#state.extra = Object.freeze({ ...this.#raw.extra, ...values });\n }\n\n /**\n * Returns the extended properties in a parameter object: every key that is not a member of the element. A key\n * that is a member when the parameters are applied (`value`, `access`, an accessor a subclass adds) belongs to\n * the element. A key that exists only on Object.prototype counts as extended. `validators` and `actions` are\n * neither: they name what to register on the element.\n *\n * A member a subclass declares as a class field is not a member at this point: class fields are defined on the\n * instance after the base constructor returns, and the parameters are applied inside it. A subclass that needs a\n * parameter assigned to a member of the same name declares that member as an accessor.\n */\n protected extendedOf(params: object): Partial<X> {\n // the accumulator has no prototype, so a params key of `__proto__` (possible in a parameter object parsed from\n // JSON) becomes an own property instead of calling the Object.prototype setter and replacing the accumulator's\n // prototype, which would make the ownership test below match keys that were never added\n const extended: Record<string, any> = Object.create(null);\n Object.entries(params).forEach(([key, value]) => {\n if (registrationParams.has(key)) return;\n if (!accessorOf(this, key)) extended[key] = value;\n });\n return extended as Partial<X>;\n }\n\n /**\n * Applies a parameter object: a key that names an accessor of the element is assigned to the element, and every\n * other key becomes an extended property. A key named like a method or another non-accessor member (`validate`,\n * `bind`, `settled`) is stored in `extra` and leaves the member as it is. Assigning a getter-only accessor throws a\n * TypeError, so a parameter object that bypasses the type system and contains `valid` or `parent` throws.\n */\n protected assignParams(params: object): void {\n refuseEnabled(params);\n const extended = this.extendedOf(params);\n Object.entries(params).forEach(([key, value]) => {\n if (Object.hasOwn(extended, key) || registrationParams.has(key)) return;\n (this as any)[key] = value;\n });\n if (!isEmpty(extended)) this.setExtendedValues(extended);\n }\n\n /**\n * Adds this element to the record of the open transaction, if one is open. A write of a single slot that announces\n * nothing calls it instead of opening a transaction: outside a transaction such a write is atomic, and inside one\n * it must be restored by a rollback.\n */\n protected touchState(): void {\n currentTransaction()?.touch(this);\n }\n\n /**\n * Records all of this element's mutable state, so that a rolled-back transaction restores it exactly. The errors\n * array is copied because a validator modifies the array in place, and a subclass copies any other state it holds\n * by reference in the same way.\n *\n * The action map is not in the snapshot: no write modifies it, and an operation that replaces it registers its\n * own undo with the transaction, so every element captures the same shape.\n */\n protected [TxCapture](): TxSnapshot {\n return { ...this.#raw, errors: [...this.#raw.errors] };\n }\n\n /**\n * Restores a captured state. It writes through the tracked view, so an effect that ran on the state the\n * transaction produced runs again on the restored state, for the slots that differ.\n *\n * The two validation counters are not restored: they count runs in flight. A rollback cancels the asynchronous\n * runs the transaction started, and each cancelled run ends its count when its promise settles; restored counts\n * would not match the endValidating calls still to come.\n */\n protected [TxRestore](snapshot: TxSnapshot): void {\n const validating = this.#raw.validatingCount;\n const validatingChildren = this.#raw.validatingChildren;\n Object.assign(this.#state, snapshot);\n this.#state.validatingCount = validating;\n this.#state.validatingChildren = validatingChildren;\n }\n\n /**\n * True while an asynchronous validation is in flight on this element or on any element below it, so on a form it\n * covers the whole tree. It is computed from two counters, without a walk: the element's own runs, and the number\n * of its children whose `validating` is true. A child that becomes validating or stops validating updates its\n * container's counter, and a change of the container's `validating` updates the counter above it. A transition\n * costs one step per nesting level; a read costs one counter comparison.\n */\n get validating(): boolean {\n return this.#state.validatingCount > 0 || this.#state.validatingChildren > 0;\n }\n\n /**\n * Counts one asynchronous validation run as started and returns the function that counts it as ended. The\n * function ends that run only: a second call does nothing, so `validating` and `settled()` cannot report the end\n * of a run that is still in flight.\n */\n [BeginValidating](): () => void {\n const wasIdle = !this.validating;\n this.#state.validatingCount++;\n if (wasIdle) this.container?.childValidatingChanged(true);\n let ended = false;\n return () => {\n if (ended) return;\n ended = true;\n this.#state.validatingCount--;\n if (!this.validating) this.container?.childValidatingChanged(false);\n };\n }\n\n /**\n * Records that a child's `validating` became true or false, and passes the transition up if it changes this\n * element's own `validating`. Only a `Container` has children and implements this; it is declared here because a\n * child calls it on its container.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected childValidatingChanged(started: boolean): void {}\n\n /**\n * True while an `Action.execute()` at or below this element has not settled. On an `Action` it covers its own\n * runs, on a container the actions below it; on any other element it is false.\n *\n * It does not include validation; `pending` covers both.\n */\n get busy(): boolean {\n return false;\n }\n\n /**\n * True while an asynchronous validation or an `Action.execute()` at or below this element has not settled:\n * `validating || busy`. It is reactive, so a template binds a submit button to it. `settled()` resolves when it\n * turns false.\n */\n get pending(): boolean {\n return this.validating || this.busy;\n }\n\n /**\n * Resolves when nothing at or below this element is running: no asynchronous validation and no unsettled\n * `Action.execute()`, which is when `pending` is false. A submit path awaits it instead of polling `pending`. If\n * nothing is running, the returned promise is already resolved.\n *\n * It covers only the moment it resolves: work started later makes the element run again, so a caller that needs\n * a settled tree reads what it needs immediately after the await.\n */\n settled(): Promise<void> {\n if (!this.pending) return Promise.resolve();\n return new Promise((resolve) => {\n // sync flush, so the promise resolves in the write that ended the last run, not a tick later\n const stop = watch(\n () => this.pending,\n (running) => {\n if (running) return;\n stop();\n resolve();\n },\n { flush: 'sync' },\n );\n });\n }\n\n /**\n * List of errors. The returned array is the one the element holds, and a validator modifies it in place, so this\n * getter adds the element to an open transaction's record: otherwise a rollback would restore everything except\n * the errors.\n *\n * The array and its members are Vue proxies, not the raw instances a validator returned: `field.errors[0] ===\n * myError` is `false` even for the same error. Compare identity with `toRaw()`.\n *\n * Whether an error of an origin other than `'validator'` counts toward `valid`, and when the element removes it\n * by itself, is the rule of its origin: see `ErrorPolicy`. An `'edit'` rule compares the value the element holds\n * against the one it held when the error was written: the value at the assignment of `errors`. For an error added\n * to the array in place it is the value at the next read of `errors` outside a transaction, and a change of the\n * element's value before that read counts as a change.\n */\n get errors(): ValidationError[] {\n this.touchState();\n // a validator reads the errors while a write is in progress, after the value changed: the value recorded there\n // would be the changed one. A read inside a transaction records nothing, and a change before the next read\n // outside one is recorded as a change (errorsAfterChange)\n if (!currentTransaction()) this.noteErrorsBaseline();\n return this.#state.errors;\n }\n\n set errors(newValue: ValidationError[]) {\n this.touchState();\n this.#state.errors = newValue;\n this.#raw.errorsBaseline = NoErrorsBaseline;\n this.noteErrorsBaseline();\n }\n\n /** Records the value the element holds as `errorsBaseline` where it holds a ruled error and has none recorded. */\n private noteErrorsBaseline(): void {\n const raw = this.#raw;\n if (raw.errorsBaseline !== NoErrorsBaseline || !raw.errors.some(ruled)) return;\n raw.errorsBaseline = toRaw(this.value);\n }\n\n /**\n * The rule of `origin` for this element: the one stated by the nearest `ErrorPolicy` naming it, on this element or\n * on a container above it, and otherwise the default. The walk reads `parent` through the tracked view, so a\n * validity computed over it follows the element into another container.\n */\n private ruleOf(origin: ErrorOrigin): ErrorPolicyRule {\n for (const element of this.selfAndAbove()) {\n const actions = element.boundActions;\n if (!actions?.willTrigger(ErrorPolicy.classIdentifier)) continue;\n const policies = actions.ofClass(ErrorPolicy.classIdentifier);\n for (let index = policies.length - 1; index >= 0; index--) {\n const rule = ruleIn(policies[index] as ErrorPolicy, origin);\n if (rule) return rule;\n }\n }\n return defaultRule(origin);\n }\n\n /** This element and every container above it, nearest first. */\n private selfAndAbove(): FieldBase[] {\n const chain: FieldBase[] = [this];\n for (let above = this.parent; above; above = above.parent) chain.push(above);\n return chain;\n }\n\n /** Whether `errors`, held by this element, leave it valid: none of them counts toward validity. */\n protected ownErrorsValid(errors: readonly ValidationError[]): boolean {\n if (errors.length === 0) return true;\n return !errors.some((error) => {\n if (!ruled(error)) return true;\n readRulesVersion();\n return this.ruleOf(error.origin).validEffect;\n });\n }\n\n /**\n * Removes the ruled errors whose rule `removes` accepts and returns whether it removed any. The caller has added\n * the element to the transaction and recomputes its validity.\n */\n private removeErrors(removes: (rule: ErrorPolicyRule) => boolean): boolean {\n const errors = this.#state.errors;\n let removed = false;\n for (let i = errors.length - 1; i >= 0; i--) {\n if (ruled(errors[i]) && removes(this.ruleOf(errors[i].origin))) {\n errors.splice(i, 1);\n removed = true;\n }\n }\n if (!this.#raw.errors.some(ruled)) this.#raw.errorsBaseline = NoErrorsBaseline;\n return removed;\n }\n\n /**\n * Called when `touched = true` is written on this element: on it and on every container above it, the errors whose\n * rule removes them on `'edit'` are removed where the element's value differs from the one recorded when they\n * were written.\n */\n protected editConcluded(): void {\n const holds = (element: FieldBase) =>\n element.#raw.errors.some((error) => ruled(error) && element.ruleOf(error.origin).removeOn === 'edit');\n const chain = this.selfAndAbove().filter(holds);\n if (chain.length === 0) return;\n transactional((tx) => {\n for (const element of chain) {\n const raw = element.#raw;\n const baseline = raw.errorsBaseline;\n tx.touch(element);\n if (baseline === NoErrorsBaseline) {\n // nothing recorded and no change since the errors were written: the value they describe is this one\n raw.errorsBaseline = toRaw(element.value);\n continue;\n }\n if (baseline !== ChangedSinceErrors && isEqual(element.value, baseline)) continue;\n element.removeErrors((rule) => rule.removeOn === 'edit');\n tx.markValidityDirty(element);\n }\n });\n }\n\n /** Removes, on this element and every element below it, the errors whose rule removes them on `'submit'`. */\n [RemoveErrorsOnSubmit](): void {\n transactional((tx) => {\n const visit = (element: FieldBase) => {\n if (element.#raw.errors.some(ruled)) {\n tx.touch(element);\n if (element.removeErrors((rule) => rule.removeOn === 'submit')) tx.markValidityDirty(element);\n }\n element.members.forEach(visit);\n };\n visit(this);\n });\n }\n\n /**\n * Recomputes the validity of every element at or below this one that holds a ruled error, after the rules over\n * those errors may have changed.\n */\n [ErrorPoliciesChanged](): void {\n transactional((tx) => {\n const visit = (element: FieldBase) => {\n if (element.#raw.errors.some(ruled)) tx.markValidityDirty(element);\n element.members.forEach(visit);\n };\n visit(this);\n });\n }\n\n /**\n * The container that holds this element: the Group it is a member of, or the List whose row it is, and\n * undefined while no container holds it. Only the container writes it. The read is tracked, so an effect that\n * reads it (`v-if=\"field.parent\"`) re-runs when a container takes or releases the element.\n *\n * The type is `Container`, which declares no members: a sibling lookup narrows it, either with\n * `field.parent instanceof Group` or with a cast where the structure guarantees the type.\n */\n get parent(): Container | undefined {\n return this.#state.parent;\n }\n\n /**\n * The same link, typed as `FieldBase` for internal calls. The hooks a child calls on its container\n * (childValidatingChanged, childValidityChanged) are declared here, and a protected member is reachable only\n * through the class that declares it; `Container` overrides them.\n */\n private get container(): FieldBase | undefined {\n return this.#state.parent;\n }\n\n /** when member of a Group, fieldName specifies the name of this field. Written by the group, read-only after */\n get fieldName(): string | undefined {\n return this.#state.fieldName;\n }\n\n /**\n * The element this one was declared as: itself for an element built from parameters, and the element it was\n * bound from for a binding, transitively, so a binding of a binding has the same declaration. Every row a `List`\n * builds from its item template is a binding of it, so a row's member and the corresponding item template member\n * have the same `declaration`, and an action registered on the item template can distinguish the two.\n */\n get declaration(): FieldBase {\n return this.#raw.declaration ?? this;\n }\n\n /** The elements this one holds: a Group's members, a List's rows, none for a leaf. */\n protected get members(): FieldBase[] {\n return [];\n }\n\n /**\n * Returns every element in this element's subtree, this element included, whose declaration is `declaration`. A\n * shared action uses it when the change happened in a different record than its targets (a form field that every\n * row of a list reacts to). It walks the subtree, so it is used only when resolution within a single record does\n * not apply.\n */\n bindingsOf(declaration: FieldBase): FieldBase[] {\n const canonical = declaration.declaration;\n const found: FieldBase[] = [];\n const visit = (element: FieldBase) => {\n if (element.declaration === canonical) found.push(element);\n element.members.forEach(visit);\n };\n visit(this);\n return found;\n }\n\n /** set while an eager pass over this element is waiting for the record the element belongs to */\n declare protected _recordPending?: boolean;\n\n /**\n * Marks that an eager pass over this element did not find an element it needs, because the record this element\n * belongs to was not assembled yet: a `List` row is built member by member and its members are bound before the\n * row holds them, so a validator comparing two of them runs before the row exists. The container that completes\n * the record runs the pass again; a pass that still finds nothing marks the element again, and the next container\n * above runs it.\n */\n markRecordIncomplete(): void {\n if (this._recordPending) return;\n this._recordPending = true;\n incompleteRecords++;\n }\n\n /**\n * Runs the pending eager passes in `element`'s subtree, once the record it belongs to is assembled. A container\n * calls it after it completes a record: a Group after it has written its members, and a List after it has taken a\n * row, which connects the row's elements to the form above it.\n */\n protected completeRecords(element: FieldBase = this): void {\n if (incompleteRecords === 0) return;\n transactional(() => {\n const visit = (current: FieldBase) => {\n if (current._recordPending) {\n current._recordPending = false;\n incompleteRecords--;\n current.rerunEagerActions();\n }\n current.members.forEach(visit);\n };\n visit(element);\n });\n }\n\n /** Runs this element's eager actions over the value it holds and recomputes its validity. */\n private rerunEagerActions(): void {\n transactional((tx) => {\n this.boundActions?.triggerEager(this, this.contribution, this.contribution);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * The map of actions registered on a declaration; undefined until one is registered. A binding has no map of its\n * own: its slot holds the same map as its declaration.\n */\n declare protected _actions?: ActionsMap;\n\n /**\n * The actions registered for this element; undefined if none are registered. A binding holds its declaration's\n * map itself, not a copy, so a trigger reads one property, and a rule registered on a `List`'s item template\n * reaches every row through the shared map, including rows built before the registration.\n */\n protected get boundActions(): ActionsMap | undefined {\n return this._actions;\n }\n\n /** Records that `binding` was made from this element, so a later registration can reach it. */\n protected noteBinding(binding: FieldBase): void {\n let made = bindingsMade.get(this);\n if (!made) {\n made = new Set();\n bindingsMade.set(this, made);\n }\n made.add(new WeakRef(binding));\n }\n\n /**\n * The live bindings made from this element's declaration, and the declaration itself. Dead references are removed\n * when found, so the set does not grow over the life of a long-lived declaration.\n */\n protected get boundElements(): FieldBase[] {\n const declaration = this.declaration;\n const made = bindingsMade.get(declaration);\n const alive: FieldBase[] = [declaration];\n if (!made) return alive;\n made.forEach((ref) => {\n const binding = ref.deref();\n if (!binding) made.delete(ref);\n else alive.push(binding);\n });\n return alive;\n }\n\n /**\n * The map registrations go into: the declaration's. The map is created on the first registration and assigned to\n * every binding already made from the declaration, so all of them read one map through their own slot.\n */\n protected get actions(): ActionsMap {\n const declaration = this.declaration;\n if (!declaration._actions) {\n const map = new ActionsMap();\n declaration.boundElements.forEach((element) => {\n element._actions = map;\n });\n }\n return declaration._actions!;\n }\n\n /**\n * Counts the writes that have changed the value of this element or of any element below it. A container reads it\n * before returning its cached value, and the read is tracked, so an effect that read a cached value re-runs when\n * a descendant is written.\n */\n protected get valueVersion(): number {\n return this.#state.valueVersion;\n }\n\n /**\n * Marks the value of this element and of every ancestor as outdated. It walks the parent chain only (one step per\n * nesting level); an ancestor rebuilds its value on the next read. The walk adds each element to the open\n * transaction, so a rollback restores the versions and no cached value outlives the state it was built from.\n */\n protected bumpValueVersion(): void {\n transactional((tx) => {\n tx.touch(this);\n this.#state.valueVersion++;\n let ancestor: FieldBase | undefined = this.parent;\n while (ancestor) {\n tx.touch(ancestor);\n ancestor.#state.valueVersion++;\n ancestor = ancestor.parent;\n }\n });\n }\n\n /**\n * Marks that this element's value changed, and with it the value of every container above it. Nothing is\n * announced here: at commit the transaction determines which enrolled elements hold a different value and\n * announces each of them once.\n *\n * Every value change of an element passes through here, so this is where the element removes the errors whose\n * rule removes them on `'change'`, and records that its value changed where it holds a ruled error with no value\n * recorded to compare against. The removal is part of the transaction and a rollback restores the errors.\n *\n * `force` means the caller has established that the value changed (a list with one item more or fewer is a\n * different list whatever the items compare as), so the commit announces it without a comparison.\n */\n protected propagateValueChanged(force: boolean = false): void {\n transactional((tx) => {\n tx.markValueChanged(this, force);\n this.errorsAfterChange(tx);\n tx.markValidityDirty(this);\n this.parent?.notifyValueChanged();\n });\n }\n\n /** What a change of the element's value does to its ruled errors; see `propagateValueChanged`. */\n private errorsAfterChange(tx: Transaction): void {\n const raw = this.#raw;\n if (!raw.errors.some(ruled)) return;\n tx.touch(this);\n this.removeErrors((rule) => rule.removeOn === 'change');\n if (raw.errorsBaseline === NoErrorsBaseline && raw.errors.some(ruled)) raw.errorsBaseline = ChangedSinceErrors;\n }\n\n /**\n * The last step of a construction: it runs inside the construction's transaction, with the parameters applied and\n * the value in place, before the element records its initial state.\n *\n * A subclass overrides it to complete the element. What it writes here is part of the construction, not a\n * change: the element announces no ValueChangedAction, and its eager actions and validators run once over the\n * state the hook leaves. An element whose parameters contain no `originalValue` takes the value the hook left as\n * its `originalValue` and starts unchanged; one whose parameters contain `originalValue` is compared against it.\n * A `Field` writes `_value` here, because the value setter records a change.\n *\n * A container completes itself through its members, and each member has already been constructed: the write\n * reaches it as a regular change, so the member announces it. A `Group` constructed with a value records what each\n * member holds after this hook as its baseline; without a value the member reports itself changed. To have a\n * member start unchanged in both cases, set its baseline here as well:\n * `this.fields.x.originalValue = this.fields.x.value`.\n *\n * `params` is the parameter object the constructor received, if any.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected constructed(params?: object): void {}\n\n /**\n * Re-reads the old value the next announcements will report. A contribution is composed only when something\n * listens for it, so the stored copy is re-read here. A leaf records its value at every announcement, so that\n * copy is always current; a container, which composes its held value only for a listener, re-reads that too.\n */\n protected refreshPreviousValue(): void {\n this.#raw.announcedContribution = this.contribution;\n }\n\n /**\n * The validity validate() records and announces: computed from this element's own errors and the count of invalid\n * children, so a container computes it without walking its members. `valid` reads the live errors arrays instead;\n * the two differ only for an error written into a member without a validate() call, which is the documented\n * limitation of writing errors by hand.\n */\n protected get countedValid(): boolean {\n return this.ownErrorsValid(this.#raw.errors) && this.#raw.invalidChildren === 0;\n }\n\n /**\n * Makes this element the container of `child`: it sets the back-reference, records the name a Group holds the\n * child under, and adds the child to the invalid count. An element belongs to one container at a time, so a\n * child that already has a parent throws a TypeError; releaseChild() removes the link, after which the element\n * can be taken by another container. The child's state is private to FieldBase, so a container writes the two\n * slots through this method.\n */\n protected takeChild(child: FieldBase, fieldName?: string): void {\n transactional((tx) => {\n if (child.parent) throw new TypeError('This element already belongs to a container - pass a bind() of it');\n tx.touch(child);\n child.#state.fieldName = fieldName;\n // below an editable container every element keeps its own effective access, so only a container that narrows\n // access needs the check\n const narrowing = this.effectiveAccess !== 'editable';\n const detached = narrowing ? child.effectiveAccessFromHere() : undefined;\n // only a Container calls this, since only a container holds children\n child.#state.parent = this as unknown as Container;\n // the containers above now determine what the child sends, so elements whose effective access changed are\n // validated again\n if (detached) child.revalidateWhereChanged(detached);\n // and the error policies above it now state the rules over its errors\n if (rulesArePositional()) child[ErrorPoliciesChanged]();\n this.adoptChild(child);\n elementAdopted(tx, child);\n });\n }\n\n /** Adds a child to this element's invalid count; a container calls it after setting the child's parent link. */\n protected adoptChild(child: FieldBase): void {\n transactional((tx) => {\n tx.touch(this);\n if (!child.#raw.valid && child.countsInContainer) this.#raw.invalidChildren++;\n // a run in flight below the child is now also below this element. The validation counters are outside the\n // snapshot, so the transfer registers its own undo, which reads the child at rollback time: a run that starts\n // below the child during the transaction is counted here too, and is still in flight after the rollback\n if (child.validating) this.childValidatingChanged(true);\n tx.whenRolledBack(() => {\n if (child.validating) this.childValidatingChanged(false);\n });\n // the invalid count changed, so this element's validity is recomputed\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Removes a child from this element's invalid count and clears its back-reference. With the link left in place,\n * the element would keep updating that container's invalid count and could not be taken by another container.\n */\n protected releaseChild(child: FieldBase): void {\n transactional((tx) => {\n tx.touch(this);\n tx.touch(child);\n if (!child.#raw.valid && child.countsInContainer) this.#raw.invalidChildren--;\n // released from a container that narrowed its access, the child is validated again where its effective\n // access changed\n const attached = this.effectiveAccess !== 'editable' ? child.effectiveAccessFromHere() : undefined;\n // the undo reads the child at rollback time, as in adoptChild: after the rollback this element counts the runs\n // the child has in flight at that time\n if (child.validating) this.childValidatingChanged(false);\n tx.whenRolledBack(() => {\n if (child.validating) this.childValidatingChanged(true);\n });\n child.#state.parent = undefined;\n // the name is cleared with the link, so the element is as detached as one bind() returns\n child.#state.fieldName = undefined;\n if (attached) child.revalidateWhereChanged(attached);\n if (rulesArePositional()) child[ErrorPoliciesChanged]();\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Sets this element to the state of a new binding of `source` with `value`: `value` is written if supplied, and\n * `source`'s value otherwise; the change history (originalValue, touched) starts over, and the errors are cleared\n * and set again by the validators. A container that reuses an element at a position calls it through\n * `resetChild`, which also writes the flags, inside `asReset`, which applies the rules before the baseline is\n * final, so the element is in the state of one built for that position; extended properties are kept.\n */\n protected resetTo(source: FieldBase, value: any): void {\n transactional(() => {\n const target = value === undefined ? source.value : value;\n const dropped = this.errors.length > 0;\n if (dropped) this.errors = [];\n this.touched = false;\n const assigned = this.value !== target;\n this.value = target;\n this.originalValue = this.value;\n // an assignment that changed the value ran the validators over the new value. If it was a no-op, they run\n // here only if errors were cleared; otherwise the existing validation result for the unchanged value is kept.\n this.validate(!assigned && dropped);\n });\n }\n\n /**\n * Resets a member. A container calls it to reset a child of any class. A child reset from an element other than\n * itself (a member of a bound group, a reused `List` row) also takes `source`'s `access` and `visibility`, and its\n * eager actions run again once the record is complete, so the conditional rules apply over the new record. A child\n * that is its own source (a member of a declared group) keeps its flags.\n */\n protected resetChild(child: FieldBase, source: FieldBase, value: any): void {\n if (child !== source) {\n child.access = source.access;\n child.visibility = source.visibility;\n child.boundActions?.resetBinding(child);\n }\n child.resetTo(source, value);\n resetElements?.push(child);\n }\n\n /**\n * Runs `reset`, which resets elements to new records through `resetTo`, as one reset. Once every element holds\n * its new values, the rules of each reset element (its eager actions other than the validators) run over them, and\n * each records its baseline again, so `originalValue` includes what the rules changed: a member a conditional\n * access enables is in its container's baseline. A reset inside a reset is part of the outer one.\n */\n protected asReset(reset: () => void): void {\n if (resetElements) {\n reset();\n return;\n }\n const elements: FieldBase[] = [];\n resetElements = elements;\n try {\n reset();\n } finally {\n resetElements = null;\n }\n elements.forEach((element) =>\n element.boundActions?.triggerEagerRules(element, element.contribution, element.contribution),\n );\n elements.forEach((element) => element.recordBaseline());\n }\n\n /**\n * Records what every element below this one holds as its baseline, each after its own members. A binding, and a\n * group constructed with a value, call it once built, so a member written by the construction is not a change.\n */\n protected baselineMembers(): void {\n this.members.forEach((member) => {\n member.baselineMembers();\n member.recordBaseline();\n });\n }\n\n /**\n * Records what the element holds as its baseline at the end of a reset. A container also records it as the\n * value its listeners last heard: the container that reset it announces the change.\n */\n protected recordBaseline(): void {\n this.originalValue = this.value;\n }\n\n /**\n * Records a child's new validity in this element's invalid count. Only a `Container` has children and implements\n * this; it is declared here for the same reason as `childValidatingChanged`.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected childValidityChanged(nowValid: boolean): void {}\n\n // default property handlers\n /**\n * How a rendering layer shows this element. It affects presentation only: what the element sends and whether it\n * is validated are determined by `access`, and visibility changes neither.\n */\n get visibility(): Visibility {\n return this.#state.visibility;\n }\n\n set visibility(newValue: Visibility) {\n const oldValue = this.#state.visibility;\n // writing the current value is not a change, so nothing runs: no *Changing* handler, no enrolment in the\n // transaction, no *Changed* event. The value setter follows the same rule\n if (newValue === oldValue) return;\n transactional((tx) => {\n const alteredValue = this.boundActions?.trigger(VisibilityChangingAction, this, newValue, oldValue);\n // a handler that aborted the run cancels the write: nothing is written and nothing is announced\n if (alteredValue instanceof AbortEventHandlingException) return;\n const written = alteredValue ?? newValue;\n if (!isVisibility(written))\n throw new Error(`${describe(written)} is not a visibility: ${listOf(visibilityValues)}`);\n // a handler that returned the current value refused the write\n if (written === oldValue) return;\n tx.touch(this);\n // the commit announces the net change: the value before the transaction's first write against the last one\n if (this.#raw.announcedVisibility === undefined) this.#raw.announcedVisibility = oldValue;\n this.#state.visibility = written;\n tx.markFlagsDirty(this);\n });\n }\n\n /**\n * What this element accepts and what it sends: `'editable'` and `'readonly'` send its value, `'disabled'` sends\n * nothing and `'disabled-null'` sends `null`, and only `'editable'` accepts input. The validators run over what\n * the element sends, and only where it is sent at all (see `effectiveAccess`), so a change of access that changes\n * what an element sends runs them again on that element, this one and the ones below it. A change between\n * `'editable'` and `'readonly'` changes what the element accepts, not what it sends, and runs nothing.\n */\n get access(): Access {\n return this.#state.access;\n }\n\n set access(newValue: Access) {\n const oldValue = this.#state.access;\n // as with visibility: writing the current value is not a change, and nothing runs\n if (newValue === oldValue) return;\n transactional((tx) => {\n const alteredValue = this.boundActions?.trigger(AccessChangingAction, this, newValue, oldValue);\n // as with visibility: a handler that aborted the run cancels the write\n if (alteredValue instanceof AbortEventHandlingException) return;\n const written = alteredValue ?? newValue;\n if (!isAccess(written)) throw new Error(`${describe(written)} is not an access: ${listOf(accessValues)}`);\n // a handler that returned the current access cancels the write\n if (written === oldValue) return;\n const wasEnabled = this.enabled;\n const willBeEnabled = written === 'editable';\n if (willBeEnabled !== wasEnabled) {\n // enabled is read from access, so a handler that returns the current enabled cancels the write of an access\n // that would change it\n const enabledAnswer = this.boundActions?.trigger(EnabledChangingAction, this, willBeEnabled, wasEnabled);\n if (enabledAnswer instanceof AbortEventHandlingException) return;\n if (enabledAnswer != null && typeof enabledAnswer !== 'boolean') {\n throw new Error(`${describe(enabledAnswer)} is not what an EnabledChangingAction answers with: a boolean`);\n }\n if (enabledAnswer === wasEnabled) return;\n }\n tx.touch(this);\n const oldContribution = this.contribution;\n const counted = this.countsInContainer;\n const below = this.effectiveAccessBelow();\n this.#state.access = written;\n this.revalidateWhereChanged(below);\n // a leaf's validators run here, over what it now sends; a container's run at the commit, where what it sends\n // is composed\n if (!this.composesValue && sendsAs(oldValue) !== sendsAs(written)) {\n this.boundActions?.triggerEager(this, this.contribution, oldContribution);\n }\n // the commit compares the element's contribution and that of every container above it again; what any of\n // them holds did not change\n this.contributionChanged(tx, counted);\n if (this.#raw.announcedAccess === undefined) this.#raw.announcedAccess = oldValue;\n tx.markFlagsDirty(this);\n });\n }\n\n /**\n * The access of this element after the containers above it are applied. A container that sends nothing or `null`\n * sends none of its members, so below a `'disabled'` or `'disabled-null'` container every element is\n * `'disabled'`; below a `'readonly'` one an `'editable'` element is `'readonly'`. Otherwise it is the element's\n * own access.\n *\n * It determines whether the element's validators run: an element whose effective access is `'disabled'` is not\n * sent, so its validators produce no result and it has none of their errors. Otherwise they run over what the\n * element sends: its value, or `null`.\n */\n get effectiveAccess(): Access {\n const own = this.access;\n const above = this.parent?.effectiveAccess;\n if (above === 'disabled' || above === 'disabled-null') return 'disabled';\n if (above === 'readonly' && own === 'editable') return 'readonly';\n return own;\n }\n\n /**\n * Whether `effectiveAccess` is `'disabled'`, read from the untracked state. A validator reads it on every run,\n * where nothing renders from the result and a tracked walk up the containers would add a tracked read per level\n * to every write.\n */\n [SentNowhere](): boolean {\n if (this.#raw.access === 'disabled') return true;\n for (let above = this.#raw.parent; above; above = above.#raw.parent) {\n if (above.#raw.access === 'disabled' || above.#raw.access === 'disabled-null') return true;\n }\n return false;\n }\n\n /**\n * True if `access` is `'editable'`: the element accepts input. It reads only `access` and concerns input, not\n * data: a `'readonly'` element is not enabled and still sends its value. What an element sends is read from\n * `access`.\n */\n get enabled(): boolean {\n return this.access === 'editable';\n }\n\n /**\n * True if `effectiveAccess` is `'editable'`: this element and every container above it accept input. A rendering\n * layer reads this instead of walking the parent chain; the inputs of members inside a container that is not\n * editable read false here.\n */\n get effectiveEnabled(): boolean {\n return this.effectiveAccess === 'editable';\n }\n\n /** The effective access of this element and of every element below it, read before a change that may move it. */\n private effectiveAccessFromHere(): Map<FieldBase, Access> {\n const seen = this.effectiveAccessBelow();\n seen.set(this, this.effectiveAccess);\n return seen;\n }\n\n /** The effective access of every element below this one, read before a change that may move it. */\n private effectiveAccessBelow(): Map<FieldBase, Access> {\n const seen = new Map<FieldBase, Access>();\n const visit = (element: FieldBase) => {\n element.members.forEach((member) => {\n seen.set(member, member.effectiveAccess);\n visit(member);\n });\n };\n visit(this);\n return seen;\n }\n\n /**\n * Runs the validators again on every element whose effective access changed what it sends since `before` was\n * read: an element that is no longer sent loses their errors, and one that is now sent is validated over what it\n * sends.\n */\n private revalidateWhereChanged(before: Map<FieldBase, Access>): void {\n before.forEach((access, element) => {\n if (sendsAs(element.effectiveAccess) !== sendsAs(access)) element.rerunEagerActions();\n });\n }\n\n /**\n * What this element sends to its container's `value` or `fullValue`: its own value, `null`, or nothing. Every\n * container composes its values through this method.\n *\n * `fullValue` contains everything the form holds, so every element sends its value there. `value` contains what\n * the form sends, determined by `access`: `'disabled'` omits the element and `'disabled-null'` sends `null`,\n * whatever a container holds below it.\n */\n protected serializesAs(purpose: 'value' | 'fullValue'): 'value' | 'null' | 'omit' {\n if (purpose === 'fullValue') return 'value';\n switch (this.access) {\n case 'disabled':\n return 'omit';\n case 'disabled-null':\n return 'null';\n default:\n return 'value';\n }\n }\n\n /** What `child` sends to this container; a protected-access bridge like `childComposesValue`. */\n protected childSerializesAs(child: FieldBase, purpose: 'value' | 'fullValue'): 'value' | 'null' | 'omit' {\n return child.serializesAs(purpose);\n }\n\n /**\n * What this element sends to its container's `value`: its value where its access sends it, `null` for\n * `'disabled-null'`, and `undefined` for `'disabled'`, whose key or row is omitted. The element's validators run\n * over it, and `ContributionChangedAction` reports it.\n */\n get contribution(): unknown {\n switch (this.serializesAs('value')) {\n case 'omit':\n return undefined;\n case 'null':\n return null;\n default:\n return this.value;\n }\n }\n\n /**\n * The value `ValueChangedAction` reports for this element: its value. A container holds every member's value\n * whatever the member sends, so on a container it is its `fullValue`.\n */\n protected get holding(): any {\n return this.value;\n }\n\n /**\n * Whether the container holding this element counts its validity: true for every element that sends something,\n * `null` included. A `'disabled'` element sends nothing, so it is not counted, neither for an error written by\n * hand nor for one from a validator (validators do not run on it).\n */\n private get countsInContainer(): boolean {\n return this.serializesAs('value') !== 'omit';\n }\n\n /**\n * Processes a change of what this element sends: the element is enrolled so the commit compares its contribution\n * and recomputes its validity, the container's value is rebuilt, and an invalid element is added to or removed\n * from the container's invalid count as it starts or stops being counted.\n */\n private contributionChanged(tx: Transaction, wasCounted: boolean): void {\n tx.markValueChanged(this, false);\n tx.markValidityDirty(this);\n this.bumpValueVersion();\n const holder = this.container;\n if (!holder) return;\n const counted = this.countsInContainer;\n if (counted !== wasCounted && !this.#raw.valid) {\n tx.touch(holder);\n // for the invalid count, an invalid element that stops being counted is one that became valid, and vice versa\n holder.childValidityChanged(!counted);\n tx.markValidityDirty(holder);\n }\n this.parent!.notifyValueChanged();\n }\n\n /**\n * True for an element whose value is composed of its members' values. The commit builds such a value only if\n * something receives it, compares it by content (not identity), and runs the element's own validators with the\n * announcement: a container's validators read the composed value, which exists only after the members have been\n * written. A leaf's validators run at the write, so its announcement runs no eager pass.\n */\n protected get composesValue(): boolean {\n return false;\n }\n\n /**\n * Whether `child` composes its value from its own members. A container uses it to distinguish a nested container\n * from a leaf without knowing the child's class, as with `resetChild`.\n */\n protected childComposesValue(child: FieldBase): boolean {\n return child.composesValue;\n }\n\n /**\n * Announces what this element holds and what it sends at the end of the transaction. Each pair is (now, at the\n * last announcement), so a value that went A -> B -> A within the transaction is not announced. Events that\n * describe an operation (an item added, an item removed) are emitted first, in the order the operations happened.\n *\n * A container's validators read what it sends, which is composed here, so they run first, if it changed; a\n * leaf's ran at the write. `ValueChangedAction` reports what the element holds, and `ContributionChangedAction`\n * what it sends to its container.\n */\n protected [TxAnnounceValue](tx: Transaction, dirty: boolean, force: boolean, structural?: TxStructuralEvent[]): void {\n structural?.forEach((event) => this.boundActions?.trigger(event.actionClass, this, event.item, event.index));\n if (!dirty) return;\n const actions = this.boundActions;\n const composes = this.composesValue;\n const same = (a: unknown, b: unknown) => (composes ? isEqual(a, b) : a === b);\n\n // a container composes what it sends only where its validators read it\n if (composes && actions?.hasEager) {\n const sent = this.contribution;\n const validated = this.#raw.validatedValue;\n if (force || !isEqual(sent, validated)) {\n tx.touch(this);\n this.#raw.validatedValue = sent;\n actions.triggerEager(this, sent, validated);\n }\n }\n\n // what a container holds is composed only if something receives it; a leaf's is its value, with no composition.\n // The announced value is recorded before the event: a change a handler makes is a change of its own, compared\n // against this announcement\n if (!composes || actions?.willTrigger(ValueChangedActionClassIdentifier)) {\n const held = this.holding;\n const announced = this.#raw.announcedValue;\n if (force || !same(held, announced)) {\n tx.touch(this);\n this.#raw.announcedValue = held;\n actions?.trigger(ValueChangedAction, this, held, announced);\n }\n }\n\n if (actions?.willTrigger(ContributionChangedActionClassIdentifier)) {\n const contribution = this.contribution;\n const announced = this.#raw.announcedContribution;\n if (!same(contribution, announced)) {\n tx.touch(this);\n this.#raw.announcedContribution = contribution;\n actions.trigger(ContributionChangedAction, this, contribution, announced);\n }\n }\n }\n\n /**\n * Records what this element holds and sends as last announced, so the following commit announces no change of\n * either. A construction calls it over its final state, as does `rebind()`.\n */\n protected recordAnnounced(): void {\n // a baseline is composed only if something receives the announcement it is compared for; a registration that\n // adds a listener later re-reads it (refreshPreviousValue), and a leaf's value needs no composition\n const actions = this.boundActions;\n if (!this.composesValue || actions?.willTrigger(ValueChangedActionClassIdentifier)) {\n this.#raw.announcedValue = this.holding;\n }\n if (actions?.willTrigger(ContributionChangedActionClassIdentifier))\n this.#raw.announcedContribution = this.contribution;\n if (this.composesValue && actions?.hasEager) this.#raw.validatedValue = this.contribution;\n // errors given as a construction parameter are assigned before the value is in place: the value they describe\n // is the one the element ends with, recorded at the next read of its errors\n this.#raw.errorsBaseline = NoErrorsBaseline;\n }\n\n /**\n * Computes the validity this element ends the transaction with and announces a change of it. The container is\n * updated first, so a handler reads an invalid count that already includes this element, and the container is\n * enrolled in the same transaction: its validity depends on its members', so a member whose validity changes\n * without a value change (an asynchronous validator, an error written by hand) makes the container recompute its\n * own. The transaction settles the deepest element first, so a container is settled after its members.\n */\n /**\n * Announces the net change of access, enabled and visibility over the transaction: `AccessChangedAction` and\n * `EnabledChangedAction` where the access differs from the one before the transaction's first write of it, and\n * `VisibilityChangedAction` likewise. A value that went back to where it started announces nothing.\n */\n protected [TxAnnounceFlags](): void {\n const raw = this.#raw;\n const previousAccess = raw.announcedAccess;\n if (previousAccess !== undefined) {\n raw.announcedAccess = undefined;\n const access = raw.access;\n if (access !== previousAccess) {\n this.boundActions?.trigger(AccessChangedAction, this, access, previousAccess);\n const enabled = access === 'editable';\n const wasEnabled = previousAccess === 'editable';\n if (enabled !== wasEnabled) this.boundActions?.trigger(EnabledChangedAction, this, enabled, wasEnabled);\n }\n }\n const previousVisibility = raw.announcedVisibility;\n if (previousVisibility !== undefined) {\n raw.announcedVisibility = undefined;\n if (raw.visibility !== previousVisibility) {\n this.boundActions?.trigger(VisibilityChangedAction, this, raw.visibility, previousVisibility);\n }\n }\n }\n\n protected [TxSettleValidity](tx: Transaction): void {\n const oldValid = this.#raw.valid;\n const newValid = this.countedValid;\n if (newValid === oldValid) return;\n tx.touch(this);\n this.#raw.valid = newValid;\n // the validity goes to the container that holds this element; release clears the link, so a removed row does\n // not change any invalid count\n const holder = this.container;\n // an element that sends nothing is not in its container's invalid count, so its validity changes nothing above\n if (holder && this.countsInContainer) {\n tx.touch(holder);\n holder.childValidityChanged(newValid);\n tx.markValidityDirty(holder);\n }\n this.boundActions?.trigger(ValidChangedAction, this, newValid, oldValid);\n }\n\n validate(revalidate: boolean = false) {\n transactional((tx) => {\n if (revalidate) this.boundActions?.triggerEager(this, this.contribution, this.contribution);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * True while no error of the element counts toward validity: every error of origin `'validator'` counts, and an\n * error of another origin counts where its rule's `validEffect` is true (see `ErrorPolicy`).\n */\n get valid() {\n // reads the slot directly: the errors getter adds the element to an open transaction, and reading validity\n // changes nothing a rollback has to restore\n return this.ownErrorsValid(this.#state.errors);\n }\n\n get fullValue(): T {\n return this.value;\n }\n\n get isChanged(): boolean {\n return !isEqual(this.value, this.originalValue);\n }\n\n /**\n * Sets up a new element as a binding of `source`: it records the declaration, copies the extended properties of\n * `source`, uses the actions `source` has, and runs the eager ones over the value it was built with. Extended\n * properties in `overrides` are written over the copied ones before the eager pass, so an action that reads one\n * sees the binding's final value. The actions are the same instances `source` holds, and each is bound to this\n * element (`boundToBinding`), so an action serving several bindings has a reference to each of them.\n */\n protected boundFrom(source: FieldBase<any, X>, newValue: any, oldValue: any, overrides?: object): void {\n if (overrides) refuseEnabled(overrides);\n this.#raw.declaration = source.declaration;\n const extended: Partial<X> = { ...source.extra, ...(overrides && this.extendedOf(overrides)) };\n if (!isEmpty(extended)) this.setExtendedValues(extended);\n const declaration = this.declaration;\n declaration.noteBinding(this);\n // the binding uses the declaration's map itself, not a copy, so a rule registered on the declaration after this\n // binding was made reaches it too. A declaration with nothing registered has no map; the map it creates later\n // is assigned to this element then\n const actions = declaration._actions;\n if (!actions) return;\n this._actions = actions;\n actions.bindTo(this);\n // the construction recorded no baseline for listeners, because the element had none at that point\n this.recordAnnounced();\n actions.triggerEager(this, newValue, oldValue);\n }\n\n /**\n * Registers the actions a constructor received in its parameters, without the eager trigger: a constructor ends\n * with a single this.actions.triggerEager(...) over the finished value. With the trigger, an eager action would\n * also run once per registration, over a partially built field.\n */\n protected registerInitialActions(actions: FieldActionBase[]): void {\n actions.forEach((action) => {\n this.actions.register(action);\n action.boundToBinding(this);\n });\n }\n\n registerAction(action: FieldActionBase): this {\n transactional((tx) => {\n // the baseline of a change the transaction has yet to announce is kept: the element is already enrolled to\n // announce that change, and moving the baseline to the current value would cancel the announcement\n if (!tx.willAnnounceValue(this)) this.refreshPreviousValue();\n this.actions.register(action);\n this.registered(tx, action);\n });\n return this;\n }\n\n /**\n * Registers `action` so that `before` wraps it: `before` calls it through the `supr` argument. This adds an\n * action to an existing chain inside a handler that is already registered, which registration order alone cannot\n * do. `before` must be registered on this element under the same identifier.\n */\n registerActionBefore(action: FieldActionBase, before: FieldActionBase): this {\n transactional((tx) => {\n if (!tx.willAnnounceValue(this)) this.refreshPreviousValue();\n this.actions.register(action, before);\n this.registered(tx, action);\n });\n return this;\n }\n\n /**\n * Unregisters `action` from this element and returns whether it was registered. The registration is shared with\n * the element's declaration and every binding made from it, so the action is removed from all of them; elements\n * of other declarations that the same instance is registered on keep it. A validator removes the errors it put on\n * the elements it is removed from, so their validity reflects only the remaining validators.\n */\n unregisterAction(action: FieldActionBase): boolean {\n let dropped = false;\n transactional((tx) => {\n const actions = this.boundActions;\n if (!actions) return;\n dropped = actions.unregister(action);\n if (!dropped) return;\n tx.touch(this);\n // a run still in flight may belong to the removed validator, and its result must not be applied\n if (action instanceof Validator) this.#state.validationEpoch++;\n // the action served the declaration and every binding made from it, so it is released from all of them\n const elements = this.boundElements;\n tx.whenRolledBack(() => {\n actions.register(action);\n elements.forEach((element) => action.boundToBinding(element));\n });\n elements.forEach((element) => action.unregisterFrom(element));\n });\n return dropped;\n }\n\n /**\n * Binds a newly registered `action` to the existing bindings and registers an undo for a rollback. The\n * registration is not in the state slots the snapshot covers, so it registers its own undo.\n */\n private registered(tx: Transaction, action: FieldActionBase): void {\n // the action is registered on the declaration, so it applies to every binding made from it, existing and future.\n // An eager action runs over each existing binding's value immediately; its whole handler chain runs, because\n // actions registered before it may wrap it and its own `supr` calls them.\n const elements = this.boundElements;\n elements.forEach((element) => {\n action.boundToBinding(element);\n if (action.eager) {\n // records the value the action runs over as the one a container's validators last ran over\n element.#raw.validatedValue = element.contribution;\n this.actions.triggerEagerFor(action.classIdentifier, element, element.contribution, element.originalValue);\n }\n });\n tx.whenRolledBack(() => {\n if (this.boundActions?.unregister(action)) elements.forEach((element) => action.unregisterFrom(element));\n });\n }\n\n triggerAction<T2 extends FieldActionBase>(\n actionClass: (abstract new (...args: any[]) => T2) & { classIdentifier: symbol },\n ...params: any[]\n ): any {\n // an element with no map has nothing registered, and ActionsMap.trigger returns null in that case\n const actions = this.boundActions;\n return actions ? actions.trigger(actionClass, this, ...params) : null;\n }\n\n /**\n * Generation counter of the validators attached to this field. A Validator reads it when a run starts and drops\n * a result whose epoch no longer matches, so a validation still in flight when clearValidators() is called\n * cannot push an error onto a field that no longer has the validator that produced it.\n */\n get [ValidationEpoch](): number {\n return this.#state.validationEpoch;\n }\n\n clearValidators(): void {\n transactional((tx) => {\n tx.touch(this);\n this.#state.validationEpoch++;\n const actions = this.boundActions;\n if (actions) {\n // each release names the element, because the same instance stays registered on elements of other\n // declarations\n const elements = this.boundElements;\n actions.validators.forEach((validator) => {\n actions.unregister(validator);\n tx.whenRolledBack(() => {\n actions.register(validator);\n elements.forEach((element) => validator.boundToBinding(element));\n });\n // each validator removes the errors it put on every element it validated\n elements.forEach((element) => validator.unregisterFrom(element));\n });\n }\n this.errors = [];\n // the errors are cleared before the recomputation, so the commit computes validity over the cleared state and\n // the change follows the usual path: ValidChangedAction fires and the parent recomputes its validity\n this.validate();\n });\n }\n}\n\ndeclare module '@vue/reactivity' {\n /**\n * An element carries __v_skip, so ref() and reactive() hold it as it is. Listing it here makes their types do the\n * same: `ref([action])` is a `Ref<Action[]>` and `reactive({ form }).form` is the form's own type, where Vue's\n * unwrapping would otherwise produce a structural copy of the class without its non-public members.\n */\n export interface RefUnwrapBailTypes {\n dynamicformsElement: FieldBase<any, any>;\n }\n}\n","import { isString } from 'lodash-es';\nimport { unref } from 'vue';\n\nimport { FieldBase } from '../../field-base';\nimport { resolveInScope } from '../../resolve';\n\nimport Operator from './operator';\n\n// An operand is a nested Statement, an element whose current value is compared, or a literal of any type. The\n// union with `any` is `any` for the type checker, so the alias documents intent and does not constrain callers;\n// the constructor rejects undefined and a function, which are not operands.\nexport type OperandType = any | Statement | FieldBase;\n\nfunction XOR(value1: boolean, value2: boolean): boolean {\n return value1 ? !value2 : value2;\n}\n\nexport class Statement {\n private readonly operand1: OperandType;\n\n private readonly operator: Operator;\n\n private readonly operand2: OperandType;\n\n /**\n * An operand is a nested `Statement`, a `FieldBase` whose value is compared, or a literal. `undefined` and a\n * function are not operands: they result from a misspelled field name and from an accessor passed without being\n * called, and a statement built from one would compare nothing and never fire. The error message includes the\n * operand's position.\n */\n private static validateOperand(operand: OperandType, position: 1 | 2): void {\n if (operand === undefined) {\n throw new TypeError(\n `Statement operand ${position} is undefined: an operand is a field, a nested statement or a literal, ` +\n 'and a name resolving to nothing is none of them. Compare against null to test for an unset value.',\n );\n }\n if (typeof operand === 'function') {\n throw new TypeError(\n `Statement operand ${position} is a function: an operand is a field, a nested statement or a literal, ` +\n \"and a function is none of them. An accessor states the field it answers with: group.field('name').\",\n );\n }\n }\n\n /**\n * `NOT` reads one operand, so it takes one. Every other operator compares two and takes both, as does an operator\n * held in a variable: `Operator.fromString()` returns the type, not the constant, so the compiler cannot\n * determine which of the two forms applies.\n *\n * @throws TypeError if an operand the statement reads is undefined or a function.\n */\n constructor(operand1: OperandType, operator: Operator.NOT);\n constructor(operand1: OperandType, operator: Operator, operand2: OperandType);\n constructor(operand1: OperandType, operator: Operator, operand2?: OperandType) {\n Statement.validateOperand(operand1, 1);\n // NOT reads only operand1, so the second position is neither compared nor validated\n if (operator !== Operator.NOT) Statement.validateOperand(operand2, 2);\n\n this.operand1 = operand1;\n this.operator = operator;\n this.operand2 = operand2;\n }\n\n /**\n * Returns the value of an operand. A field operand refers to the corresponding element of the record the\n * statement is evaluated in: the same statement over a `List` reads row 3's element when row 3 is the record, and\n * an element outside the statement's records (a form field above the list) is read directly. If the record does\n * not hold the element yet (a partially built row), the value is undefined.\n */\n private static valueOf(operand: OperandType, scope?: FieldBase) {\n if (operand instanceof Statement) return operand.evaluate(scope);\n if (operand instanceof FieldBase) {\n const field = scope ? resolveInScope(operand, scope) : operand;\n return field ? unref(field.value) : undefined;\n }\n return operand; // any\n }\n\n get operand1Value() {\n return Statement.valueOf(this.operand1);\n }\n\n get operand2Value() {\n return Statement.valueOf(this.operand2);\n }\n\n /**\n * The result of the statement, over the record `scope` belongs to if given, and over the elements the statement\n * was built from otherwise.\n */\n evaluate(scope?: FieldBase): boolean {\n const operand1 = Statement.valueOf(this.operand1, scope);\n const operand2 = Statement.valueOf(this.operand2, scope);\n\n switch (this.operator) {\n // logical operators\n // `&&` and `||` evaluate to one of their operands, which can be of any type. The coercion ensures evaluate()\n // returns a boolean, as its signature declares: otherwise `0` or `''` would be returned, and a consumer\n // comparing results with !== would see a change where the logical value is the same.\n case Operator.AND:\n return Boolean(operand1 && operand2);\n case Operator.OR:\n return Boolean(operand1 || operand2);\n case Operator.NAND:\n return !(operand1 && operand2);\n case Operator.NOR:\n return !(operand1 || operand2);\n case Operator.XOR:\n return XOR(Boolean(operand1), Boolean(operand2));\n case Operator.NOT:\n return !operand1;\n\n // comparison operators\n case Operator.EQUALS:\n return operand1 == operand2;\n case Operator.NOT_EQUALS:\n return operand1 != operand2;\n case Operator.LT:\n return operand1 < operand2;\n case Operator.LE:\n return operand1 <= operand2;\n case Operator.GE:\n return operand1 >= operand2;\n case Operator.GT:\n return operand1 > operand2;\n case Operator.IN:\n // `includes` is called on an operand of any type, so its return value is not necessarily a boolean; a\n // missing or non-callable `includes` yields undefined and therefore false. NOT_IN negates the same\n // expression, so for a right operand without `includes`, IN is false and NOT_IN is true.\n return Boolean(operand2?.includes?.(operand1));\n case Operator.NOT_IN:\n return !operand2?.includes?.(operand1);\n case Operator.INCLUDES:\n return isString(operand1) && isString(operand2) && operand1.indexOf(operand2) >= 0;\n case Operator.NOT_INCLUDES:\n return !(isString(operand1) && isString(operand2) && operand1.indexOf(operand2) >= 0);\n\n default:\n throw new Error(`Operator not implemented ${this.operator}`);\n }\n }\n\n /**\n * Recursively collects all fields used in this statement and its nested statements\n * @returns A set of all fields used in this statement\n */\n collectFields(): Set<FieldBase> {\n const fields = new Set<FieldBase>();\n\n function processOperand(op: OperandType) {\n if (op instanceof FieldBase) {\n fields.add(op);\n } else if (op instanceof Statement) {\n // For nested statements, merge their fields with our collection\n const nestedFields = op.collectFields();\n nestedFields.forEach((field) => fields.add(field));\n }\n }\n processOperand(this.operand1);\n processOperand(this.operand2);\n\n return fields;\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ExecuteActionClassIdentifier = Symbol('ExecuteAction');\n\nexport class ExecuteAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, params: any) => any) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ExecuteActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, params: any): any {\n return super.execute(field, supr, params);\n }\n\n /**\n * Whether this handler can run now on `action`. `Action.executable` is false while any of the action's\n * `ExecuteAction` handlers returns false. The base class returns true; a subclass overrides it with a condition\n * that a template can bind to, such as the validity of the form a `SubmitAction` sends. The read is reactive where\n * the condition reads reactive state.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n canExecute(action: FieldBase): boolean {\n return true;\n }\n}\n","import { watch } from 'vue';\n\nimport { RemoveErrorsOnSubmit } from '../element-state';\nimport type { FieldBase } from '../field-base';\nimport { AbortEventHandlingException } from '../field.interface';\n\nimport { ExecuteAction } from './execute-action';\n\n/**\n * The element a `SubmitAction` or a `RejectAction` works on: an element, or a callback that returns it for the\n * action the handler is registered on.\n */\nexport type CommandTarget = FieldBase | ((action: FieldBase) => FieldBase | null | undefined);\n\n/** An `ExecuteAction` that works on a target element; `Container.confirm()` and `reject()` find it by its target. */\nexport abstract class TargetedExecuteAction extends ExecuteAction {\n protected abstract readonly target: CommandTarget;\n\n /** The element this handler works on when it runs on `action`, or undefined where the callback returns none. */\n targetFor(action: FieldBase): FieldBase | undefined {\n const target = this.target;\n return typeof target === 'function' ? (target(action) ?? undefined) : target;\n }\n}\n\n/** How a `SubmitAction` treats its target. */\nexport interface SubmitOptions {\n /**\n * Whether a result other than `undefined` is written back with `target.rebind(result)`, which makes it the new\n * baseline: `isChanged` is false, `touched` is false and the errors are revalidated. Defaults to true.\n */\n rebind?: boolean;\n /**\n * Whether an `'editable'` target is `'readonly'` while the handler runs, so no input reaches it during the\n * submit. Defaults to true.\n */\n lock?: boolean;\n}\n\n/** What `execute()` of an action with a `SubmitAction` resolves with after a successful submit. */\nexport interface SubmitResult<R = any> {\n /** The action that ran the submit. */\n action: FieldBase;\n /** The value passed to the handler: the target's `value`. */\n sent: unknown;\n /** The value the handler returned. */\n received: R;\n}\n\n/** Resolves when `element.validating` is false. */\nfunction validated(element: FieldBase): Promise<void> {\n if (!element.validating) return Promise.resolve();\n return new Promise((resolve) => {\n const stop = watch(\n () => element.validating,\n (validating) => {\n if (validating) return;\n stop();\n resolve();\n },\n { flush: 'sync' },\n );\n });\n}\n\n/**\n * The base of the exceptions a `TargetedExecuteAction` ends with when its command did not complete. `execute()`\n * resolves with it. A `SubmitAction` ends with a `SubmitFailedException` or a `SubmitRefusedException`, so the\n * resolved value of a submit is `SubmitResult | CommandException`.\n */\nexport abstract class CommandException extends AbortEventHandlingException {}\n\n/** The `CommandException` a `SubmitAction` ends with when its handler throws or rejects; `cause` is what it threw. */\nexport class SubmitFailedException extends CommandException {\n constructor(cause: unknown) {\n super('the submit handler failed', { cause });\n }\n}\n\n/** Why a `SubmitAction` refused to submit: the target is invalid, or a submit of the same action is running. */\nexport type SubmitRefusalReason = 'invalid' | 'running';\n\n/**\n * The `CommandException` a `SubmitAction` ends with when it refuses to submit and does not call the handler;\n * `reason` states why.\n */\nexport class SubmitRefusedException extends CommandException {\n constructor(public readonly reason: SubmitRefusalReason) {\n super(reason === 'invalid' ? 'the submitted element is invalid' : 'a submit of this action is already running');\n }\n}\n\n/**\n * Sends the value of `target` to `handler`. On `execute()` it:\n *\n * 1. waits until `target.validating` is false, so a validation started in the same event is finished. It does not\n * await `target.settled()`: the action is `busy` while it runs, so the target is `pending` until it returns;\n * 2. where `target.valid` is false, ends with a `SubmitRefusedException` with `reason` `'invalid'`, which\n * `execute()` resolves with;\n * 3. removes, from the target and every element below it, the errors whose rule removes them on `'submit'` (see\n * `ErrorPolicy`);\n * 4. where the target's `access` is `'editable'` and `lock` is not false, sets it to `'readonly'`;\n * 5. calls `handler(target.value, target)` and awaits it;\n * 6. where the result is not `undefined` and `rebind` is not false, calls `target.rebind(result)`;\n * 7. sets the target's `access` back to `'editable'` where step 4 set it and it is still `'readonly'`, whether the\n * handler succeeded or failed;\n * 8. calls the next handler in the chain and returns a `SubmitResult`: the action, the value sent and the value\n * `handler` returned.\n *\n * A second `execute()` while a submit of the same action is running is refused with a `SubmitRefusedException`\n * with `reason` `'running'`.\n *\n * A `handler` that throws or rejects ends the submit with a `SubmitFailedException` whose `cause` is the error;\n * `execute()` resolves with it and the target is not changed. Mapping a server's field errors to the fields is the\n * handler's: it writes them to `field.errors` before it throws.\n *\n * The resolved value is `SubmitResult<R> | CommandException`. `execute()` is typed `Promise<any>`, because the\n * chain may hold other handlers; the caller states the type where it awaits the result.\n *\n * `'readonly'` sends and validates the target as `'editable'` does, so its `value`, `valid` and `isChanged` do not\n * change and no validator runs because of the lock; the members inherit it through `effectiveAccess`, so every\n * input below the target is not enabled while the handler runs. The rebind in step 6 replaces the target's value\n * with the result, so a change written to the target by code while the handler runs is lost and `isChanged` is\n * false afterwards. `busy` and `pending` report the running submit.\n *\n * `canExecute()` is true while the target is valid and not `pending`, so `Action.executable` disables a submit\n * button while the form is invalid or a validation is running.\n */\nexport class SubmitAction<R = any> extends TargetedExecuteAction {\n protected readonly target: CommandTarget;\n\n constructor(\n target: CommandTarget,\n handler: (value: any, target: FieldBase) => R | Promise<R>,\n options: SubmitOptions = {},\n ) {\n super(async (action, supr, params): Promise<SubmitResult<R>> => {\n const run = this.state(action, () => ({ running: false }));\n if (run.running) throw new SubmitRefusedException('running');\n run.running = true;\n try {\n const element = this.targetFor(action);\n if (!element) throw new Error('SubmitAction: the target callback returned no element');\n await validated(element);\n if (!element.valid) throw new SubmitRefusedException('invalid');\n element[RemoveErrorsOnSubmit]();\n const sent = element.value;\n let received: R;\n const locking = options.lock !== false && element.access === 'editable';\n if (locking) element.access = 'readonly';\n // an AccessChangingAction may refuse the lock, and an access written while the handler runs is kept\n const locked = locking && element.access === 'readonly';\n try {\n try {\n received = await handler(sent, element);\n } catch (error) {\n throw new SubmitFailedException(error);\n }\n if (received !== undefined && options.rebind !== false) element.rebind(received);\n } finally {\n if (locked && element.access === 'readonly') element.access = 'editable';\n }\n await supr(action, params);\n return { action, sent, received };\n } finally {\n run.running = false;\n }\n });\n this.target = target;\n }\n\n canExecute(action: FieldBase): boolean {\n const element = this.targetFor(action);\n return element !== undefined && element.valid && !element.pending;\n }\n}\n","import type { FieldBase } from '../field-base';\n\nimport { type CommandTarget, TargetedExecuteAction } from './submit-action';\n\n/**\n * Puts `target` back to its baseline: on `execute()` it calls `target.rebind(target.originalValue)`, which sets the\n * value to `originalValue`, resets `touched` and revalidates, then calls the next handler in the chain and returns\n * its result.\n *\n * `canExecute()` is true while the target exists, whatever its validity.\n */\nexport class RejectAction extends TargetedExecuteAction {\n protected readonly target: CommandTarget;\n\n constructor(target: CommandTarget) {\n super((action, supr, params) => {\n const element = this.targetFor(action);\n if (!element) throw new Error('RejectAction: the target callback returned no element');\n element.rebind(element.originalValue);\n return supr(action, params);\n });\n this.target = target;\n }\n\n canExecute(action: FieldBase): boolean {\n return this.targetFor(action) !== undefined;\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ListItemAddedActionClassIdentifier = Symbol('ListItemAddedAction');\n\nexport class ListItemAddedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, item: any, index: number) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ListItemAddedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, item: any, index: number): void {\n return super.execute(field, supr, item, index);\n }\n}\n","import FieldActionBase from './field-action-base';\n\nimport type { FieldBase } from '@/field-base';\nimport { FieldActionExecute } from '@/field.interface';\n\nconst ListItemRemovedActionClassIdentifier = Symbol('ListItemRemovedAction');\n\nexport class ListItemRemovedAction extends FieldActionBase {\n constructor(executorFn: (field: FieldBase, supr: FieldActionExecute, item: any, index: number) => void) {\n super(executorFn);\n }\n\n static get classIdentifier() {\n return ListItemRemovedActionClassIdentifier;\n }\n\n execute(field: FieldBase, supr: FieldActionExecute, item: any, index: number): void {\n return super.execute(field, supr, item, index);\n }\n}\n","import { toRaw } from 'vue';\n\nimport { type FieldSlots, fieldSlots } from './element-state';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\nimport { asBinding, ChangeInPlace, pipeValue } from './plugins';\nimport { transactional } from './transaction';\n\nclass Field<T = any, X extends object = Extras> extends FieldBase<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Field';\n }\n\n protected get state(): FieldSlots<T> {\n return super.state as FieldSlots<T>;\n }\n\n protected get raw(): FieldSlots<T> {\n return super.raw as FieldSlots<T>;\n }\n\n /** the value slot itself, without the notifications the value setter sends on a write */\n protected get _value(): T {\n return this.state.value;\n }\n\n protected set _value(newValue: T) {\n this.state.value = pipeValue(this, newValue);\n }\n\n constructor(params?: IFieldParams<T, X>) {\n super(fieldSlots<T>());\n this.init(params);\n }\n\n /**\n * Applies the constructor parameters. A subclass that needs different parameter handling overrides this method\n * instead of redeclaring the constructor, as Action does.\n *\n * It is called from this constructor, so it runs before a subclass's class field initializers, which run after\n * super() returns. An override can therefore use only its parameters: members the subclass initializes are\n * undefined inside it, and a value it writes to such a member is overwritten when the initializer runs.\n */\n protected init(params?: IFieldParams<T, X>) {\n transactional(() => {\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // actions are registered before the remaining parameters are assigned, so a *Changing* action supplied here\n // also applies to those assignments\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n // a missing value defaults to originalValue; an explicit null is a value and is kept\n this._value = paramValue !== undefined ? paramValue : this.originalValue;\n }\n this.constructed(params);\n // without a supplied baseline, the baseline is the value the construction ends with, which is the value the\n // hook above leaves\n if (this.originalValue === undefined) this.originalValue = this._value;\n // the value a construction ends with is the field's initial state, not a change, so it is recorded as\n // announced and the following commit announces nothing for it\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n get value() {\n // the version is read so that a reader re-runs on a change a plugin makes inside the value, which leaves the\n // slot holding the same object\n void this.valueVersion;\n return this._value;\n }\n\n set value(newValue: T) {\n const oldValue = this._value;\n // the write is applied whatever the access: access determines what the field sends and whether an input\n // accepts typing, and a record loaded into the form reaches every member\n // NaN is not === to itself, so a write of NaN over NaN is compared as the same value, as Array.includes does\n if (oldValue === newValue || (Number.isNaN(oldValue) && Number.isNaN(newValue))) return;\n transactional((tx) => {\n tx.touch(this);\n this._value = newValue;\n this.bumpValueVersion();\n // the validators run here, not at the announcement, because the commit announces their result. They read\n // what the field sends, which a write changes only if the field sends its value: a field that sends nothing\n // or null sends the same after the write\n if (this.serializesAs('value') === 'value') this.boundActions?.triggerEager(this, this._value, oldValue);\n // the handlers receive the change when the transaction closes, with the field's final value\n this.propagateValueChanged();\n });\n }\n\n /** The implementation of `PluginContext.changeInPlace`. */\n protected [ChangeInPlace](write: () => void, undo: () => void, copy: () => T): void {\n transactional((tx) => {\n tx.touch(this);\n const raw = this.raw;\n // after an announcement the field's last announced value is the object it holds; the first write into it\n // records a copy, so the commit reports what the value was before\n if (toRaw(raw.announcedValue) === toRaw(raw.value)) raw.announcedValue = copy();\n write();\n tx.whenRolledBack(undo);\n this.bumpValueVersion();\n if (this.serializesAs('value') === 'value') {\n this.boundActions?.triggerEager(this, this._value, raw.announcedValue);\n }\n this.propagateValueChanged(true);\n });\n }\n\n get touched(): boolean {\n return this.state.touched;\n }\n\n /**\n * Whether the user has interacted with the field. A rendering layer writes `true` when the user leaves the input;\n * the write removes the errors whose rule removes them on `'edit'` from the field and the containers above it,\n * where their values changed since those errors were written (see `ErrorPolicy`).\n */\n set touched(touched: boolean) {\n this.touchState();\n this.state.touched = touched;\n if (touched) this.editConcluded();\n }\n\n bind(data?: T, overrides?: IBindParams<T, X>): this {\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (params?: IFieldParams<T, X>) => this;\n const res = asBinding(\n () =>\n new Ctor({\n // undefined data counts as not supplied; an explicit null is supplied and clears\n value: data !== undefined ? data : this.value,\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<T, X>),\n );\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n return res;\n }\n}\n\nexport { Field };\n\nexport type NullableField<T = any> = Field<T> | null;\n","import { ref, type Ref } from 'vue';\n\nimport { ExecuteAction } from './actions';\nimport { ExecuteHandlers } from './element-state';\nimport { Field } from './field';\nimport { type Extras, IFieldParams } from './field.interface';\nimport { SentNowhere, transactional } from './transaction';\n\n/**\n * The value an `Action` holds. Both members are `unknown` because `Action` defines the concept and a UI library\n * defines what it renders: a subclass declares its value type with `label` and `icon` in the shape it renders them\n * (a string, a markdown string, a per-breakpoint object), and the accessors below return that type, because they\n * read it from `T`.\n *\n * For an `Action` built without a type argument, both members are `unknown` and the reader casts them. An\n * application that renders actions uses the subclass its UI library provides.\n */\nexport interface ActionValue {\n label?: unknown;\n icon?: unknown;\n /** The action a container's `confirm()` executes: the one a confirm gesture, such as Enter, triggers. */\n defaultConfirm?: boolean;\n /** The action a container's `reject()` executes: the one a reject gesture, such as Escape, triggers. */\n defaultReject?: boolean;\n}\n\n/**\n * The number of unsettled executions of an action, held outside the action and created on first access. An action\n * that is never executed and whose `busy` is never read has no counter; the others have a Vue ref, so a button\n * that reads `busy` re-renders when the count leaves zero and when it returns to zero.\n */\nconst busyCounters = new WeakMap<object, Ref<number>>();\n\n/**\n * Returns the value object if any of its members is set, and undefined otherwise. A member holding `null` or\n * `undefined` is not set, so `{}` and the initial pair of `undefined` members return undefined.\n *\n * `T` may be a wider type a subclass declares, so an object with a render style, a name or per-breakpoint options\n * and no label is returned.\n */\nfunction stated<T extends ActionValue>(val: T | undefined): T | undefined {\n if (val == null) return undefined;\n return Object.values(val).some((member) => member != null) ? val : undefined;\n}\n\nexport class Action<\n T extends ActionValue = ActionValue,\n X extends object = Omit<Extras, keyof ActionValue>,\n> extends Field<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Action';\n }\n\n protected init(params?: IFieldParams<T, X>) {\n transactional(() => {\n // an Action's value is always an object, so an action constructed without a value holds an object with two\n // undefined members, not undefined\n this._value = { label: undefined, icon: undefined } as T;\n if (params) {\n const { value: paramValue, originalValue, validators, actions, ...otherParams } = params;\n // actions are registered before the remaining parameters are assigned, so a *Changing* action supplied here\n // also applies to those assignments\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n const val = stated(paramValue);\n const org = stated(originalValue);\n // a supplied value is kept by identity, so a reactive object passed in stays linked to the action; without\n // one, the action holds a copy of the baseline, not the frozen baseline itself\n if (val) this._value = val;\n else if (org) this._value = { ...org };\n // the baseline has exactly the members it was declared with: isChanged is a structural comparison of\n // own-key sets, so the action is unchanged after construction, and so is every container above it\n if (org) this.originalValue = Object.freeze({ ...org }) as T;\n }\n this.constructed(params);\n // without a declared baseline, the baseline is the value the construction ends with (the same object, so\n // both have the same members), which is the value the hook above leaves\n if (this.originalValue === undefined) this.originalValue = this._value;\n // the value a construction ends with is the action's initial state, not a change\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n /**\n * Returns a copy of the value this action holds with one member replaced. A member set to undefined is deleted\n * from the copy: an own key holding undefined is invisible to a reader and to JSON, but lodash isEqual compares\n * own-key sets, so the action would remain changed against a baseline without that key.\n */\n private valueWith<K extends 'label' | 'icon'>(member: K, newValue: T[K]): T {\n const res: ActionValue = { ...this.value };\n if (newValue === undefined) delete res[member];\n else res[member] = newValue;\n return res as T;\n }\n\n get icon(): T['icon'] {\n return this.value.icon;\n }\n\n set icon(newValue: T['icon']) {\n if (this.value.icon === newValue) return;\n this.value = this.valueWith('icon', newValue);\n }\n\n get label(): T['label'] {\n return this.value.label;\n }\n\n /**\n * The two setters pass a new object to the value setter instead of modifying the one the action holds, so each\n * is a regular value change: the handlers fire and isChanged reflects it.\n * The new object is built only if the member differs from the current one: the value setter compares by identity\n * and every copy is a new object, so without this check a write of the current value would announce a change and\n * invalidate the value cache of every container above.\n */\n set label(newValue: T['label']) {\n if (this.value.label === newValue) return;\n this.value = this.valueWith('label', newValue);\n }\n\n /** `value.defaultConfirm`: whether a container's `confirm()` executes this action. */\n get defaultConfirm(): boolean {\n return this.value.defaultConfirm ?? false;\n }\n\n /** `value.defaultReject`: whether a container's `reject()` executes this action. */\n get defaultReject(): boolean {\n return this.value.defaultReject ?? false;\n }\n\n /**\n * An action is a command, not data: it sends nothing to its container's `value` or `fullValue`, so it is not in\n * the payload, does not affect the container's `isChanged`, and is not counted in its validity. Its validators do\n * not run, as on any element that sends nothing.\n */\n protected serializesAs(): 'value' | 'null' | 'omit' {\n return 'omit';\n }\n\n /** An action is sent nowhere, so a validator registered on it reaches no result and adds no error. */\n [SentNowhere](): boolean {\n return true;\n }\n\n /**\n * Whether the action can run now: it accepts input (`effectiveEnabled`), is shown (`visibility` is `'full'`), is\n * not running (`busy` is false), and every `ExecuteAction` handler registered on it returns true from\n * `canExecute()`. Reactive, so a button binds `:disabled=\"!action.executable\"`. A container's `confirm()` and\n * `reject()` execute only an executable action. `execute()` does not check it.\n */\n get executable(): boolean {\n if (!this.effectiveEnabled || this.visibility !== 'full' || this.busy) return false;\n return this[ExecuteHandlers]().every((handler) => handler.canExecute(this));\n }\n\n /** The `ExecuteAction` handlers registered on this action, in registration order. */\n [ExecuteHandlers](): ExecuteAction[] {\n return (this.boundActions?.ofClass(ExecuteAction.classIdentifier) ?? []) as ExecuteAction[];\n }\n\n /** the counter behind `busy`, created on first access */\n private get busyRuns(): Ref<number> {\n let runs = busyCounters.get(this);\n if (!runs) {\n runs = ref(0);\n busyCounters.set(this, runs);\n }\n return runs;\n }\n\n /** true from the call to execute() until the handler it ran has settled, resolved or rejected */\n get busy(): boolean {\n return this.busyRuns.value > 0;\n }\n\n /**\n * Runs the ExecuteAction chain registered on this action and returns the chain's result. `busy` is true for the\n * duration of the run: the chain starts synchronously, and the flag is cleared when its result has settled; a\n * handler that returns a promise keeps it set until that promise settles, and a rejection clears it.\n *\n * The return value is a promise whatever the handler returns, so a handler that throws rejects the promise; this\n * call does not throw. A caller that neither awaits it nor attaches a catch handler leaves the rejection\n * unhandled. An `AbortEventHandlingException` does not reject: the promise resolves with it, for a synchronous\n * and an asynchronous chain alike.\n */\n async execute(params?: any): Promise<any> {\n const runs = this.busyRuns;\n runs.value++;\n try {\n return await this.triggerAction(ExecuteAction, params);\n } finally {\n runs.value--;\n }\n }\n}\n\nexport type NullableAction = Action | null;\n","import { computed, type ComputedRef } from 'vue';\n\nimport { Action } from './action';\nimport { RejectAction } from './actions/reject-action';\nimport { SubmitAction } from './actions/submit-action';\nimport { ExecuteHandlers } from './element-state';\nimport { FieldBase } from './field-base';\nimport { type Extras } from './field.interface';\nimport { transactional } from './transaction';\n\n/**\n * The computed behind a container's `valid`, held outside the element. A computed references itself through its\n * dependency record, and JSON.stringify and lodash isEqual both walk own enumerable properties, so an element with\n * a computed as a property would be a cycle for both.\n */\nconst validReads = new WeakMap<object, ComputedRef<boolean>>();\n\n/** The computed behind a container's `busy`, held outside the element for the same reason as `validReads`. */\nconst busyReads = new WeakMap<object, ComputedRef<boolean>>();\n\n/**\n * A form element that holds other elements and composes its state from theirs: `Group`, which holds named\n * members, and `List`, which holds rows. Every element's `parent` is a `Container`.\n *\n * The behaviour over children is the same in both subclasses: `valid` and `busy` are composed from the children's,\n * `touched` is true if any child is touched and an assignment propagates down to every child, `validate(true)`\n * revalidates every child before the container computes its own validity, and a child's change of value or\n * validity reaches the container through `notifyValueChanged()` and the counters below. The subclass defines how\n * children are addressed: by name or by position.\n */\nexport abstract class Container<T = any, X extends object = Extras> extends FieldBase<T, X> {\n get [Symbol.toStringTag](): string {\n return 'Container';\n }\n\n /**\n * The children this container holds, read through the tracked view of its state, so a validity or flag composed\n * over them is recomputed when a child is added or removed.\n */\n protected abstract get children(): readonly FieldBase[];\n\n get touched(): boolean {\n return this.children.some((child) => child.touched);\n }\n\n set touched(touched: boolean) {\n transactional(() => {\n this.members.forEach((child) => {\n child.touched = touched;\n });\n });\n }\n\n get valid(): boolean {\n return this.validRead;\n }\n\n get busy(): boolean {\n return this.busyRead;\n }\n\n validate(revalidate: boolean = false) {\n transactional(() => {\n // the children are revalidated first and the container computes its own validity afterwards, over all of\n // them: a child that becomes valid announces nothing until the transaction closes, so the container does not\n // report a validity computed over a partially revalidated set\n if (revalidate) this.members.forEach((child) => child.validate(true));\n super.validate(revalidate);\n });\n }\n\n /**\n * Records that a child changed its value, so that at commit the open transaction computes this container's new\n * value and announces it once. The mutation methods call it; a direct call is rarely needed.\n */\n notifyValueChanged() {\n this.propagateValueChanged();\n }\n\n /**\n * Executes the action that confirms this container, with `params`, and returns what its `execute()` returns.\n * The action is looked up in three steps; the first step that finds a candidate decides:\n *\n * 1. an action at or below this container with a `SubmitAction` whose target is this container;\n * 2. an action with `defaultConfirm` among the direct members;\n * 3. an action with `defaultConfirm` at a lower level.\n *\n * Only actions whose `visibility` is `'full'` are candidates. One candidate is executed if it is `executable`;\n * where it is not, nothing is executed. Two or more candidates in one step are ambiguous: nothing is executed and\n * a warning is logged. Returns undefined where nothing is executed. A rendering layer calls it for a confirm\n * gesture, such as Enter in a dialog.\n */\n confirm(params?: any): Promise<any> | undefined {\n return this.command('confirm')?.execute(params);\n }\n\n /**\n * Executes the action that rejects this container, looked up as in `confirm()` with `RejectAction` and\n * `defaultReject`. A rendering layer calls it for a reject gesture, such as Escape in a dialog.\n */\n reject(params?: any): Promise<any> | undefined {\n return this.command('reject')?.execute(params);\n }\n\n /**\n * A container whose members are all actions, such as a bar of buttons, holds no data and sends nothing, like an\n * action. A container without members, or with at least one member that is not an action, sends as its access\n * determines.\n */\n protected serializesAs(purpose: 'value' | 'fullValue'): 'value' | 'null' | 'omit' {\n const children = this.children;\n if (children.length > 0 && children.every((child) => this.childSerializesAs(child, 'fullValue') === 'omit')) {\n return 'omit';\n }\n return super.serializesAs(purpose);\n }\n\n /** The action `confirm()` or `reject()` executes, or undefined. */\n private command(kind: 'confirm' | 'reject'): Action | undefined {\n const Handler = kind === 'confirm' ? SubmitAction : RejectAction;\n const flag = kind === 'confirm' ? 'defaultConfirm' : 'defaultReject';\n const shown = this.actionsBelow().filter((entry) => entry.action.visibility === 'full');\n const steps = [\n shown.filter(({ action }) =>\n action[ExecuteHandlers]().some((h) => h instanceof Handler && h.targetFor(action) === this),\n ),\n shown.filter(({ action, depth }) => depth === 0 && action[flag]),\n shown.filter(({ action, depth }) => depth > 0 && action[flag]),\n ];\n for (const candidates of steps) {\n if (candidates.length === 0) continue;\n if (candidates.length > 1) {\n console.warn(`${kind}(): ${candidates.length} actions qualify, so none is executed`);\n return undefined;\n }\n const { action } = candidates[0];\n return action.executable ? action : undefined;\n }\n return undefined;\n }\n\n /** Every action at or below this container, depth-first in member order, with its depth below this container. */\n private actionsBelow(depth = 0): { action: Action; depth: number }[] {\n return this.children.flatMap((child) => {\n if (child instanceof Action) return [{ action: child, depth }];\n if (child instanceof Container) return child.actionsBelow(depth + 1);\n return [];\n });\n }\n\n protected get composesValue(): boolean {\n return true;\n }\n\n /**\n * A container with no listener for what it holds does not compose it, so its stored copy predates the\n * unannounced changes. A registration that adds a listener updates the copy here, so the listener receives the\n * changes made after the registration.\n */\n protected refreshPreviousValue(): void {\n super.refreshPreviousValue();\n this.raw.announcedValue = this.holding;\n }\n\n /** A container holds every member's value whatever the member sends: its `fullValue`. */\n protected get holding(): any {\n return this.fullValue;\n }\n\n /**\n * The composed validity `valid` returns, memoised by Vue. The walk over the children makes an error written into\n * one of them visible without a validate() call, and the computed skips the walk while nothing it read has\n * changed.\n */\n private get validRead(): boolean {\n let read = validReads.get(this);\n if (!read) {\n read = computed(\n () =>\n this.ownErrorsValid(this.state.errors) &&\n // a child that sends nothing does not affect the container's validity\n this.children.every((child) => child.valid || this.childSerializesAs(child, 'value') === 'omit'),\n );\n validReads.set(this, read);\n }\n return read.value;\n }\n\n /**\n * The composed value of `busy`, memoised by Vue. An `Action` counts its executions in its own counter, which does\n * not notify containers, so the value is composed over the children; the computed skips the walk while nothing\n * it read has changed, and a child that is a container reads its own computed.\n */\n private get busyRead(): boolean {\n let read = busyReads.get(this);\n if (!read) {\n read = computed(() => this.children.some((child) => child.busy));\n busyReads.set(this, read);\n }\n return read.value;\n }\n\n /**\n * Records that a child's `validating` became true or false, and passes the transition up if it changes this\n * container's own `validating`.\n */\n protected childValidatingChanged(started: boolean): void {\n const wasValidating = this.validating;\n this.state.validatingChildren += started ? 1 : -1;\n if (this.validating !== wasValidating) this.parent?.childValidatingChanged(started);\n }\n\n /**\n * Records a child's new validity in this container's invalid count. The child calls it as it settles, and the\n * commit settles the deepest element first, so the count is complete when the container settles. The delta is\n * applied here; recomputing by walking the children at commit would cost `O(children)` per container and make\n * filling a list quadratic.\n */\n protected childValidityChanged(nowValid: boolean): void {\n this.raw.invalidChildren += nowValid ? -1 : 1;\n }\n}\n","import { isPlainObject } from 'lodash-es';\n\nimport { ListItemAddedAction, ListItemRemovedAction } from './actions';\nimport { Container } from './container';\nimport { type ListSlots, listSlots, ReorderRows } from './element-state';\nimport { Field } from './field';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\nimport { Group } from './group';\nimport { asBinding, noteItemTemplate } from './plugins';\nimport { transactional, TxCapture, type TxSnapshot } from './transaction';\n\n/**\n * The value of a List of R: the value of each row it sends, `null` for a row whose access is `'disabled-null'`,\n * and `[]` if it sends no rows\n */\nexport type ListValue<R extends FieldBase = Group> = (R['value'] | null)[];\n/** what List.value and the List constructor accept: an array of rows, or null, which empties the list */\nexport type ListValueInput<R extends FieldBase = Group> = ListValue<R> | null;\n/** the value of List.fullValue: the full value of every row, whatever its access */\nexport type ListFullValue<R extends FieldBase = Group> = R['fullValue'][];\n\n/** the value of a list without rows; it is frozen like every value a list builds */\nconst emptyListValue: readonly any[] = Object.freeze([]);\n\n/** What `push()` and `insert()` take: the data a row is built from, or an element. */\nexport type ListItemInput<R extends FieldBase> = R['value'] | R;\n\nexport class List<R extends FieldBase = Group, X extends object = Extras> extends Container<ListValue<R>, X> {\n get [Symbol.toStringTag](): string {\n return 'List';\n }\n\n protected get state(): ListSlots<R> {\n return super.state as ListSlots<R>;\n }\n\n protected get raw(): ListSlots<R> {\n return super.raw as ListSlots<R>;\n }\n\n private _itemTemplate?: R;\n\n constructor(itemTemplate?: undefined, params?: IFieldParams<ListValueInput<R>, X>);\n constructor(itemTemplate: R, params?: IFieldParams<ListValueInput<R>, X>);\n constructor(itemTemplate?: R, params?: IFieldParams<ListValueInput<R>, X>) {\n super(listSlots<R>());\n\n this._itemTemplate = itemTemplate;\n if (itemTemplate) noteItemTemplate(itemTemplate);\n\n // construction is one transaction, so all rows are in place before anything is announced\n transactional(() => {\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // actions are registered before the remaining parameters are assigned, so a *Changing* action supplied here\n // also applies to those assignments\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n\n // the value is assigned only if supplied, and undefined counts as not supplied (spreading an optional\n // property yields undefined), so a list declared with only an originalValue takes its rows from it. An\n // explicit null is a supplied value and leaves the list empty, its initial state.\n if (paramValue !== undefined) this.setValueInternal(paramValue);\n else if (this.originalValue !== undefined) this.setValueInternal(this.originalValue);\n }\n\n this.constructed(params);\n\n if (this.originalValue === undefined) this.originalValue = List.baseline(this.value);\n // the rows a construction ends with are the list's initial state, not a change, so the commit that closes\n // the construction announces nothing for them\n this.recordAnnounced();\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n this.validate();\n });\n }\n\n /** The row array is copied as well, so a rollback restores the rows the list held before the transaction. */\n protected [TxCapture](): TxSnapshot {\n const captured = super[TxCapture]();\n captured.rows = this.raw.rows ? [...this.raw.rows] : this.raw.rows;\n return captured;\n }\n\n /**\n * A copy of a built value, used as a baseline. The value getter returns one array per version, and a baseline\n * holding that same array would make every value equal to its original.\n */\n private static baseline<V extends any[] | null>(value: V): V {\n return (value == null ? value : [...value]) as V;\n }\n\n private processSetValueItem(item: any): R {\n let res: R;\n // an item that is already an element is used as is, and data is bound to the item template\n if (item instanceof FieldBase) res = item as R;\n else if (this._itemTemplate) res = this._itemTemplate.bind(item) as R;\n else res = List.elementFor(item) as R;\n\n // an item that already belongs to a container throws here; one this list released earlier has no parent link\n // and is taken like any other\n this.takeChild(res);\n // the row is now connected to the form above this list, so a rule of the row that refers to an element there\n // (one no record below can resolve) runs over it here\n this.completeRecords(res);\n\n return res;\n }\n\n /**\n * The row a list without an item template builds from `item`: a `Group` of fields from a plain object, a `List`\n * from an array, and a `Field` holding anything else.\n */\n private static elementFor(item: unknown): FieldBase {\n if (isPlainObject(item)) return Group.createFromFormData(item as Record<string, any>);\n if (Array.isArray(item)) return new List(undefined, { value: item });\n return new Field({ value: item });\n }\n\n /**\n * Builds an item that fills a gap left by an insert beyond the end of the list: the item template bound to its\n * own values, or, if the list has no item template, an empty element of the kind `item` is built into.\n */\n private createPaddingItem(item: unknown): R {\n if (this._itemTemplate) return this.processSetValueItem(this._itemTemplate.bind());\n if (item instanceof Group || isPlainObject(item)) return this.processSetValueItem({});\n if (item instanceof List || Array.isArray(item)) return this.processSetValueItem([]);\n return this.processSetValueItem(undefined);\n }\n\n /** Records that the set of rows changed, so `items` rebuilds its frozen array at the next read. */\n private rowsChanged(): void {\n this.state.rowsVersion++;\n }\n\n /** True if `next` is a different set of rows than `previous`: a different count, or a different row at a position. */\n private static rowsDiffer(previous: FieldBase[] | null, next: FieldBase[] | null): boolean {\n const before = previous ?? [];\n const after = next ?? [];\n return before.length !== after.length || before.some((row, index) => row !== after[index]);\n }\n\n /**\n * Installs the rows `newValue` describes. With `announce`, a row that leaves the list is announced with a\n * `ListItemRemovedAction` and a row that enters it with a `ListItemAddedAction`; a row reused at its position is\n * neither. The construction installs its rows without announcing them.\n */\n private setValueInternal(newValue: readonly unknown[] | null, announce = false) {\n // only an array (or null) is a valid list value. The check runs before the transaction opens, so a rejected\n // value leaves the rows unchanged.\n if (newValue != null && !Array.isArray(newValue)) {\n throw new TypeError('Invalid value provided: a list takes an array of rows, or null to empty it');\n }\n // a reused row is reset; its rules apply and its baseline is recorded once every row holds its new item\n transactional((tx) =>\n this.asReset(() => {\n tx.touch(this);\n // the rows before the write, so `items` builds a new array only if the assignment changes the set of rows; an\n // assignment that keeps every row keeps the array a reader already has\n const held = this.raw.rows;\n // null clears the list, as Group.value = null writes null into every member; otherwise a list nested in a\n // group would keep its rows while every sibling field was cleared\n const removed = (item: R, index: number) => {\n if (announce) tx.recordStructural(this, { actionClass: ListItemRemovedAction, item, index });\n };\n const added = (item: R, index: number) => {\n if (announce) tx.recordStructural(this, { actionClass: ListItemAddedAction, item, index });\n };\n if (newValue == null) {\n const previous = this.raw.rows ?? [];\n for (let index = previous.length - 1; index >= 0; index--) removed(previous[index], index);\n this.releaseRows();\n this.raw.rows = null;\n } else {\n const previous = this.raw.rows ?? [];\n // rows past the new length leave first, from the last one, so every announced index is the row's position\n // at the moment it leaves\n for (let index = previous.length - 1; index >= newValue.length; index--) removed(previous[index], index);\n // the new rows are built in a separate array and installed together: writing a row runs its validators, and\n // a validator that reads this list during the loop must not see an unfilled position\n const rows: R[] = new Array(newValue.length);\n for (let index = 0; index < newValue.length; index++) {\n const item = newValue[index];\n const row = previous[index];\n // an existing row at this index takes the new item, so its identity is kept and a keyed v-for keeps the\n // component rendering it. This requires an item template: a list without one builds each row from its\n // own data, so two rows can have different members, and writing one row's data into another's members\n // would drop the members they do not share. The row is reset, not assigned, so it ends in the state of a\n // row built for this position.\n // A row the list did not build from its item template (an element passed to push()) is replaced: reset\n // through the template, it would lose the members the template does not have.\n const template = this._itemTemplate;\n if (row && template && !(item instanceof FieldBase) && row.declaration === template.declaration) {\n this.resetChild(row, template, item);\n rows[index] = row;\n } else {\n if (row) {\n this.releaseChild(row);\n removed(row, index);\n }\n rows[index] = this.processSetValueItem(item);\n added(rows[index], index);\n }\n }\n for (let index = newValue.length; index < previous.length; index++) this.releaseChild(previous[index]);\n this.raw.rows = rows;\n }\n if (List.rowsDiffer(held, this.raw.rows)) this.rowsChanged();\n this.bumpValueVersion();\n }),\n );\n }\n\n get value(): ListValue<R> {\n // the version read is tracked and the cache read is not, so a reader served from the cache still depends on\n // every write below this list, without repeating the walk over its rows\n const version = this.valueVersion;\n if (this.raw.cachedValueVersion === version) return this.raw.cachedValue;\n\n const value: unknown[] = [];\n (this.rows ?? []).forEach((row) => {\n switch (this.childSerializesAs(row, 'value')) {\n case 'value':\n value.push(row.value);\n break;\n case 'null':\n value.push(null);\n break;\n case 'omit':\n break;\n }\n });\n // the array is shared with later readers, so it is frozen, as is every row object in it; a write into either\n // would change the list's value without any row holding that value. A list without rows returns [].\n const built = (value.length ? Object.freeze(value) : emptyListValue) as ListValue<R>;\n this.raw.cachedValue = built;\n this.raw.cachedValueVersion = version;\n return built;\n }\n\n set value(newValue: ListValueInput<R>) {\n transactional(() => {\n this.setValueInternal(newValue, true);\n // an assignment replaces the whole list and is always announced, without a comparison\n this.propagateValueChanged(true);\n });\n }\n\n /**\n * If no value is supplied, the rows are taken from `source`, so a list nested in a row reused by a whole-list\n * assignment ends up with the item template's rows, not its previous ones.\n */\n protected resetTo(source: FieldBase, value: any): void {\n transactional((tx) => {\n tx.touch(this);\n if (this.errors.length) this.errors = [];\n this.setValueInternal(value === undefined ? (source as List<R>).fullValue : value);\n this.recordBaseline();\n super.validate(true);\n });\n }\n\n protected recordBaseline(): void {\n // a reset list announces nothing itself: the container that reset it announces the change\n this.recordAnnounced();\n this.originalValue = List.baseline(this.value);\n }\n\n bind(data?: ListValueInput<R>, overrides?: IBindParams<ListValueInput<R>, X>): List<R, X> {\n const template = this._itemTemplate?.bind() as R | undefined;\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (itemTemplate?: R, params?: IFieldParams<ListValueInput<R>, X>) => List<R, X>;\n const res = asBinding(\n () =>\n new Ctor(template, {\n // undefined data counts as not supplied; an explicit null is supplied and clears. The copied value is what\n // the list holds (fullValue), not what it sends, so a row that sends nothing keeps its data\n value: [...((data !== undefined ? data : this.fullValue) ?? [])],\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<ListValueInput<R>, X>),\n );\n // a subclass whose constructor does not take (itemTemplate, params) ignores both and would return a list built\n // from its own declaration instead of this record. The difference would not be visible, so it throws here.\n if (res._itemTemplate !== template) {\n throw new TypeError(\n `${this.constructor.name}.bind() built a list that did not take the item template it was given, so the ` +\n \"binding would carry the declaration's rows. A subclass whose constructor does not take \" +\n '(itemTemplate, params) has to override bind() and construct itself.',\n );\n }\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n return res;\n }\n\n /**\n * The rows, read so that the caller depends on the set of rows: the read of `rowsVersion` is tracked, and the\n * array itself is held outside Vue's reactivity. A reactive array would route every element a `splice()` shifts\n * through the proxy, so inserting or removing a row would cost a proxied write per row after it. Every change\n * of the set of rows increments `rowsVersion`.\n */\n private get rows(): R[] | null {\n void this.state.rowsVersion;\n return this.raw.rows;\n }\n\n protected get members(): FieldBase[] {\n return this.raw.rows ?? [];\n }\n\n protected get children(): readonly FieldBase[] {\n return this.rows ?? [];\n }\n\n /**\n * The full value of every row. `value` is what the list sends; `fullValue` is what the list holds: every row\n * whatever its access, and every field of a group row. A binding or a reset copies it.\n */\n get fullValue(): ListFullValue<R> {\n return (this.rows ?? [])\n .filter((row) => this.childSerializesAs(row, 'fullValue') !== 'omit')\n .map((row) => row.fullValue);\n }\n\n /**\n * The number of rows this list holds. The read is tracked, so a template that reads it re-renders when rows are\n * added or removed.\n */\n get length(): number {\n return this.rows?.length ?? 0;\n }\n\n /**\n * The rows this list holds, in position order. The array is a frozen copy of the rows at the time of the read and\n * cannot be written through (`push`, `insert`, `remove` and `clear` change the rows), so a caller may keep it. The\n * rows in it are the live elements, so a row read from it returns its current state.\n *\n * The copy is built once per change of the set of rows and returned to every reader until the next change: a\n * write inside a row changes what the list sends without changing which rows it holds, and the array stays the\n * same across such a write.\n */\n get items(): readonly R[] {\n // the version read is tracked and the cache read is not, so a reader served from the cache still re-runs when\n // the set of rows changes\n const version = this.state.rowsVersion;\n if (this.raw.cachedItemsVersion !== version) {\n this.raw.cachedItems = Object.freeze([...(this.raw.rows ?? [])]);\n this.raw.cachedItemsVersion = version;\n }\n return this.raw.cachedItems!;\n }\n\n get(index: number): R | undefined {\n return this.rows?.[index];\n }\n\n push(item: ListItemInput<R>): number {\n return this.insert(item, this.raw.rows?.length ?? 0) + 1;\n }\n\n pop(): R | undefined {\n return this.remove((this.raw.rows?.length ?? 0) - 1);\n }\n\n remove(index: number): R | undefined {\n let removedItem: R | undefined;\n transactional((tx) => {\n const rows = this.raw.rows;\n if (rows == null || index < 0 || rows.length <= index) return;\n\n // the row array is recorded before the splice, so a rollback restores the rows\n tx.touch(this);\n const row = rows.splice(index, 1)?.[0];\n if (!row) return;\n\n // the removed row is returned as is: releaseChild clears its back-reference, so another container can take\n // it, and it keeps its values, its errors and the change history behind isChanged\n this.releaseChild(row);\n this.rowsChanged();\n this.bumpValueVersion();\n removedItem = row;\n\n // a removal is an operation with no net result over a transaction, so it is queued in order without a\n // comparison, and the commit emits it before the resulting value change\n tx.recordStructural(this, { actionClass: ListItemRemovedAction, item: removedItem, index });\n // one item fewer is a different set, so the value change is announced without a comparison\n this.propagateValueChanged(true);\n });\n\n return removedItem;\n }\n\n insert(item: ListItemInput<R>, index: number): number {\n let position = 0;\n transactional((tx) => {\n tx.touch(this);\n const rows = (this.raw.rows ??= []);\n // a negative index counts back from the end and is clamped at the start, as in splice, so the announced and\n // returned position is the one the item occupies\n position = index < 0 ? Math.max(rows.length + index, 0) : index;\n while (rows.length < position) {\n // an index beyond the end is reached by adding padding items\n const itm = this.createPaddingItem(item);\n // push returns the new length, while the event carries the index of the item that was added\n const idx = rows.push(itm) - 1;\n this.bumpValueVersion();\n tx.recordStructural(this, { actionClass: ListItemAddedAction, item: itm, index: idx });\n }\n const itm = this.processSetValueItem(item);\n rows.splice(position, 0, itm);\n\n tx.recordStructural(this, { actionClass: ListItemAddedAction, item: itm, index: position });\n // one item more is a different set, so the value change is announced without a comparison\n this.rowsChanged();\n this.bumpValueVersion();\n this.propagateValueChanged(true);\n });\n\n return position;\n }\n\n /** Releases every row from this list, so a later validity change of a row does not affect its invalid count. */\n private releaseRows(): void {\n this.raw.rows?.forEach((row) => this.releaseChild(row));\n }\n\n /**\n * Puts the rows in the order `rows` gives, in place: `rows` holds the same rows as the list, in a new order. The\n * set of rows does not change, so no `ListItemAddedAction` or `ListItemRemovedAction` fires; the value changes and\n * is announced. The view of a list calls it for `sort()` and `reverse()`; the package does not export the key.\n */\n [ReorderRows](rows: readonly R[]): void {\n transactional((tx) => {\n tx.touch(this);\n this.raw.rows = [...rows];\n this.rowsChanged();\n this.bumpValueVersion();\n this.propagateValueChanged(true);\n });\n }\n\n clear() {\n transactional((tx) => {\n const rows = this.raw.rows ?? [];\n const hadItems = rows.length > 0;\n tx.touch(this);\n // every row leaves, from the last one, so every announced index is the row's position at the moment it leaves\n for (let index = rows.length - 1; index >= 0; index--) {\n tx.recordStructural(this, { actionClass: ListItemRemovedAction, item: rows[index], index });\n }\n this.releaseRows();\n this.raw.rows = null;\n // clearing a list without rows does not change its rows, so the array `items` returns is kept\n if (hadItems) this.rowsChanged();\n this.bumpValueVersion();\n this.propagateValueChanged(hadItems);\n });\n }\n\n /** Takes `null` as well as an array of rows: `rebind(null)` empties the list. */\n rebind(data: ListValueInput<R>): this {\n return super.rebind(data as ListValue<R>);\n }\n}\n\nexport type NullableList = List | null;\n","import { isEmpty, isPlainObject } from 'lodash-es';\n\nimport type { Action } from './action';\nimport { Container } from './container';\nimport { type GroupSlots, groupSlots } from './element-state';\nimport { Field } from './field';\nimport { FieldBase } from './field-base';\nimport { type Extras, IBindParams, IFieldParams } from './field.interface';\n// list.ts imports this module as well; List is used only inside a call, after both modules are loaded\nimport { List } from './list';\nimport { asBinding } from './plugins';\nimport { transactional, TxCapture, type TxSnapshot } from './transaction';\n\nexport type GenericFieldsInterface = Record<string, FieldBase>;\n\n/** The keys of the members that send something: every member except an `Action`. */\ntype DataKeys<T extends GenericFieldsInterface> = {\n [K in keyof T]: T[K] extends Action<any, any> ? never : K;\n}[keyof T];\n\n/**\n * Converts a field structure into the matching value structure. The indexed access reads each element's value\n * getter, so a nested Group sends its own value structure and a List sends its row array; inferring from\n * FieldBase<infer U> would use the value setter, which on Group accepts a wider type than the getter returns.\n * Every member may be `null`, because a member whose access is `'disabled-null'` sends `null` in place of its\n * value. An `Action` member sends nothing and has no key.\n */\nexport type FieldsToValues<T extends GenericFieldsInterface> = {\n [K in DataKeys<T>]: T[K]['value'] | null;\n};\n\n/**\n * The type of Group.fullValue. The indexed access reads each element's fullValue getter, so a nested group has its\n * full structure, not the partial one its `value` builds. Every member is present whatever its access, except an\n * `Action`, which holds no data.\n */\nexport type FieldsToFullValues<T extends GenericFieldsInterface> = {\n [K in DataKeys<T>]: T[K]['fullValue'];\n};\n\n/**\n * The type of Group.value: the values of the members that send something, and `{}` if none does. Every key is\n * optional, because a member whose access is `'disabled'` is omitted from the object the group builds.\n */\nexport type GroupValue<T extends GenericFieldsInterface> = Partial<FieldsToValues<T>>;\n/** what Group.value and the Group constructor accept: missing keys are not assigned, and null clears */\nexport type GroupValueInput<T extends GenericFieldsInterface> = Partial<FieldsToValues<T>> | null;\n\n/**\n * The groups whose constructor is still adding and writing their members. A member's record is completed after the\n * constructor has written the given data, so a rule that reads a sibling runs over that data, not over the values\n * the members were bound with.\n */\n/** The element plain data is built into: a `Group` for a plain object, a `List` for an array, a `Field` otherwise. */\nfunction elementFromData(value: unknown): FieldBase {\n if (isPlainObject(value)) return Group.createFromFormData(value as Record<string, any>);\n if (Array.isArray(value)) return new List(undefined, { value });\n return new Field({ value });\n}\n\nconst assembling = new WeakSet<object>();\n\n/** the value of a group in which no member sends anything; it is frozen like every value a group builds */\nconst emptyGroupValue = Object.freeze({});\n\n/**\n * The read-only view of a group's member map, held outside the group. It is a proxy over the map the group writes\n * into, so as a property of the group it would be walked twice by JSON.stringify and by lodash isEqual, which both\n * walk own keys.\n */\nconst fieldsViews = new WeakMap<object, GenericFieldsInterface>();\n\n/**\n * The handler of that view. Every read calls `track` first, which reads the group's name array (the part of the\n * state that lists the members), so a reader inside an effect re-runs when addField() or removeField() changes the\n * set of members; the map itself is outside the reactive state, and a write to it alone triggers no effect.\n *\n * Every write throws a TypeError: an element assigned into the map or deleted from it would not get its parent,\n * fieldName or change notifications updated, and the group would keep counting the validity of a member it no\n * longer holds. Use addField() and removeField() to change the set of members.\n */\nconst fieldsAreReadOnly = (track: () => number): ProxyHandler<GenericFieldsInterface> => ({\n get(target, key, receiver) {\n track();\n return Reflect.get(target, key, receiver);\n },\n has(target, key) {\n track();\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n track();\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n track();\n return Reflect.getOwnPropertyDescriptor(target, key);\n },\n set(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be assigned: use addField() to give the group a member`);\n },\n defineProperty(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be redefined: use addField() to give the group a member`);\n },\n deleteProperty(_target, key) {\n throw new TypeError(`fields.${String(key)} cannot be deleted: use removeField() to take a member out`);\n },\n});\n\nexport class Group<\n T extends GenericFieldsInterface = GenericFieldsInterface,\n X extends object = Extras,\n> extends Container<GroupValue<T>, X> {\n get [Symbol.toStringTag](): string {\n return 'Group';\n }\n\n protected get state(): GroupSlots<GroupValue<T>> {\n return super.state as GroupSlots<GroupValue<T>>;\n }\n\n protected get raw(): GroupSlots<GroupValue<T>> {\n return super.raw as GroupSlots<GroupValue<T>>;\n }\n\n private readonly _fields: T;\n\n constructor(fields: T, params?: IFieldParams<GroupValueInput<T>, X>) {\n super(groupSlots<GroupValue<T>>());\n\n if (!Group.isValidFields(fields)) throw new Error('Invalid fields object provided');\n // the backing map has no prototype: a field may be named after an Object.prototype member, and on a regular\n // object a `__proto__` key would call the inherited setter instead of becoming a field\n this._fields = Object.create(null) as T;\n\n // construction is one transaction: the members are added and written before anything is announced, and a\n // member that cannot be added (another container already holds it) leaves no partially built group\n transactional(() => {\n let assigned = false;\n let suppliedBaseline = false;\n assembling.add(this);\n try {\n Object.entries(fields).forEach(([name, field]) => this.addField(name, field));\n\n if (params) {\n const { value: paramValue, validators, actions, ...otherParams } = params;\n // actions are registered before the remaining parameters are assigned, so a *Changing* action supplied\n // here also applies to those assignments\n this.registerInitialActions([...(validators || []), ...(actions || [])]);\n this.assignParams(otherParams);\n // the value is assigned only if supplied, and undefined counts as not supplied (spreading an optional\n // property yields undefined): assigning it would write null into every member and record that cleared\n // state as the original, so the group would report itself unchanged over values its members never held.\n // An explicit null is a supplied value and clears the members.\n if (paramValue !== undefined) this.assignMembers(paramValue as GroupValueInput<T>);\n else if (this.originalValue !== undefined) this.assignMembers(this.originalValue);\n assigned = paramValue !== undefined || this.originalValue !== undefined;\n suppliedBaseline = params.originalValue !== undefined && paramValue !== undefined;\n }\n } finally {\n assembling.delete(this);\n }\n\n // the members are in place and hold their values, so their record is complete: a member whose eager pass ran\n // before the group existed (every member of a bound group) runs it again here\n this.completeRecords();\n\n this.constructed(params);\n\n // reading value walks every member and builds an object, so it is read once here and reused below\n const constructedValue = this.value;\n if (this.originalValue === undefined) this.originalValue = Group.baseline(constructedValue);\n\n // the state a construction ends with is the group's initial state, not a change: recording it as announced\n // keeps the commit from announcing the members' assignment as a change of the group, and the first later\n // change of a member is compared against it\n this.recordAnnounced();\n\n this.boundActions?.triggerEager(this, this.contribution, this.originalValue);\n\n // the members hold their part of the assigned data, so it is their baseline as it is the group's\n if (assigned) {\n this.baselineMembers();\n if (suppliedBaseline) this.baselineMembersFrom(this.originalValue);\n }\n this.validate();\n });\n }\n\n /**\n * Gives every member `data` contains its part of `data` as its baseline, and so on through the groups below it;\n * null gives each member null.\n */\n private baselineMembersFrom(data: GroupValue<T> | null): void {\n Object.entries(this._fields).forEach(([name, field]) => {\n if (this.childSerializesAs(field, 'fullValue') === 'omit') return;\n if (data != null && !Object.hasOwn(data, name)) return;\n const part = data == null ? null : (data as Record<string, any>)[name];\n if (field instanceof Group) field.baselineMembersFrom(part);\n field.originalValue = part;\n });\n }\n\n /**\n * The name array is copied as well, so a rollback restores the set of members the group held before the\n * transaction.\n */\n protected [TxCapture](): TxSnapshot {\n const captured = super[TxCapture]();\n captured.fieldNames = [...this.raw.fieldNames];\n return captured;\n }\n\n /**\n * A copy of a built value, used as a baseline. The value getter returns one object per version, and a baseline\n * holding that same object would make every value equal to its original.\n */\n private static baseline<V extends GenericFieldsInterface>(value: GroupValue<V>): GroupValue<V> {\n return value == null ? value : { ...value };\n }\n\n /**\n * Adds `field` to this group under `fieldName`, in the same state as an element passed to the constructor: the\n * element has the back-reference and the name, its validity counts towards the group's, and a rule of the element\n * that refers to another element of the form is resolved here.\n *\n * The change is announced through the regular path: the group announces its new value when the transaction\n * closes, and its validity is recomputed over its current members. The baseline behind `isChanged` is not\n * rewritten: a group that gains an element holds a value its original value does not contain, and reports itself\n * changed until `originalValue` is written.\n *\n * @throws Error if this group already holds an element under `fieldName`.\n * @throws TypeError if `field` already belongs to a container; pass a `bind()` of it instead.\n */\n addField(fieldName: string, field: FieldBase): this {\n transactional((tx) => {\n if (Object.hasOwn(this._fields, fieldName)) {\n throw new Error(`Field ${fieldName} is already in this form`);\n }\n // takeChild throws for an element another group or list already holds, and sets the back-reference and the\n // name together\n this.takeChild(field, fieldName);\n tx.touch(this);\n Group.setEntry(this._fields, fieldName, field);\n // the map is not in the state a snapshot covers, so the removal is registered as a separate undo; the name\n // array is in the state and a rollback restores it with the rest\n tx.whenRolledBack(() => Group.dropEntry(this._fields, fieldName));\n this.state.fieldNames.push(fieldName);\n // the element is now connected to the form above this group, so a rule of the element that refers to an\n // element there (one no record below can resolve) runs over it here. A group still being constructed\n // completes its members after it has written the given data.\n if (!assembling.has(this)) this.completeRecords(field);\n this.bumpValueVersion();\n this.notifyValueChanged();\n });\n return this;\n }\n\n /**\n * Removes the element held under `fieldName` from this group and returns it, or returns undefined if the group\n * holds no element of that name. The back-reference and the name are cleared, its validity and its runs in\n * flight no longer count towards the group's, and another container can take it. It keeps its value, its errors\n * and the change history behind `isChanged`.\n *\n * The change is announced through the regular path, so the group's value and validity are recomputed over the\n * remaining members. The baseline behind `isChanged` is not rewritten, as with `addField`.\n */\n removeField(fieldName: string): FieldBase | undefined {\n let removed: FieldBase | undefined;\n transactional((tx) => {\n if (!Object.hasOwn(this._fields, fieldName)) return;\n const field: FieldBase = this._fields[fieldName];\n tx.touch(this);\n this.releaseChild(field);\n Group.dropEntry(this._fields, fieldName);\n tx.whenRolledBack(() => Group.setEntry(this._fields, fieldName, field));\n this.state.fieldNames.splice(this.state.fieldNames.indexOf(fieldName), 1);\n this.bumpValueVersion();\n this.notifyValueChanged();\n removed = field;\n });\n return removed;\n }\n\n /**\n * Writes one entry of the member map. The map is typed by the fields interface, which lists only the members of\n * that group type, so here and in dropEntry it is cast to a plain record.\n */\n private static setEntry(fields: GenericFieldsInterface, fieldName: string, field: FieldBase): void {\n (fields as Record<string, FieldBase>)[fieldName] = field;\n }\n\n /** Removes one entry from the member map. */\n private static dropEntry(fields: GenericFieldsInterface, fieldName: string): void {\n delete (fields as Record<string, FieldBase | undefined>)[fieldName];\n }\n\n private static isValidFields(flds: unknown): flds is Record<string, FieldBase> {\n function isFieldAll(field: unknown): field is FieldBase {\n return field instanceof FieldBase;\n }\n\n return typeof flds === 'object' && flds !== null && Object.entries(flds).every(([, field]) => isFieldAll(field));\n }\n\n /**\n * Builds a group from plain data, so that its `fullValue` is `data`: a plain object becomes a `Group`, an array a\n * `List` without an item template (whose rows are built by the same rule), and any other value a `Field`, at every\n * level.\n */\n static createFromFormData(data: Record<string, any> | null): Group {\n if (data instanceof FieldBase) {\n throw new Error('data is already a Form structure, should be a simple object');\n }\n return new Group(\n data == null ? {} : Object.fromEntries(Object.entries(data).map(([key, value]) => [key, elementFromData(value)])),\n );\n }\n\n field<K extends keyof T>(fieldName: K): T[K] | null {\n return this._fields[fieldName] ?? null;\n }\n\n /**\n * The typed map of this group's members. It is a view over the map the group holds: a read returns the members\n * themselves, and every write throws a TypeError (use addField() and removeField()). The view is created on the\n * first read.\n *\n * A read through it is a tracked read of the set of members, so a template that reads `group.fields` re-renders\n * when an element is added or removed; each member tracks its own state.\n */\n get fields(): T {\n let view = fieldsViews.get(this);\n if (!view) {\n view = new Proxy(\n this._fields,\n fieldsAreReadOnly(() => this.state.fieldNames.length),\n );\n fieldsViews.set(this, view);\n }\n return view as T;\n }\n\n protected get members(): FieldBase[] {\n return this.raw.fieldNames.map((name) => this._fields[name]);\n }\n\n protected get children(): readonly FieldBase[] {\n // the names are read through the tracked view, so adding or removing a member recomputes what is composed\n // over them; the members are read from the map, which is outside the reactive state\n return this.state.fieldNames.map((name) => this._fields[name]);\n }\n\n get value(): GroupValue<T> {\n // the version read is tracked and the cache read is not, so a reader served from the cache still depends on\n // every write below this group, without repeating the walk\n const version = this.valueVersion;\n if (this.raw.cachedValueVersion === version) return this.raw.cachedValue;\n\n // accumulate without a prototype so a field named `__proto__` is stored instead of reassigning the\n // accumulator's prototype; the spread on return produces a regular object\n const val = Object.create(null) as Record<string, any>;\n Object.entries(this._fields).forEach(([name, field]) => {\n switch (this.childSerializesAs(field, 'value')) {\n case 'value':\n val[name] = field.value;\n break;\n case 'null':\n val[name] = null;\n break;\n case 'omit':\n break;\n }\n });\n // the object is shared with later readers, so it is frozen: a write into it would change the group's value\n // without any member holding that value. A group that sends a value sends an object, so a group in which no\n // member sends anything returns {}.\n const built = (isEmpty(val) ? emptyGroupValue : Object.freeze({ ...val })) as GroupValue<T>;\n this.raw.cachedValue = built;\n this.raw.cachedValueVersion = version;\n return built;\n }\n\n /**\n * Writes the members whose keys the given value contains. The members are written one by one and the group\n * announces nothing in between: the transaction compares the group's value and validity once, after all members\n * are written, and announces each at most once.\n */\n private assignMembers(newValue: GroupValueInput<T>) {\n transactional(() => {\n Object.entries(this._fields).forEach(([name, field]) => {\n // an action holds no data, so a value assigned to the group does not reach it, null included\n if (this.childSerializesAs(field, 'fullValue') === 'omit') return;\n if (newValue == null || Object.hasOwn(newValue, name)) {\n field.value = newValue == null ? null : (newValue as Record<string, any>)[name];\n }\n });\n });\n }\n\n set value(newValue: GroupValueInput<T>) {\n transactional((tx) => {\n this.assignMembers(newValue);\n tx.markValidityDirty(this);\n });\n }\n\n /**\n * Members are reset one by one, not assigned as a whole value: the value setter writes only the keys the value\n * contains, while a member missing from the value must take its value from `source`. `source` supplies it per\n * member, so a group reset from the declaration it was bound from matches a new binding of it.\n */\n protected resetTo(source: FieldBase, value: any): void {\n const template = source as Group<T>;\n transactional((tx) => {\n tx.touch(this);\n if (this.errors.length) this.errors = [];\n Object.entries(this._fields).forEach(([name, field]) => {\n // a null value clears every member, as assigning null does. A member whose key is missing from a value takes\n // the baseline of the template's member: for a group that is its own declaration that is the member's own\n // originalValue, so a member the value leaves out (a 'disabled' one) is put back to its baseline, not left\n // holding what was written to it since. Without a value, every member takes the template member's value.\n // An action holds no data and takes its value from the template, whatever the value contains\n const source = template.field(name) ?? field;\n let memberValue: any;\n if (this.childSerializesAs(field, 'fullValue') === 'omit') memberValue = undefined;\n else if (value === null) memberValue = null;\n else if (value !== undefined) memberValue = Object.hasOwn(value, name) ? value[name] : source.originalValue;\n this.resetChild(field, source, memberValue);\n });\n this.recordBaseline();\n super.validate(true);\n });\n }\n\n protected recordBaseline(): void {\n // a reset group announces nothing itself: the container that reset it announces the change\n this.recordAnnounced();\n this.originalValue = Group.baseline(this.value);\n }\n\n /**\n * Everything the group holds: every member's `fullValue`, whatever the member's access. `value` is what the group\n * sends; `fullValue` is what it holds, and a binding of the group copies it.\n */\n get fullValue(): FieldsToFullValues<T> {\n const value = Object.create(null) as Record<string, any>;\n Object.entries(this._fields).forEach(([name, field]) => {\n if (this.childSerializesAs(field, 'fullValue') !== 'omit') value[name] = field.fullValue;\n });\n return { ...value } as FieldsToFullValues<T>;\n }\n\n /**\n * Throws a TypeError if `res` was not built from the members passed to it. A subclass whose constructor does not\n * take `(fields, params)` (one that composes its own members and passes them to super) ignores them and would\n * return a binding with the declaration's data instead of the record's. The difference would not be visible, so\n * it throws here.\n */\n private static assertTookFields(res: Group<any, any>, fields: object, name: string): void {\n // the members are compared by identity, not by name: a subclass that composes its own members has the same\n // names, and the check requires the instances that hold the record's data\n const asked = Object.entries(fields) as [string, FieldBase][];\n const got = res.raw.fieldNames;\n if (asked.length === got.length && asked.every(([key, field]) => res._fields[key] === field)) return;\n throw new TypeError(\n `${name}.bind() built an element that did not take the members it was given, so the binding would carry ` +\n `the declaration's data. A subclass whose constructor does not take (fields, params) has to override ` +\n 'bind() and construct itself.',\n );\n }\n\n bind(data?: GroupValueInput<T>, overrides?: IBindParams<GroupValueInput<T>, X>): Group<T, X> {\n const newFields = Object.create(null) as T;\n Object.entries(this._fields).forEach(([name, field]) => {\n newFields[name as keyof T] = field.bind() as any;\n });\n // construction goes through this.constructor so that a subclass binds into its own type\n const Ctor = this.constructor as new (fields: T, params?: IFieldParams<GroupValueInput<T>, X>) => Group<T, X>;\n const res = asBinding(\n () =>\n new Ctor(newFields, {\n // undefined data counts as not supplied; an explicit null is supplied and clears. The copied value is what\n // the group holds (fullValue), not what it sends, so a member that sends nothing keeps its data\n value: data !== undefined ? this.withBaselines(data) : (this.fullValue as GroupValueInput<T>),\n ...(overrides && 'originalValue' in overrides ? { originalValue: overrides.originalValue } : {}),\n access: overrides?.access ?? this.access,\n visibility: overrides?.visibility ?? this.visibility,\n } as IFieldParams<GroupValueInput<T>, X>),\n );\n Group.assertTookFields(res, newFields, this.constructor.name);\n res.boundFrom(this, res.contribution, res.originalValue, overrides);\n // the members were bound empty and written by the construction, which assembles the record their rules read; a\n // binding starts out unchanged at every level, so each member records what it holds as its baseline, and a\n // baseline the overrides supply is the baseline of the members it contains\n res.baselineMembers();\n if (overrides?.originalValue !== undefined) res.baselineMembersFrom(res.originalValue);\n return res;\n }\n\n /**\n * `data` with every key it leaves out filled in with the baseline of the corresponding member, as `rebind` fills\n * it; null and an action, which holds no data, stay as they are.\n */\n private withBaselines(data: GroupValueInput<T> | null): GroupValueInput<T> | null {\n if (data === null) return data;\n const filled: Record<string, unknown> = { ...data };\n Object.entries(this._fields).forEach(([name, field]) => {\n if (!Object.hasOwn(filled, name) && this.childSerializesAs(field, 'fullValue') !== 'omit') {\n filled[name] = field.originalValue;\n }\n });\n return filled as GroupValueInput<T>;\n }\n\n /**\n * A record need not contain every member: a member whose key is missing takes the `originalValue` of the\n * corresponding member of the group's declaration, and for a group that is its own declaration, its own baseline.\n */\n rebind(data: GroupValueInput<T>): this {\n return super.rebind(data as GroupValue<T>);\n }\n}\n\nexport type NullableGroup = Group | null;\n","import { isEqual as structuralEqual, isEqualWith } from 'lodash-es';\n\nimport { FieldBase } from './field-base';\n\n/**\n * Where either side is a `FieldBase`, compares the value it holds: a structural comparison of two elements finds\n * no properties, because their state is in private class fields. Returning `undefined` passes the comparison to\n * lodash's structural comparison, so an element nested at any depth inside a plain object or an array\n * (`list.items`, a `Map`, a hand-built record) is reached too.\n */\nfunction customizer(a: unknown, b: unknown): boolean | undefined {\n const aValue = a instanceof FieldBase ? a.value : a;\n const bValue = b instanceof FieldBase ? b.value : b;\n return aValue === a && bValue === b ? undefined : structuralEqual(aValue, bValue);\n}\n\n/**\n * Structural equality that compares a `FieldBase` by the value it holds. `isEqual(fieldA, fieldB)` and\n * `isEqual(list.items, other.items)` compare values as `isEqual(fieldA.value, fieldB.value)` does, without\n * unwrapping each element at the call site.\n *\n * Two `FieldBase` operands are compared by `.value` directly, without the `isEqualWith` customizer dispatch.\n */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (a instanceof FieldBase && b instanceof FieldBase) return structuralEqual(a.value, b.value);\n return isEqualWith(a, b, customizer);\n}\n","import { unref } from 'vue';\n\nimport { ValueChangedAction } from '../actions';\nimport type { FieldBase } from '../field-base';\nimport { bindingsIn, resolveByName, resolveInScope, scopeOf } from '../resolve';\n\nimport { ValidationErrorOptions, ValidationFunction, Validator, ValidatorBindingState } from './validator';\n\n/**\n * The element to compare against: the element itself, its name in its container, or a callback that returns it\n * for the field being validated. All three are resolved within the record the validation runs over: given an\n * element of a `List`'s item template, a row compares against that row's element.\n */\nexport type CompareToTarget = FieldBase | string | ((field: FieldBase) => FieldBase | null | undefined);\n\n/** The validator's state for one field it validates. */\ninterface CompareToBindingState<T> extends ValidatorBindingState {\n oldValue: T;\n}\n\nexport default class CompareTo<T = any> extends Validator {\n private readonly otherField: CompareToTarget;\n\n /**\n * The fields this validator is registered on. Registration happens one element at a time (the rows of a list\n * receive the validator one by one, as they are built from the item template), so this set determines which\n * elements of a declaration have the rule; a change of the compared element does not revalidate the others.\n */\n private readonly registrations = new WeakSet<FieldBase>();\n\n /**\n * The elements this validator has installed its listener on. A binding of such an element has the listener too\n * (a binding uses the actions of its declaration), so the declaration is checked as well, and a list of N rows\n * installs one listener, not N.\n */\n private readonly listening = new WeakSet<FieldBase>();\n\n /**\n * The declarations of the fields this validator was registered on. One entry covers every binding of such a\n * field, so a change of a compared element finds the fields of its record without this set holding every row.\n */\n private readonly declarations = new Set<FieldBase>();\n\n constructor(\n otherField: CompareToTarget,\n private isValidComparison: (myValue: T, otherValue: T) => boolean,\n options?: ValidationErrorOptions,\n ) {\n const validationFn: ValidationFunction = (newValue: T, oldValue: T, field: FieldBase) => {\n this.comparisonState(field).oldValue = oldValue;\n\n const other = this.resolve(field);\n // a record that does not hold the compared element yet (a row still being built) produces no result, and the\n // container that completes the record runs this pass again\n if (!other) {\n field.markRecordIncomplete();\n return null;\n }\n this.listenOn(other);\n\n const otherValue = unref(other.value);\n if (!this.isValidComparison(unref(newValue), otherValue)) {\n return [\n this.errorFor(options, 'compare_to', 'Value does not match the comparison with {otherValue}', {\n newValue,\n oldValue,\n otherValue,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n this.otherField = otherField;\n }\n\n /** The element `field` is compared against, within the record `field` belongs to. */\n private resolve(field: FieldBase): FieldBase | undefined {\n const other = this.otherField;\n if (typeof other === 'function') return other(field) ?? undefined;\n if (typeof other === 'string') return resolveByName(other, field);\n return resolveInScope(other, scopeOf(field));\n }\n\n /**\n * Registers a listener so a change of `other` re-runs this comparison. The listener re-runs it over the fields of\n * the record the change happened in, not over the field that installed it, so a listener a row inherits from its\n * declaration applies to that row; it re-runs only this validator, not the whole chain.\n */\n private listenOn(other: FieldBase): void {\n if (this.listening.has(other) || this.listening.has(other.declaration)) return;\n this.listening.add(other);\n other.registerAction(\n new ValueChangedAction((oField, supr, oNewValue, oOldValue) => {\n supr(oField, oNewValue, oOldValue);\n const scope = scopeOf(oField);\n this.declarations.forEach((declaration) =>\n bindingsIn(declaration, scope).forEach((mine) => {\n // of the declaration's elements, only those the validator is registered on are revalidated, so a rule\n // registered on one row of a list applies only to that row\n if (!this.registrations.has(mine)) return;\n this.execute(mine, () => null, mine.contribution, this.comparisonState(mine).oldValue);\n }),\n );\n }),\n );\n }\n\n boundToBinding(binding: FieldBase) {\n this.declarations.add(binding.declaration);\n this.registrations.add(binding);\n }\n\n private comparisonState(field: FieldBase): CompareToBindingState<T> {\n return this.bindingState(field) as CompareToBindingState<T>;\n }\n\n protected newBindingState(): CompareToBindingState<T> {\n return { ...super.newBindingState(), oldValue: undefined as T };\n }\n\n unregisterFrom(binding: FieldBase) {\n // the errors this validator put on the binding are removed with the registration: the base method removes\n // them, recomputes validity and cancels the run in flight, and the binding is removed from the set the\n // compared element revalidates\n super.unregisterFrom(binding);\n this.registrations.delete(binding);\n }\n}\n","import { isArray, isObject, isString } from 'lodash-es';\n\n/**\n * The length of a value as the length and the `Required` validators measure it: the length of a string or an array,\n * the size of a `Map` or a `Set`, the number of own keys of a plain object (one without a prototype included), and\n * the length of the string any other value converts to.\n */\nexport function toLength(a: any): number {\n if (a == null) return 0;\n if (isArray(a)) return a.length;\n if (isString(a)) return a.length;\n if (a instanceof Map || a instanceof Set) return a.size;\n if (isObject(a)) {\n const proto = Object.getPrototypeOf(a);\n if (proto === Object.prototype || proto === null) return Object.keys(a).length;\n }\n return String(a).length;\n}\n\n/**\n * Whether `value` is empty: `null`, `undefined`, an empty string, an empty array, an empty `Map` or `Set`, or a\n * plain object (one without a prototype included) with no own keys. Every built-in validator except `Required` and\n * `CompareTo` passes an empty value, so a field that may stay empty carries only the other validators, and a field\n * that may not adds `Required`.\n */\nexport function isEmptyValue(value: unknown): boolean {\n return toLength(value) === 0 && (value == null || isString(value) || isArray(value) || isObject(value));\n}\n\n/**\n * Compares `value` with `bound`: negative where `value` is smaller, zero where equal, positive where larger, and\n * `undefined` where the two cannot be compared. Numbers compare with numbers, bigints with bigints, strings with\n * strings (by code unit) and dates with dates (by time). `NaN` and an invalid date compare with nothing.\n */\nexport function compareValues(value: unknown, bound: unknown): number | undefined {\n if (value instanceof Date && bound instanceof Date) {\n const difference = value.getTime() - bound.getTime();\n return Number.isNaN(difference) ? undefined : difference;\n }\n if (typeof value === 'number' && typeof bound === 'number') {\n return Number.isNaN(value) || Number.isNaN(bound) ? undefined : value - bound;\n }\n if (\n (typeof value === 'string' && typeof bound === 'string') ||\n (typeof value === 'bigint' && typeof bound === 'bigint')\n ) {\n if (value < bound) return -1;\n return value > bound ? 1 : 0;\n }\n return undefined;\n}\n","import { truncate } from 'lodash-es';\nimport { type Ref, unref } from 'vue';\n\nimport { ValidationErrorOptions, ValidationFunction, Validator } from './validator';\nimport { isEmptyValue } from './value-checks';\n\n/**\n * The values a field may hold: a fixed list, or a ref or a callback for a list that is filled or replaced after\n * the validator is built (options returned by a server, or the options another field's value allows).\n */\nexport type AllowedValues<T> = T[] | Ref<T[]> | (() => T[]);\n\nexport default class InAllowedValues<T = any> extends Validator {\n constructor(allowedValues: AllowedValues<T>, options?: ValidationErrorOptions) {\n // the list is read at each validation, not at construction, so a list set later is the one the value is\n // checked against and the one the error lists\n const resolve = (): T[] => {\n const values = unref(allowedValues);\n return typeof values === 'function' ? values() : values;\n };\n const asText = (values: T[]): string => {\n const text = values.join(', ');\n if (text.length <= 60) return text;\n return truncate(text, { length: 40, separator: ', ', omission: `... (${values.length} items total)` });\n };\n\n const validationFn: ValidationFunction = (newValue: T, oldValue: T) => {\n if (isEmptyValue(unref(newValue))) return null;\n const values = resolve();\n if (!values.includes(unref(newValue))) {\n return [\n this.errorFor(options, 'in_allowed_values', 'Must be one of [{allowedAsText}]', {\n newValue,\n oldValue,\n allowedValues: values,\n allowedAsText: asText(values),\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { isString } from 'lodash-es';\nimport { unref } from 'vue';\n\nimport { ValidationErrorOptions, ValidationFunction, Validator } from './validator';\nimport { toLength } from './value-checks';\n\n/** How the value is read before its length is measured, and the error's code and detail. */\nexport type RequiredOptions = ValidationErrorOptions & {\n /**\n * Whether a string is trimmed before it is measured, so that whitespace alone counts as no value. Defaults to\n * true. Set it to false if spaces are part of the field's value.\n */\n trim?: boolean;\n};\n\nexport default class Required extends Validator {\n constructor(options?: RequiredOptions) {\n const trim = options?.trim ?? true;\n const validationFn: ValidationFunction = (newValue, oldValue) => {\n const value = unref(newValue);\n if (toLength(trim && isString(value) ? value.trim() : value) === 0) {\n return [this.errorFor(options, 'required', 'Please enter a value', { newValue, oldValue })];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { ValidationErrorOptions, ValidationFunction, Validator } from './validator';\nimport { compareValues, isEmptyValue } from './value-checks';\n\nexport class MinValue<T = any> extends Validator {\n constructor(minValue: T, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue: T, oldValue: T) => {\n if (isEmptyValue(newValue)) return null;\n const below = compareValues(newValue, minValue);\n if (below === undefined || below < 0) {\n return [\n this.errorFor(options, 'min_value', 'Value must be larger or equal to {minValue}', {\n newValue,\n oldValue,\n minValue,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class MaxValue<T = any> extends Validator {\n constructor(maxValue: T, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue: T, oldValue: T) => {\n if (isEmptyValue(newValue)) return null;\n const above = compareValues(newValue, maxValue);\n if (above === undefined || above > 0) {\n return [\n this.errorFor(options, 'max_value', 'Value must be less than or equal to {maxValue}', {\n newValue,\n oldValue,\n maxValue,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class ValueInRange<T = any> extends Validator {\n constructor(minValue: T, maxValue: T, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue: T, oldValue: T) => {\n if (isEmptyValue(newValue)) return null;\n const below = compareValues(newValue, minValue);\n const above = compareValues(newValue, maxValue);\n if (below === undefined || above === undefined || below < 0 || above > 0) {\n return [\n this.errorFor(options, 'value_in_range', 'Value must be between {minValue} and {maxValue}', {\n newValue,\n oldValue,\n minValue,\n maxValue,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { ValidationErrorOptions, ValidationFunction, Validator } from './validator';\nimport { isEmptyValue, toLength } from './value-checks';\n\nexport class MinLength extends Validator {\n constructor(minLength: number, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue, oldValue) => {\n if (isEmptyValue(newValue)) return null;\n if (toLength(newValue) < minLength) {\n return [\n this.errorFor(options, 'min_length', 'Length must be larger or equal to {minLength}', {\n newValue,\n oldValue,\n minLength,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class MaxLength extends Validator {\n constructor(maxLength: number, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue, oldValue) => {\n if (isEmptyValue(newValue)) return null;\n if (toLength(newValue) > maxLength) {\n return [\n this.errorFor(options, 'max_length', 'Length must be less than or equal to {maxLength}', {\n newValue,\n oldValue,\n maxLength,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n\nexport class LengthInRange extends Validator {\n constructor(minLength: number, maxLength: number, options?: ValidationErrorOptions) {\n const validationFn: ValidationFunction = (newValue, oldValue) => {\n if (isEmptyValue(newValue)) return null;\n const len = toLength(newValue);\n if (len < minLength || len > maxLength) {\n return [\n this.errorFor(options, 'length_in_range', 'Length must be between {minLength} and {maxLength}', {\n newValue,\n oldValue,\n minLength,\n maxLength,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { unref } from 'vue';\n\nimport { ValidationErrorOptions, ValidationFunction, Validator } from './validator';\nimport { isEmptyValue } from './value-checks';\n\nexport default class Pattern extends Validator {\n constructor(pattern: RegExp, options?: ValidationErrorOptions) {\n // a `g` or `y` flag makes `test()` resume from the end of the previous match, so the same value would pass and\n // fail in turn; the validator tests with a copy without them and leaves the caller's expression as it is\n const tester = /[gy]/.test(pattern.flags)\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''))\n : pattern;\n const validationFn: ValidationFunction = (newValue, oldValue) => {\n const value = unref(newValue);\n if (isEmptyValue(value)) return null;\n if (!tester.test(String(value))) {\n return [\n this.errorFor(options, 'pattern', 'Value must match pattern \"{pattern}\"', {\n newValue,\n oldValue,\n pattern,\n }),\n ];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","export * from './validator';\nexport { default as CompareTo, type CompareToTarget } from './validator-compare-to';\nexport { default as InAllowedValues, type AllowedValues } from './validator-in-allowed-values';\nexport { default as Required, type RequiredOptions } from './validator-required';\nexport * from './validator-min-max-range';\nexport * from './validator-min-max-range-length';\nexport { default as Pattern } from './validator-pattern';\nexport { isEmptyValue } from './value-checks';\n","import { Container } from './container';\nimport { ReorderRows } from './element-state';\nimport { FieldBase } from './field-base';\nimport { type GenericFieldsInterface, Group } from './group';\nimport { List } from './list';\nimport { transaction } from './transaction';\n\n/** the type a view returns for a member: the view of a container, the value of any other element */\ntype Slot<E> = E extends Container ? View<E> : E extends FieldBase ? E['value'] : never;\n\n/** the data keys of a group's view */\ntype GroupData<F extends GenericFieldsInterface> = {\n // a container's value is assigned through `$.value`, so its key is read-only; a field's key reads and writes\n // its value\n readonly [K in keyof F as F[K] extends Container ? K : never]: Slot<F[K]>;\n} & {\n -readonly [K in keyof F as F[K] extends Container ? never : K]: Slot<F[K]>;\n};\n\n/** what a list's view accepts as a row: the data a row is built from, an element, or the view of one */\ntype RowInput<R extends FieldBase> = R['value'] | R | View<R>;\n\n/** the type of a list's view: every array read, and the mutations performed as the list's own operations */\ntype ListData<R extends FieldBase> = Omit<Slot<R>[], 'push' | 'unshift' | 'splice' | 'fill' | 'copyWithin'> & {\n push(...items: RowInput<R>[]): number;\n unshift(...items: RowInput<R>[]): number;\n splice(start: number, deleteCount?: number, ...items: RowInput<R>[]): Slot<R>[];\n};\n\n/**\n * An element presented as its data: the members of a group, or the rows of a list, as plain properties, and the\n * element itself as `$`. See `view()`.\n */\nexport type View<E extends FieldBase> = (E extends Group<infer F, any>\n ? GroupData<F>\n : E extends List<infer R, any>\n ? ListData<R>\n : unknown) & { readonly $: E };\n\n/** the views created so far, one per element, and the element of each */\nconst views = new WeakMap<FieldBase, object>();\nconst elements = new WeakMap<object, FieldBase>();\n\n/** the array methods that move rows: a view performs them as the list's own operations, keeping the row elements */\nconst listMutations = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin']);\n\nfunction isIndex(key: string | symbol): key is string {\n return typeof key === 'string' && /^(0|[1-9]\\d*)$/.test(key);\n}\n\n/** the element of a view, or the argument itself if it is not a view */\nfunction unwrap<T>(item: T): T | FieldBase {\n return (typeof item === 'object' && item !== null && elements.get(item as object)) || item;\n}\n\n/** a member read through a view: a container as its view, anything else as its value */\nfunction slotOf(element: FieldBase): unknown {\n return element instanceof Container ? view(element) : element.value;\n}\n\n/** writes a member through a view: its value, whatever it is */\nfunction writeSlot(element: FieldBase, value: unknown): void {\n element.value = unwrap(value) instanceof FieldBase ? (unwrap(value) as FieldBase).value : value;\n}\n\n/** the keys a view handles for Vue and the language, not as data */\nfunction special(key: string | symbol): { answered: boolean; value?: unknown } {\n // reactive() returns the view unwrapped, and a template reads through it: every read already reaches the tracked\n // state of the view's element\n if (key === '__v_skip') return { answered: true, value: true };\n if (typeof key === 'string' && key.startsWith('__v_')) return { answered: true, value: undefined };\n // a view is not a thenable: `await` returns it unchanged\n if (key === 'then') return { answered: true, value: undefined };\n return { answered: false };\n}\n\nfunction groupHandler(group: Group<any, any>): ProxyHandler<object> {\n const memberOf = (key: string | symbol) =>\n typeof key === 'string' && key !== '$' ? (group.field(key) ?? undefined) : undefined;\n const dataKeys = () => Object.keys(group.fields);\n return {\n get(target, key) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return group;\n if (key === Symbol.toStringTag) return 'View';\n const element = memberOf(key);\n return element ? slotOf(element) : undefined;\n },\n set(target, key, value) {\n if (key === '$') throw new TypeError('$ is the element a view stands for, and cannot be replaced');\n const element = memberOf(key);\n if (!element) throw new TypeError(`${String(key)} is not a member of this group - use $.addField() to add one`);\n writeSlot(element, value);\n return true;\n },\n has(target, key) {\n return key === '$' || (typeof key === 'string' && dataKeys().includes(key));\n },\n ownKeys() {\n return dataKeys();\n },\n getOwnPropertyDescriptor(target, key) {\n if (typeof key !== 'string' || !dataKeys().includes(key)) return undefined;\n return { value: slotOf(group.fields[key]), writable: true, enumerable: true, configurable: true };\n },\n deleteProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be deleted from a view - use $.removeField() to take a member out`);\n },\n defineProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be defined on a view`);\n },\n };\n}\n\nfunction listView(list: List<any, any>): unknown[] {\n // the rows a view shows, in order: every row the list holds, whatever it sends\n // the rows the view shows: every row, in the frozen array `items` keeps until the set of rows changes, so a read\n // of an index or of `length` costs no copy\n const shown = (): readonly FieldBase[] => list.items;\n // the list position of a view index; an index past the last row appends\n const positionOf = (index: number): number => Math.min(index, list.length);\n const clamp = (index: number, length: number) => (index < 0 ? Math.max(length + index, 0) : Math.min(index, length));\n\n /** replaces the shown rows with `rows`, keeping every row element and its state */\n const reorder = (rows: FieldBase[]) =>\n transaction(() => {\n list[ReorderRows](rows);\n });\n\n const mutations: Record<string, (...args: any[]) => unknown> = {\n push: (...items: unknown[]) => {\n transaction(() => items.forEach((item) => list.push(unwrap(item))));\n return shown().length;\n },\n pop: () => {\n const rows = shown();\n if (!rows.length) return undefined;\n const slot = slotOf(rows[rows.length - 1]);\n list.remove(list.items.indexOf(rows[rows.length - 1]));\n return slot;\n },\n shift: () => {\n const rows = shown();\n if (!rows.length) return undefined;\n const slot = slotOf(rows[0]);\n list.remove(list.items.indexOf(rows[0]));\n return slot;\n },\n unshift: (...items: unknown[]) => {\n transaction(() => {\n const at = positionOf(0);\n items.forEach((item, offset) => list.insert(unwrap(item), at + offset));\n });\n return shown().length;\n },\n splice: (start: number, deleteCount?: number, ...items: unknown[]) => {\n const removed: unknown[] = [];\n transaction(() => {\n const rows = shown();\n const from = clamp(Math.trunc(start) || 0, rows.length);\n const count =\n deleteCount === undefined ? rows.length - from : Math.max(0, Math.min(deleteCount, rows.length - from));\n rows.slice(from, from + count).forEach((row) => {\n removed.push(slotOf(row));\n list.remove(list.items.indexOf(row));\n });\n const at = positionOf(from);\n items.forEach((item, offset) => list.insert(unwrap(item), at + offset));\n });\n return removed;\n },\n sort: (compare?: (a: unknown, b: unknown) => number) => {\n const rows = shown();\n const sorted = rows\n .map((row) => ({ row, slot: slotOf(row) }))\n .sort((a, b) => {\n if (compare) return compare(a.slot, b.slot);\n const x = String(a.slot);\n const y = String(b.slot);\n return x < y ? -1 : x > y ? 1 : 0;\n })\n .map(({ row }) => row);\n reorder(sorted);\n return proxy;\n },\n reverse: () => {\n reorder([...shown()].reverse());\n return proxy;\n },\n fill: () => {\n throw new TypeError('fill() is not available on a list view - assign $.value instead');\n },\n copyWithin: () => {\n throw new TypeError('copyWithin() is not available on a list view - assign $.value instead');\n },\n };\n\n let proxy: unknown[];\n const handler: ProxyHandler<unknown[]> = {\n get(target, key, receiver) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return list;\n if (key === 'length') return shown().length;\n if (isIndex(key)) {\n const row = shown()[Number(key)];\n return row ? slotOf(row) : undefined;\n }\n if (typeof key === 'string' && listMutations.has(key)) return mutations[key];\n // every other array member reads the view through its length and its indices\n return Reflect.get(target, key, receiver);\n },\n set(target, key, value) {\n if (key === '$') throw new TypeError('$ is the element a view stands for, and cannot be replaced');\n if (key === 'length') {\n const length = Number(value);\n const rows = shown();\n if (length > rows.length) throw new TypeError('a list view grows by push(), not by its length');\n transaction(() => rows.slice(length).forEach((row) => list.remove(list.items.indexOf(row))));\n return true;\n }\n if (isIndex(key)) {\n const index = Number(key);\n const rows = shown();\n if (index < rows.length) writeSlot(rows[index], value);\n else list.insert(unwrap(value), positionOf(rows.length) + (index - rows.length));\n return true;\n }\n throw new TypeError(`${String(key)} cannot be set on a list view`);\n },\n has(target, key) {\n if (key === '$' || key === 'length') return true;\n if (isIndex(key)) return Number(key) < shown().length;\n return Reflect.has(target, key);\n },\n ownKeys() {\n return [...shown().map((_, index) => String(index)), 'length'];\n },\n getOwnPropertyDescriptor(target, key) {\n if (key === 'length') return { value: shown().length, writable: true, enumerable: false, configurable: false };\n if (!isIndex(key) || Number(key) >= shown().length) return undefined;\n return { value: slotOf(shown()[Number(key)]), writable: true, enumerable: true, configurable: true };\n },\n deleteProperty() {\n throw new TypeError('rows cannot be deleted from a list view - use splice() or pop()');\n },\n defineProperty(target, key) {\n throw new TypeError(`${String(key)} cannot be defined on a list view`);\n },\n };\n proxy = new Proxy<unknown[]>([], handler);\n return proxy;\n}\n\nfunction fieldHandler(field: FieldBase): ProxyHandler<object> {\n return {\n get(target, key) {\n const answered = special(key);\n if (answered.answered) return answered.value;\n if (key === '$') return field;\n return undefined;\n },\n set(target, key) {\n throw new TypeError(`${String(key)} cannot be set on the view of a field - its value is $.value`);\n },\n has(target, key) {\n return key === '$';\n },\n ownKeys() {\n return [];\n },\n };\n}\n\n/** throws for a group member whose name a view cannot expose as a data key */\nfunction refuseReservedNames(group: Group<any, any>): void {\n Object.keys(group.fields).forEach((name) => {\n if (name === '$' || name === 'then' || name.startsWith('__v_')) {\n throw new TypeError(\n `A view cannot hold a member named ${name}: $ is the element the view stands for, and then and __v_* ` +\n 'are read by the language and by Vue',\n );\n }\n });\n}\n\n/**\n * Returns the element presented as its data. A group's members and a list's rows are plain properties of the view\n * (a field as its value, a container as its own view), and `$` is the element itself: `view.$.valid`,\n * `view.$.access = 'readonly'`, `view.$.registerAction(...)`.\n *\n * A member reads what the element holds, as in `fullValue`: every member is present whatever its access, so a\n * disabled field reads and writes like any other. Every read goes through the element's tracked state, so an\n * effect that reads `view.address.city` re-runs when that field changes and not when another one does.\n *\n * A list's view is an array: it reads like one, and `push`, `pop`, `shift`, `unshift`, `splice`, `sort` and\n * `reverse` are performed as the list's own operations, so every row keeps its element and its state.\n *\n * One element has one view: `view(element) === view(element)`, and `view()` of a view returns the same view.\n */\nexport function view<V extends View<any>>(of: V): V;\n// eslint-disable-next-line no-redeclare\nexport function view<E extends FieldBase>(element: E): View<E>;\n// eslint-disable-next-line no-redeclare\nexport function view<E extends FieldBase>(element: E): View<E> {\n if (elements.has(element)) return element as unknown as View<E>;\n const made = views.get(element);\n if (made) return made as View<E>;\n\n let proxy: object;\n if (element instanceof Group) {\n refuseReservedNames(element);\n proxy = new Proxy({}, groupHandler(element));\n } else if (element instanceof List) {\n proxy = listView(element);\n } else {\n proxy = new Proxy({}, fieldHandler(element));\n }\n views.set(element, proxy);\n elements.set(proxy, element);\n return proxy as View<E>;\n}\n","export { type Access, accessValues, defaultAccess, isAccess } from './access';\nexport { type Visibility, visibilityValues, defaultVisibility, isVisibility } from './visibility';\n\nexport * from './actions';\nexport * from './action';\nexport * from './container';\nexport {\n configureDevtools,\n describeState,\n type DevtoolsOptions,\n type DevtoolsRegistration,\n hideState,\n type StateDescription,\n} from './plugins/devtools/api';\nexport * from './field';\nexport * from './field.interface';\nexport * from './field-base';\nexport * from './group';\nexport * from './is-equal';\nexport * from './list';\nexport { installPlugin, type Plugin, type PluginContext } from './plugins';\n// the participation protocol symbols are not exported; consumers use the transaction() entry point\nexport { transaction, type TransactionControl } from './transaction';\nexport * from './validators';\nexport * from './view';\n","import * as Form from './index-individual';\n\nexport * from './index-individual';\n\nexport default Form;\n"],"mappings":";;;;;;;;;;;GAkBa,IAAkC,OAAO,OAAO;CAAC;CAAY;CAAY;CAAY;AAAe,CAAC,GAGrG,KAAwB;AAGrC,SAAgB,GAAS,GAAiC;CACxD,OAAQ,EAAoC,SAAS,CAAK;AAC5D;;;ACdA,IAAa,IAA0C,OAAO,OAAO;CAAC;CAAQ;CAAa;CAAU;AAAU,CAAC,GAGnG,KAAgC;AAG7C,SAAgB,GAAa,GAAqC;CAChE,OAAQ,EAAwC,SAAS,CAAK;AAChE;;;ACgBA,IAAI,KAAU,IACV,KAAW,IACX,IACA,KAAS;AAGb,SAAS,GAAK,GAA0B;CACtC,AAAK,KAOH,OAAY,8BAAW,CAAC,MAAM,MAAW,EAAO,WAAW,CAAO,CAAC,KANnE,KAAS,IACT,OAAY,8BAAW,CAAC,MAAM,MAAW;EAEvC,AADA,EAAO,QAAQ,GACf,EAAgB,CAAC,CAA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