@dynamicforms/vue-forms 3.0.0-alpha.1 → 3.0.0-alpha.3
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.
- package/dist/chunks/{plugin-uXEQYne6.js → plugin-Ds_2fb9G.js} +2 -2
- package/dist/chunks/{plugin-uXEQYne6.js.map → plugin-Ds_2fb9G.js.map} +1 -1
- package/dist/chunks/{registry-_vVZW3p9.js → registry-2GP2P-ie.js} +41 -41
- package/dist/chunks/registry-2GP2P-ie.js.map +1 -0
- package/dist/dynamicforms-vue-forms.js +578 -474
- package/dist/dynamicforms-vue-forms.js.map +1 -1
- package/dist/index.d.ts +87 -44
- package/package.json +4 -3
- package/readme.md +12 -9
- package/dist/chunks/registry-_vVZW3p9.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicforms-vue-forms.js","names":["#state","#raw"],"sources":["../src/access.ts","../src/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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C,IAAM,IAAO,GAAM,IAAI,CAAO;CAC9B,IAAI,GAAM,OAAO;CAEjB,IAAI;CAWJ,OAVI,aAAmB,KACrB,GAAoB,CAAO,GAC3B,IAAQ,IAAI,MAAM,CAAC,GAAG,GAAa,CAAO,CAAC,KACtC,AAGL,IAHS,aAAmB,KACpB,GAAS,CAAO,IAEhB,IAAI,MAAM,CAAC,GAAG,GAAa,CAAO,CAAC,GAE7C,GAAM,IAAI,GAAS,CAAK,GACxB,GAAS,IAAI,GAAO,CAAO,GACpB;AACT;;;AE9TA,IAAA,KAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA"}
|
|
1
|
+
{"version":3,"file":"dynamicforms-vue-forms.js","names":["#state","#raw"],"sources":["../src/access.ts","../src/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/error-namespace.ts","../src/validators/validation-error.ts","../src/validators/validator.ts","../src/actions/actions-map.ts","../src/resolve.ts","../src/weak-elements.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/view-names.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/**\n * Installs the devtools plugin unless it is installed or turned off, or there is no `window`: on a server the devtools\n * never show the registry, and an element rendered there is never unmounted, so it would keep its entry. Called on\n * every element's construction.\n */\nexport function installDevtools(): void {\n if (process.env.NODE_ENV !== 'production') {\n if (enabled && !uninstall && typeof window !== 'undefined') 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. Where `setup` throws, the plugin is not installed and the exception is rethrown.\n */\nexport function installPlugin(plugin: Plugin): () => void {\n installed.push(plugin);\n collect();\n const uninstall = () => {\n const index = installed.lastIndexOf(plugin);\n if (index < 0) return;\n installed.splice(index, 1);\n collect();\n };\n try {\n plugin.setup?.(context);\n } catch (error) {\n uninstall();\n throw error;\n }\n return uninstall;\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. The work runs after the transaction is closed, so a write it makes opens a transaction of its own.\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 }\n\n /**\n * Runs the work registered with whenCommitted, then the `onCommit` hooks. It is called after the transaction is\n * closed, so a write made here opens a transaction of its own and is announced, and an exception does not roll\n * back the committed change. Every step runs; the first exception thrown is rethrown after the last one.\n */\n settle(): void {\n let failed = false;\n let failure: unknown;\n const attempt = (work: () => void) => {\n try {\n work();\n } catch (error) {\n if (!failed) failure = error;\n failed = true;\n }\n };\n for (let index = 0; index < this.settled.length; index++) attempt(this.settled[index]);\n this.settled.length = 0;\n attempt(committed);\n if (failed) throw failure;\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 let result: R;\n try {\n result = fn(handle);\n rejectThenable(result);\n if (handle.rollbackRequested) throw new RollbackSignal();\n tx.commit();\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 tx.settle();\n return result;\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\n/**\n * Names a method of a listener a rule installs on an element outside the rule's own elements. The method removes\n * the listener, from every element it is installed on, if every element the rule applies to has been collected.\n * An element that registers an action calls it on the actions registered there, at most once a minute. The package\n * does not export it.\n */\nexport const ReleaseIfAbandoned = Symbol('FieldActionBase.releaseIfAbandoned');\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 /**\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 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/**\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","/**\n * The namespace of the error codes this library declares. A code the library raises is `${ERROR_NAMESPACE}.<code>`,\n * such as `vue-forms.required`.\n */\nexport const ERROR_NAMESPACE = 'vue-forms';\n\n/** The full code of `code`, an error code this library declares. */\nexport function namespaced(code: string): string {\n return `${ERROR_NAMESPACE}.${code}`;\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 /**\n * Machine-readable identifier of what failed: `<namespace>.<code>`, such as `vue-forms.min_value`. The namespace\n * names the package that declared the code.\n */\n readonly code: string;\n /** The values of the failure, such as `minValue` for `vue-forms.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, `<namespace>.<code>`. Stored as given.\n * @param params The values of the failure, such as `minValue` for `vue-forms.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 } from '../element-state';\nimport { type FieldBase } from '../field-base';\nimport { FieldActionExecute } from '../field.interface';\nimport { currentTransaction, SentNowhere, transaction, transactional } from '../transaction';\n\nimport { namespaced } from './error-namespace';\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 /**\n * The error's `code`, used as given. Defaults to the validator's own, such as `vue-forms.required`. The\n * application prefixes its own codes with a namespace of its own.\n */\n code?: string;\n detail?: never;\n }\n | {\n /** The error's `code`, used as given. */\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 // 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 validator was not removed from the\n // field (a committed removal advances the run number), the change that started it was not rolled back, and the\n // run was not cancelled\n let abandoned = false;\n const isCurrent = () => !abandoned && runs.run === run && !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 `vue-forms.validation_failed` error, so the field\n // is 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([\n new ValidationError(namespaced('validation_failed'), {}, 'Validation could not be completed'),\n ]);\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 the run, still active, then applies its result. Cancelling at the removal would leave the field\n * valid over an unchecked value after a rollback. A run started after the removal, by registering the validator\n * again in the same transaction, is not cancelled.\n */\n unregisterFrom(field: FieldBase) {\n transactional((tx) => {\n const runs = this.bindingState(field);\n const removedAt = runs.run;\n tx.whenCommitted(() => {\n if (runs.run === removedAt) this.abandonRun(field);\n });\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 once the validator's removal from the\n * field is committed: the run number advances, so the run's result is discarded and its signal aborts. The other\n * validators of the field keep their runs.\n */\n protected abandonRun(field: FieldBase): void {\n const runs = this.bindingState(field);\n runs.run++;\n runs.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. Both codes are used as given: a built-in validator passes\n * its own code as `vue-forms.<code>`, and a subclass of the application passes a code in a namespace of its own.\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. Registering and unregistering replace the array instead of\n * modifying it, so a run in progress finishes on the array it started with, the change takes effect from the next\n * trigger, and an array read through `registrations` never changes.\n */\n private actions: readonly FieldActionBase[] = [];\n\n /**\n * The registered actions, in registration order. The array is not modified later, so it records the\n * registrations at the time of the read; `restore()` reinstates them.\n */\n get registrations(): readonly FieldActionBase[] {\n return this.actions;\n }\n\n /**\n * Replaces the registered actions with `registrations`, an array `registrations` returned earlier. The order of\n * the handlers and every duplicate registration are restored with it.\n */\n restore(registrations: readonly FieldActionBase[]): void {\n this.actions = registrations;\n }\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 = ActionsMap.inserted(this.actions, at, 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 this.actions = ActionsMap.inserted(this.actions, pinned < 0 ? this.actions.length : pinned, action);\n }\n\n /** A copy of `actions` with `action` inserted at `index`. */\n private static inserted(actions: readonly FieldActionBase[], index: number, action: FieldActionBase) {\n return [...actions.slice(0, index), action, ...actions.slice(index)];\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: readonly 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: readonly 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","/**\n * A set of objects held weakly that can be iterated: an object is released when nothing else references it, and\n * `alive` returns the ones that remain. A rule that applies to the elements of several declarations holds them in\n * one, so a form that is dropped without its rules being unregistered is released even while the rule stays\n * reachable through a listener on an element outside the form.\n */\nexport class WeakElements<T extends object> {\n private readonly refs = new Set<WeakRef<T>>();\n\n private readonly byElement = new WeakMap<T, WeakRef<T>>();\n\n add(element: T): void {\n if (this.byElement.has(element)) return;\n const ref = new WeakRef(element);\n this.byElement.set(element, ref);\n this.refs.add(ref);\n }\n\n has(element: T): boolean {\n return this.byElement.has(element);\n }\n\n delete(element: T): boolean {\n const ref = this.byElement.get(element);\n if (!ref) return false;\n this.byElement.delete(element);\n this.refs.delete(ref);\n return true;\n }\n\n /** The objects that are still referenced, in the order they were added; removes the references to the others. */\n get alive(): T[] {\n const found: T[] = [];\n this.refs.forEach((ref) => {\n const element = ref.deref();\n if (element) found.push(element);\n else this.refs.delete(ref);\n });\n return found;\n }\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 { WeakElements } from '../../weak-elements';\nimport { Outermost, ReleaseIfAbandoned } 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 is 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. They are held weakly: the relay on a field the statement reads keeps this\n * action reachable, and a form dropped without unregistering the action is released all the same.\n */\n private readonly declarations = new WeakElements<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 // the relay outlives the action's elements when the statement reads a field outside them; a field the relay is\n // registered on asks the action to remove it once they are all collected\n (this.relay as any)[ReleaseIfAbandoned] = () => {\n if (this.bound && this.declarations.alive.length === 0) this.stopListening();\n };\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 or its elements are collected, and installed again when the action is next\n * registered.\n */\n private readonly relay: ValueChangedAction;\n\n private listening = false;\n\n /** Whether the action has been registered on an element; until then the relay waits for its first element. */\n private bound = 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 /** Removes the relay from the fields the statement reads; a rollback restores it with the flag. */\n private stopListening(): void {\n if (!this.listening) return;\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 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 this.bound = true;\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 this.registrations.delete(binding);\n // the declaration itself is released when the action leaves its map, which every binding of it reads; a rollback\n // binds the action to the declaration again, which adds it back\n if (binding === binding.declaration) this.declarations.delete(binding);\n // taken off the last declaration, the action has nothing left to apply, and the listener it installed on the\n // fields the statement reads is removed with it\n if (this.declarations.alive.length === 0) this.stopListening();\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.alive.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, { ReleaseIfAbandoned } 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} 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 { isVisibility, type Visibility, visibilityValues } from './visibility';\n\n/** The references to the bindings made from one declaration, and when the dead ones were last removed. */\ninterface BindingsMade {\n refs: Set<WeakRef<FieldBase>>;\n sweptAt: number;\n}\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, BindingsMade>();\n\n/**\n * Milliseconds between two removals of dead references when a declaration records a binding. A reference whose\n * binding was collected is removed by the next recording after the interval, so the set of a declaration that\n * keeps making bindings holds at most the references recorded within one interval besides the live ones. No timer\n * is involved: a declaration that records nothing keeps its set until its next recording or registration.\n */\nconst SWEEP_INTERVAL = 60_000;\n\n/** When each map of actions last released its abandoned actions; a map has no entry before its first registration. */\nconst abandonedReleasedAt = new WeakMap<ActionsMap, number>();\n\n/** Removes the references whose binding was collected and returns the live bindings. */\nfunction sweep(made: BindingsMade): FieldBase[] {\n const alive: FieldBase[] = [];\n made.refs.forEach((ref) => {\n const binding = ref.deref();\n if (!binding) made.refs.delete(ref);\n else alive.push(binding);\n });\n made.sweptAt = Date.now();\n return alive;\n}\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 = { refs: new Set(), sweptAt: Date.now() };\n bindingsMade.set(this, made);\n } else if (Date.now() - made.sweptAt >= SWEEP_INTERVAL) {\n sweep(made);\n }\n made.refs.add(new WeakRef(binding));\n }\n\n /** The live bindings made from this element's declaration and the declaration; removes the dead references. */\n protected get boundElements(): FieldBase[] {\n const declaration = this.declaration;\n const made = bindingsMade.get(declaration);\n return made ? [declaration, ...sweep(made)] : [declaration];\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. A container cannot take itself or a container above it, which also throws a\n * TypeError: the parent links would form a cycle, and a walk up them would not end. The child's state is private\n * to FieldBase, so a container writes the two 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 if (child === this) throw new TypeError('A container cannot hold itself or a container above it');\n for (let ancestor = this.parent; ancestor; ancestor = ancestor.parent) {\n if (ancestor === child) throw new TypeError('A container cannot hold itself or a container above it');\n }\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.register(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.register(tx, action, before);\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 const previous = actions.registrations;\n dropped = actions.unregister(action);\n if (!dropped) return;\n // the action served the declaration and every binding made from it, so it is released from all of them. The\n // undo restores the registrations as they were, so the handlers keep their order and a duplicate registration\n // of the instance is restored too\n const elements = this.boundElements;\n tx.whenRolledBack(() => {\n actions.restore(previous);\n elements.forEach((element) => action.boundToBinding(element));\n });\n elements.forEach((element) => action.unregisterFrom(element));\n });\n return dropped;\n }\n\n /**\n * Registers `action` on the declaration, binds it to the existing bindings and registers an undo for a rollback.\n * The registration is not in the state slots the snapshot covers, so it registers its own undo, before any call\n * that can throw: a registration that fails part way is undone with the transaction.\n */\n private register(tx: Transaction, action: FieldActionBase, before?: FieldActionBase): void {\n const actions = this.actions;\n this.releaseAbandoned(actions);\n const previous = actions.registrations;\n const elements = this.boundElements;\n tx.whenRolledBack(() => {\n // only a registration that was made is released: one the map refused added nothing, and an instance that was\n // already registered keeps what it put on the elements\n const added = actions.registrations.includes(action) && !previous.includes(action);\n actions.restore(previous);\n if (added) elements.forEach((element) => action.unregisterFrom(element));\n });\n actions.register(action, before);\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 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 actions.triggerEagerFor(action.classIdentifier, element, element.contribution, element.originalValue);\n }\n });\n }\n\n /**\n * Asks the actions of `actions` to release themselves if abandoned (see `ReleaseIfAbandoned`), if a minute or more\n * has passed since the last time. A map is checked only when an action is registered on it, with no timer.\n */\n private releaseAbandoned(actions: ActionsMap): void {\n const now = Date.now();\n const releasedAt = abandonedReleasedAt.get(actions);\n if (releasedAt !== undefined && now - releasedAt < SWEEP_INTERVAL) return;\n abandonedReleasedAt.set(actions, now);\n if (releasedAt === undefined) return;\n actions.registrations.forEach((registered) => (registered as any)[ReleaseIfAbandoned]?.());\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 clearValidators(): void {\n transactional((tx) => {\n tx.touch(this);\n const actions = this.boundActions;\n if (actions) {\n const previous = actions.registrations;\n const validators = actions.validators;\n const elements = this.boundElements;\n validators.forEach((validator) => actions.unregister(validator));\n tx.whenRolledBack(() => {\n actions.restore(previous);\n validators.forEach((validator) => elements.forEach((element) => validator.boundToBinding(element)));\n });\n // each validator removes the errors it put on every element it validated. Each release names the element,\n // because the same instance stays registered on elements of other declarations\n validators.forEach((validator) => elements.forEach((element) => validator.unregisterFrom(element)));\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\n/**\n * Throws a RangeError for an index that is not an integer. A fraction, NaN or an infinite index has no row position:\n * the row array would place it at one position while the announced index names another, and an infinite index\n * would add padding rows without end.\n */\nfunction refuseIndex(index: number, method: string): void {\n if (!Number.isInteger(index)) throw new RangeError(`List.${method}(): the index must be an integer, got ${index}`);\n}\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 refuseIndex(index, 'remove');\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 refuseIndex(index, 'insert');\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","/** The groups a view has been made for: their members are data keys of the view, so a member name is checked. */\nexport const viewedGroups = new WeakSet<object>();\n\n/** Throws a TypeError for a member name a view cannot expose as a data key. */\nexport function refuseReservedName(name: string): void {\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","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';\nimport { refuseReservedName, viewedGroups } from './view-names';\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 if (viewedGroups.has(this)) refuseReservedName(fieldName);\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 // the undo reinstates every entry, so the member returns to its position: the order of the map is the order\n // of `fields`, of the keys of `value` and of the writes a group value makes\n const entries = Object.entries(this._fields);\n Group.dropEntry(this._fields, fieldName);\n tx.whenRolledBack(() => Group.restoreEntries(this._fields, entries));\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 /** Replaces the entries of the member map with `entries`, in their order. */\n private static restoreEntries(fields: GenericFieldsInterface, entries: [string, FieldBase][]): void {\n Object.keys(fields).forEach((name) => Group.dropEntry(fields, name));\n entries.forEach(([name, field]) => Group.setEntry(fields, name, field));\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 { ReleaseIfAbandoned } from '../actions/field-action-base';\nimport type { FieldBase } from '../field-base';\nimport { bindingsIn, resolveByName, resolveInScope, scopeOf } from '../resolve';\nimport { currentTransaction } from '../transaction';\nimport { WeakElements } from '../weak-elements';\n\nimport { namespaced } from './error-namespace';\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 declarations of the elements this validator has installed its listener on. A registration goes into the map\n * of the element's declaration, which every binding of it uses, so a list of N rows installs one listener, not N.\n */\n private readonly listening = new WeakElements<FieldBase>();\n\n /**\n * The declarations of the fields this validator is 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 * They are held weakly: the listener on the compared element keeps this validator reachable, and a form dropped\n * without unregistering the validator is released all the same.\n */\n private readonly declarations = new WeakElements<FieldBase>();\n\n /**\n * The listener on the compared elements, one instance for all of them. It is removed when the validator is taken\n * off its last declaration, or, once its declarations are collected, when an element it is registered on asks it\n * to release itself.\n */\n private readonly relay: ValueChangedAction;\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, namespaced('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 this.relay = new ValueChangedAction((oField, supr, oNewValue, oOldValue) => {\n supr(oField, oNewValue, oOldValue);\n const scope = scopeOf(oField);\n this.declarations.alive.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 (this.relay as any)[ReleaseIfAbandoned] = () => {\n if (this.declarations.alive.length === 0) this.stopListening();\n };\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.declaration)) return;\n this.listening.add(other.declaration);\n other.registerAction(this.relay);\n }\n\n /** Removes the listener from every compared element; a rollback restores it and the record of the elements. */\n private stopListening(): void {\n const listening = this.listening.alive;\n if (listening.length === 0) return;\n currentTransaction()?.whenRolledBack(() => listening.forEach((element) => this.listening.add(element)));\n listening.forEach((element) => {\n this.listening.delete(element);\n element.unregisterAction(this.relay);\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 // the declaration itself is released when the validator leaves its map, which every binding of it reads; a\n // rollback binds the validator to the declaration again, which adds it back. Off its last declaration, the\n // validator has nothing to revalidate, and its listener is removed from the compared elements\n if (binding === binding.declaration) this.declarations.delete(binding);\n if (this.declarations.alive.length === 0) this.stopListening();\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 { namespaced } from './error-namespace';\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, namespaced('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 { namespaced } from './error-namespace';\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, namespaced('required'), 'Please enter a value', { newValue, oldValue })];\n }\n return null;\n };\n\n super(validationFn);\n }\n}\n","import { namespaced } from './error-namespace';\nimport { 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, namespaced('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, namespaced('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, namespaced('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 { namespaced } from './error-namespace';\nimport { 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, namespaced('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, namespaced('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, namespaced('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 { namespaced } from './error-namespace';\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, namespaced('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';\nimport { refuseReservedName, viewedGroups } from './view-names';\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/** an argument read as an integer, as array methods read it: NaN is 0, a fraction is truncated toward 0 */\nfunction toInteger(value: unknown): number {\n const number = Math.trunc(Number(value));\n return Number.isNaN(number) ? 0 : number;\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 // the arguments are read as Array.prototype.splice reads them: no argument removes nothing, a start alone\n // removes to the end, and an explicit undefined count is 0\n splice: (...args: unknown[]) => {\n const [start, deleteCount, ...items] = args;\n const removed: unknown[] = [];\n transaction(() => {\n const rows = shown();\n const from = clamp(toInteger(start), rows.length);\n let count = 0;\n if (args.length === 1) count = rows.length - from;\n else if (args.length > 1) count = Math.max(0, Math.min(toInteger(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 // the lengths an array accepts: an integer from 0 to 2^32 - 1\n if (!Number.isInteger(length) || length < 0 || length > 2 ** 32 - 1)\n throw new RangeError('Invalid array length');\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/**\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 Object.keys(element.fields).forEach(refuseReservedName);\n // a member added later is checked by addField()\n viewedGroups.add(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,KAA0C,OAAO,OAAO;CAAC;CAAQ;CAAa;CAAU;AAAU,CAAC,GAGnG,KAAgC;AAG7C,SAAgB,GAAa,GAAqC;CAChE,OAAQ,GAAwC,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,CAAC,SAAS,EAAE,SAAS,QAAa,EAAO,WAAW,CAAM,CAAC;CAC9E,CAAC;AAIL;AAEA,IAAM,KAAmB;CACvB,MAAM,GAAS;EACb,EAAoB,CAAO;CAC7B;CACA,iBAAiB,GAAS,GAAS;EAE7B,MACJ,EAAqB,GAAS,EAAQ,GACtC,GAAK,CAAO;CACd;CACA,iBAAiB,GAAS;EACxB,EAAwB,CAAO;CACjC;CACA,WAAW;EACT,EAAoB;CACtB;AACF;AAOA,SAAgB,KAAwB;CACtC,AAAA,QAAA,IAAA,aAA6B,gBACvB,MAAW,CAAC,MAAa,OAAO,SAAW,QAAa,KAAY,GAAc,EAAQ;AAElG;AAMA,S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