@ng-forge/dynamic-forms 0.3.1 → 0.5.0
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/README.md +5 -1
- package/fesm2022/ng-forge-dynamic-forms-integration.mjs +37 -66
- package/fesm2022/ng-forge-dynamic-forms-integration.mjs.map +1 -1
- package/fesm2022/{ng-forge-dynamic-forms-ng-forge-dynamic-forms-D58rojQc.mjs → ng-forge-dynamic-forms-ng-forge-dynamic-forms-WGww2nXx.mjs} +3572 -346
- package/fesm2022/ng-forge-dynamic-forms-ng-forge-dynamic-forms-WGww2nXx.mjs.map +1 -0
- package/fesm2022/{ng-forge-dynamic-forms-page-field.component-m35XgkkL.mjs → ng-forge-dynamic-forms-page-field.component-CrO9WTDw.mjs} +5 -5
- package/fesm2022/{ng-forge-dynamic-forms-page-field.component-m35XgkkL.mjs.map → ng-forge-dynamic-forms-page-field.component-CrO9WTDw.mjs.map} +1 -1
- package/fesm2022/ng-forge-dynamic-forms-schema.mjs +92 -0
- package/fesm2022/ng-forge-dynamic-forms-schema.mjs.map +1 -0
- package/fesm2022/{ng-forge-dynamic-forms-text-field.component-CfDZFTyf.mjs → ng-forge-dynamic-forms-text-field.component-BcFx_kOz.mjs} +5 -5
- package/fesm2022/{ng-forge-dynamic-forms-text-field.component-CfDZFTyf.mjs.map → ng-forge-dynamic-forms-text-field.component-BcFx_kOz.mjs.map} +1 -1
- package/fesm2022/ng-forge-dynamic-forms.mjs +1 -1
- package/package.json +13 -12
- package/types/ng-forge-dynamic-forms-integration.d.ts +61 -32
- package/types/ng-forge-dynamic-forms-schema.d.ts +178 -0
- package/types/ng-forge-dynamic-forms.d.ts +1173 -240
- package/fesm2022/ng-forge-dynamic-forms-ng-forge-dynamic-forms-D58rojQc.mjs.map +0 -1
- package/fesm2022/ng-forge-dynamic-forms-testing-test-button.harness-0iXHLraC.mjs +0 -31
- package/fesm2022/ng-forge-dynamic-forms-testing-test-button.harness-0iXHLraC.mjs.map +0 -1
- package/fesm2022/ng-forge-dynamic-forms-testing.mjs +0 -971
- package/fesm2022/ng-forge-dynamic-forms-testing.mjs.map +0 -1
- package/types/ng-forge-dynamic-forms-testing.d.ts +0 -597
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ng-forge-dynamic-forms-ng-forge-dynamic-forms-WGww2nXx.mjs","sources":["../../../../packages/dynamic-forms/src/lib/utils/derived-from-deferred/derived-from-deferred.ts","../../../../packages/dynamic-forms/src/lib/utils/grid-classes/grid-classes.ts","../../../../packages/dynamic-forms/src/lib/mappers/base/base-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/utils/field-mapper/field-mapper.ts","../../../../packages/dynamic-forms/src/lib/utils/resolve-field/resolve-field.ts","../../../../packages/dynamic-forms/src/lib/utils/submission-handler/submission-handler.ts","../../../../packages/dynamic-forms/src/lib/utils/object-utils.ts","../../../../packages/dynamic-forms/src/lib/models/field-signal-context.token.ts","../../../../packages/dynamic-forms/src/lib/errors/dynamic-form-error.ts","../../../../packages/dynamic-forms/src/lib/models/field-type.ts","../../../../packages/dynamic-forms/src/lib/utils/inject-field-registry/inject-field-registry.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/logger.token.ts","../../../../packages/dynamic-forms/src/lib/core/registry/root-form-registry.service.ts","../../../../packages/dynamic-forms/src/lib/core/registry/field-context-registry.service.ts","../../../../packages/dynamic-forms/src/lib/core/registry/function-registry.service.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/value-utils.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/types.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/tokenizer.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/parser.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/evaluator.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/expression-parser.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/condition-evaluator.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/logic-function-factory.ts","../../../../packages/dynamic-forms/src/lib/core/values/dynamic-value-factory.ts","../../../../packages/dynamic-forms/src/lib/models/logic/logic-config.ts","../../../../packages/dynamic-forms/src/lib/core/cross-field/cross-field-detector.ts","../../../../packages/dynamic-forms/src/lib/core/validation/validator-factory.ts","../../../../packages/dynamic-forms/src/lib/utils/debounce/debounce.ts","../../../../packages/dynamic-forms/src/lib/core/logic/logic-applicator.ts","../../../../packages/dynamic-forms/src/lib/core/registry/schema-registry.service.ts","../../../../packages/dynamic-forms/src/lib/core/values/type-predicate-factory.ts","../../../../packages/dynamic-forms/src/lib/core/schema-application.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/group-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/array-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/hidden-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/row-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/page-field.ts","../../../../packages/dynamic-forms/src/lib/core/form-mapping.ts","../../../../packages/dynamic-forms/src/lib/utils/default-value/default-value.ts","../../../../packages/dynamic-forms/src/lib/models/types/type-guards.ts","../../../../packages/dynamic-forms/src/lib/core/form-schema-merger.ts","../../../../packages/dynamic-forms/src/lib/core/schema-builder.ts","../../../../packages/dynamic-forms/src/lib/events/event.bus.ts","../../../../packages/dynamic-forms/src/lib/events/constants/submit.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/component-initialized.event.ts","../../../../packages/dynamic-forms/src/lib/utils/initialization-tracker/initialization-tracker.ts","../../../../packages/dynamic-forms/src/lib/models/types/form-mode.ts","../../../../packages/dynamic-forms/src/lib/utils/flattener/field-flattener.ts","../../../../packages/dynamic-forms/src/lib/core/cross-field/cross-field-collector.ts","../../../../packages/dynamic-forms/src/lib/utils/form-validation/form-mode-validator.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-constants.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-types.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-tokens.ts","../../../../packages/dynamic-forms/src/lib/utils/path-utils/path-utils.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-lookup.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-sorter.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-collector.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/cycle-detector.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-applicator.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-warning-tracker.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-logger.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-logger.service.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-orchestrator.ts","../../../../packages/dynamic-forms/src/lib/events/constants/next-page.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/page-change.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/previous-page.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/add-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/remove-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/form-reset.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/form-clear.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/page-navigation-state-change.event.ts","../../../../packages/dynamic-forms/src/lib/core/page-orchestrator/page-orchestrator.component.ts","../../../../packages/dynamic-forms/src/lib/providers/features/dynamic-form-feature.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/console-logger.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/noop-logger.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/with-logger-config.ts","../../../../packages/dynamic-forms/src/lib/dynamic-form.component.ts","../../../../packages/dynamic-forms/src/lib/mappers/array/array-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/group/group-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/row/row-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/page/page-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/text/text-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/providers/built-in-fields.ts","../../../../packages/dynamic-forms/src/lib/providers/dynamic-form-providers.ts","../../../../packages/dynamic-forms/src/lib/core/logic/button-logic-resolver.ts","../../../../packages/dynamic-forms/src/lib/definitions/base/base-value-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/base/base-checked-field.ts","../../../../packages/dynamic-forms/src/lib/events/utils/token-resolver.ts","../../../../packages/dynamic-forms/src/lib/helpers/form-config.ts","../../../../packages/dynamic-forms/src/lib/utils/dynamic-text-to-observable.ts","../../../../packages/dynamic-forms/src/lib/utils/apply-meta.ts","../../../../packages/dynamic-forms/src/lib/pipes/dynamic-text/dynamic-text.pipe.ts","../../../../packages/dynamic-forms/src/lib/utils/emit-initialization/emit-initialization.ts","../../../../packages/dynamic-forms/src/lib/fields/row/row-field.component.ts","../../../../packages/dynamic-forms/src/lib/fields/group/group-field.component.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/array-field.types.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/create-array-item-injector.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/resolve-array-item.ts","../../../../packages/dynamic-forms/src/lib/fields/array/array-field.component.ts","../../../../packages/dynamic-forms/src/lib/core/field-tree-utils.ts","../../../../packages/dynamic-forms/src/lib/utils/interpolate-params.ts","../../../../packages/dynamic-forms/src/lib/index.ts","../../../../packages/dynamic-forms/src/ng-forge-dynamic-forms.ts"],"sourcesContent":["import { Injector, isSignal, Signal } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { combineLatest, defer, Observable, OperatorFunction } from 'rxjs';\n\n/**\n * Type guard to check if a value is an array of Signals.\n * @internal\n */\nfunction isSignalArray(value: unknown): value is readonly Signal<unknown>[] {\n return Array.isArray(value) && value.every((item) => isSignal(item));\n}\n\n/**\n * Type guard to check if a value is a record (object) of Signals.\n * @internal\n */\nfunction isSignalRecord(value: unknown): value is Record<string, Signal<unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((item) => isSignal(item));\n}\n\n/**\n * Options for derivedFromDeferred.\n */\nexport interface DerivedFromDeferredOptions<R> {\n initialValue: R;\n injector: Injector;\n}\n\n/**\n * Type helper to extract the value type from a Signal.\n */\ntype SignalValue<T> = T extends Signal<infer V> ? V : never;\n\n/**\n * Type helper to map an array of Signals to an array of their value types.\n */\ntype SignalValues<T extends readonly Signal<unknown>[]> = {\n [K in keyof T]: SignalValue<T[K]>;\n};\n\n/**\n * Type helper to map an object of Signals to an object of their value types.\n */\ntype SignalObjectValues<T extends Record<string, Signal<unknown>>> = {\n [K in keyof T]: SignalValue<T[K]>;\n};\n\n/**\n * Like derivedFrom from ngxtension, but uses defer() to avoid input availability issues.\n * This ensures toObservable is called at subscription time, not at field initialization.\n *\n * Supports three source types:\n * - Single signal: `derivedFromDeferred(signal, operator, options)`\n * - Array of signals: `derivedFromDeferred([signal1, signal2], operator, options)`\n * - Object of signals: `derivedFromDeferred({a: signal1, b: signal2}, operator, options)`\n *\n * @example\n * ```typescript\n * // Single signal\n * const result = derivedFromDeferred(\n * mySignal,\n * pipe(map(v => v * 2)),\n * { initialValue: 0, injector }\n * );\n *\n * // Array of signals\n * const result = derivedFromDeferred(\n * [signalA, signalB],\n * pipe(map(([a, b]) => a + b)),\n * { initialValue: 0, injector }\n * );\n *\n * // Object of signals\n * const result = derivedFromDeferred(\n * { x: signalX, y: signalY },\n * pipe(map(({ x, y }) => x + y)),\n * { initialValue: 0, injector }\n * );\n * ```\n */\n\n// Overload: Single signal\nexport function derivedFromDeferred<T, R>(\n source: Signal<T>,\n operator: OperatorFunction<T, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Overload: Array of signals\nexport function derivedFromDeferred<T extends readonly Signal<unknown>[], R>(\n sources: [...T],\n operator: OperatorFunction<SignalValues<T>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Overload: Object of signals\nexport function derivedFromDeferred<T extends Record<string, Signal<unknown>>, R>(\n sources: T,\n operator: OperatorFunction<SignalObjectValues<T>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Implementation\nexport function derivedFromDeferred<T, R>(\n source: Signal<T> | Signal<unknown>[] | Record<string, Signal<unknown>>,\n operator: OperatorFunction<T | unknown[] | Record<string, unknown>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R> {\n const deferred$: Observable<R> = defer(() => {\n // Handle single signal\n if (isSignal(source)) {\n return toObservable(source, { injector: options.injector });\n }\n\n // Handle array of signals\n if (isSignalArray(source)) {\n const observables = source.map((s) => toObservable(s, { injector: options.injector }));\n return combineLatest(observables);\n }\n\n // Handle object of signals\n if (isSignalRecord(source)) {\n const keys = Object.keys(source);\n const observables = keys.map((key) => toObservable(source[key], { injector: options.injector }));\n\n return combineLatest(observables, (...values) => {\n const result: Record<string, unknown> = {};\n keys.forEach((key, index) => {\n result[key] = values[index];\n });\n return result;\n });\n }\n\n // Fallback - should not happen with proper typing\n throw new Error('Invalid source type. Expected a Signal, array of Signals, or object of Signals.');\n }).pipe(operator);\n\n return toSignal(deferred$, { initialValue: options.initialValue, injector: options.injector });\n}\n","import { FieldDef } from '../../definitions/base/field-def';\n\n/**\n * Generates CSS class string for responsive grid layout based on field column configuration.\n *\n * Creates Bootstrap-style column classes for implementing responsive form layouts.\n * Validates column values to ensure they fall within the standard 12-column grid system.\n *\n * @param fieldDef - Field definition containing column configuration\n * @returns CSS class string for grid layout, empty if no valid column configuration\n *\n * @example\n * ```typescript\n * // Full width field\n * const fullWidth = getGridClassString({ type: 'input', key: 'name', col: 12 });\n * // Returns: 'df-col-12'\n *\n * // Half width field\n * const halfWidth = getGridClassString({ type: 'input', key: 'email', col: 6 });\n * // Returns: 'df-col-6'\n *\n * // Invalid column value\n * const invalid = getGridClassString({ type: 'input', key: 'phone', col: 15 });\n * // Returns: ''\n * ```\n *\n * @public\n */\nexport function getGridClassString(fieldDef: FieldDef<unknown>): string {\n const col = fieldDef.col;\n if (typeof col === 'number' && Number.isInteger(col) && col > 0 && col <= 12) {\n return `df-col-${col}`;\n }\n return '';\n}\n\n/**\n * Builds a combined className string from a field definition.\n *\n * Combines user-provided className with generated grid classes into a single string.\n * Returns undefined if no classes are present (allowing conditional spreading in objects).\n *\n * @param fieldDef - Field definition containing className and col properties\n * @returns Combined class string, or undefined if no classes\n *\n * @example\n * ```typescript\n * // With both className and col\n * buildClassName({ key: 'test', type: 'group', className: 'my-class', col: 6 });\n * // Returns: 'df-col-6 my-class'\n *\n * // With only className\n * buildClassName({ key: 'test', type: 'group', className: 'my-class' });\n * // Returns: 'my-class'\n *\n * // With only col\n * buildClassName({ key: 'test', type: 'group', col: 6 });\n * // Returns: 'df-col-6'\n *\n * // With neither\n * buildClassName({ key: 'test', type: 'group' });\n * // Returns: undefined\n * ```\n *\n * @public\n */\nexport function buildClassName(fieldDef: FieldDef<unknown>): string | undefined {\n const gridClass = getGridClassString(fieldDef);\n const userClass = fieldDef.className;\n\n const classes: string[] = [];\n\n if (gridClass) {\n classes.push(gridClass);\n }\n\n if (userClass) {\n classes.push(userClass);\n }\n\n return classes.length > 0 ? classes.join(' ') : undefined;\n}\n","import { computed, Signal } from '@angular/core';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { getGridClassString } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Builds base input properties from a field definition.\n *\n * This is a helper function that extracts common field properties.\n * Used by mappers to build the inputs record.\n *\n * @param fieldDef The field definition to extract properties from\n * @param defaultProps Optional form-level default props to merge with field props\n * @returns Record of input names to values\n */\nexport function buildBaseInputs(fieldDef: FieldDef<unknown>, defaultProps?: Record<string, unknown>): Record<string, unknown> {\n const { key, label, className, tabIndex, props, meta } = fieldDef;\n const inputs: Record<string, unknown> = {};\n\n // Always include key - required by components for accessibility and identification\n inputs['key'] = key;\n\n if (label !== undefined) {\n inputs['label'] = label;\n }\n\n // Combine user className with generated grid classes\n const gridClassString = getGridClassString(fieldDef);\n const allClasses: string[] = [];\n\n if (gridClassString) {\n allClasses.push(gridClassString);\n }\n\n if (className) {\n allClasses.push(className);\n }\n\n if (allClasses.length > 0) {\n inputs['className'] = allClasses.join(' ');\n }\n\n if (tabIndex !== undefined) {\n inputs['tabIndex'] = tabIndex;\n }\n\n // Merge props: form-level defaultProps as base, field-level props override\n // Cast props to Record since it's typed as unknown but always represents an object at runtime\n const fieldProps = props as Record<string, unknown> | undefined;\n const mergedProps =\n fieldProps !== undefined || defaultProps !== undefined ? { ...(defaultProps ?? {}), ...(fieldProps ?? {}) } : undefined;\n\n if (mergedProps !== undefined) {\n inputs['props'] = mergedProps;\n }\n\n if (meta !== undefined) {\n inputs['meta'] = meta;\n }\n\n return inputs;\n}\n\n/**\n * Base field mapper that extracts common field properties into component inputs.\n *\n * Returns a Signal containing the Record of input names to values that will be\n * passed to ngComponentOutlet. The signal enables reactive updates.\n *\n * @param fieldDef The field definition to map\n * @returns Signal containing Record of input names to values\n */\nexport function baseFieldMapper(fieldDef: FieldDef<unknown>): Signal<Record<string, unknown>> {\n // For base mapper, inputs are static (no reactive dependencies)\n // Wrap in computed for consistency with the MapperFn type\n return computed(() => buildBaseInputs(fieldDef));\n}\n","import { computed, Signal } from '@angular/core';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldMeta } from '../../definitions/base/field-meta';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { baseFieldMapper } from '../../mappers/base/base-field-mapper';\n\n/**\n * Merges forwarded props into meta, with meta taking precedence.\n *\n * @param inputs The current inputs record\n * @param propsToMeta Array of prop keys to forward to meta\n * @returns Updated inputs record with merged meta\n */\nfunction mergeForwardedPropsToMeta(inputs: Record<string, unknown>, propsToMeta: string[]): Record<string, unknown> {\n const props = inputs['props'] as Record<string, unknown> | undefined;\n if (!props || propsToMeta.length === 0) {\n return inputs;\n }\n\n // Extract values to forward from props\n // Values are typed as FieldMeta-compatible since they're forwarded attributes (type, rows, cols, etc.)\n const forwardedValues: FieldMeta = {};\n for (const key of propsToMeta) {\n const value = props[key];\n if (value !== undefined && value !== null) {\n // Props being forwarded are known HTML attributes (string, number, boolean)\n forwardedValues[key] = value as string | number | boolean;\n }\n }\n\n // If nothing to forward, return inputs unchanged\n if (Object.keys(forwardedValues).length === 0) {\n return inputs;\n }\n\n // Merge: forwarded props first, then meta (meta wins)\n const existingMeta = inputs['meta'] as FieldMeta | undefined;\n const mergedMeta: FieldMeta = {\n ...forwardedValues,\n ...existingMeta,\n };\n\n return {\n ...inputs,\n meta: mergedMeta,\n };\n}\n\n/**\n * Main field mapper function that uses the field registry to get the appropriate mapper\n * based on the field's type property.\n *\n * This function must be called within an injection context where FIELD_SIGNAL_CONTEXT\n * is provided, as mappers inject the context to access form state.\n *\n * For componentless fields (no loadComponent and no mapper), returns undefined\n * since there's no component to bind inputs to. Callers should check for undefined\n * and skip rendering logic for such fields.\n *\n * If the field type definition specifies `propsToMeta`, the specified props\n * will be merged into the meta object (with meta taking precedence).\n *\n * @param fieldDef The field definition to map\n * @param fieldRegistry The registry of field type definitions\n * @returns Signal containing Record of input names to values, or undefined for componentless fields\n */\nexport function mapFieldToInputs(\n fieldDef: FieldDef<unknown>,\n fieldRegistry: Map<string, FieldTypeDefinition>,\n): Signal<Record<string, unknown>> | undefined {\n // Get the field type definition from registry\n const fieldType = fieldRegistry.get(fieldDef.type);\n\n // Componentless field (no mapper and no loadComponent) - nothing to map\n if (fieldType && !fieldType.loadComponent && !fieldType.mapper) {\n return undefined;\n }\n\n // Get the base mapper result\n const mapperResult: Signal<Record<string, unknown>> = fieldType?.mapper ? fieldType.mapper(fieldDef) : baseFieldMapper(fieldDef);\n\n // If no props forwarding configured, return as-is\n const propsToMeta = fieldType?.propsToMeta;\n if (!propsToMeta || propsToMeta.length === 0) {\n return mapperResult;\n }\n\n // Wrap in computed to merge forwarded props into meta\n return computed(() => {\n const inputs = mapperResult();\n return mergeForwardedPropsToMeta(inputs, propsToMeta);\n });\n}\n","import { DestroyRef, Injector, runInInjectionContext, Signal, Type } from '@angular/core';\nimport { catchError, forkJoin, from, map, Observable, of, OperatorFunction, pipe, scan, switchMap } from 'rxjs';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { mapFieldToInputs } from '../field-mapper/field-mapper';\n\n/**\n * Resolved field ready for rendering with ngComponentOutlet.\n */\nexport interface ResolvedField {\n key: string;\n component: Type<unknown>;\n injector: Injector;\n inputs: Signal<Record<string, unknown>>;\n}\n\n/**\n * Context required to resolve a field.\n */\nexport interface ResolveFieldContext {\n /**\n * The field registry to load components from.\n * Returns undefined for componentless fields (e.g., hidden fields).\n */\n loadTypeComponent: (type: string) => Promise<Type<unknown> | undefined>;\n /** The raw field registry map for mappers */\n registry: Map<string, FieldTypeDefinition>;\n /** The injector to use for the resolved field */\n injector: Injector;\n /** DestroyRef to check if component is destroyed */\n destroyRef: DestroyRef;\n /** Optional error handler for logging */\n onError?: (fieldDef: FieldDef<unknown>, error: unknown) => void;\n}\n\n/**\n * Resolves a single field definition to a ResolvedField using RxJS.\n * Loads the component asynchronously and maps inputs in the injection context.\n *\n * For componentless fields (e.g., hidden fields), returns undefined since\n * there's nothing to render. These fields still contribute to form values\n * through the form schema.\n *\n * @param fieldDef - The field definition to resolve\n * @param context - The context containing dependencies for resolution\n * @returns Observable that emits ResolvedField or undefined (for componentless fields or on error)\n */\nexport function resolveField(fieldDef: FieldDef<unknown>, context: ResolveFieldContext): Observable<ResolvedField | undefined> {\n return from(context.loadTypeComponent(fieldDef.type)).pipe(\n map((component) => {\n // Check if component is destroyed before proceeding\n if (context.destroyRef.destroyed) {\n return undefined;\n }\n\n // Componentless fields (e.g., hidden) return undefined - nothing to render\n if (!component) {\n return undefined;\n }\n\n // Run mapper in injection context\n const inputs = runInInjectionContext(context.injector, () => mapFieldToInputs(fieldDef, context.registry));\n\n // Fields with components should always have inputs (componentless fields are handled above)\n if (!inputs) {\n return undefined;\n }\n\n return {\n key: fieldDef.key,\n component,\n injector: context.injector,\n inputs,\n };\n }),\n catchError((error) => {\n // Only handle errors if component hasn't been destroyed\n if (!context.destroyRef.destroyed) {\n context.onError?.(fieldDef, error);\n }\n return of(undefined);\n }),\n );\n}\n\n/**\n * Reconciles previous and current resolved fields to preserve injector instances\n * for fields that haven't changed type, preventing unnecessary component recreation.\n *\n * @param prev - Previous resolved fields array\n * @param curr - Current resolved fields array\n * @returns Reconciled fields with preserved injectors where applicable\n */\nexport function reconcileFields(prev: ResolvedField[], curr: ResolvedField[]): ResolvedField[] {\n const prevMap = new Map(prev.map((f) => [f.key, f]));\n\n return curr.map((field) => {\n const existing = prevMap.get(field.key);\n\n if (existing && existing.component === field.component) {\n // Same key & type - reuse existing injector, update inputs\n return {\n ...field,\n injector: existing.injector,\n };\n }\n\n // New field or type changed - use new injector\n return field;\n });\n}\n\n/**\n * Creates an RxJS pipe for resolving field definitions to rendered components.\n * Used by container components (page, group) to resolve their child fields.\n */\nexport function createFieldResolutionPipe(getContext: () => ResolveFieldContext): OperatorFunction<FieldDef<unknown>[], ResolvedField[]> {\n return pipe(\n switchMap((fields) => {\n if (!fields || fields.length === 0) {\n return of([] as (ResolvedField | undefined)[]);\n }\n const context = getContext();\n return forkJoin(fields.map((f) => resolveField(f, context)));\n }),\n map((fields) => fields.filter((f): f is ResolvedField => f !== undefined)),\n scan(reconcileFields, [] as ResolvedField[]),\n );\n}\n","import { Signal } from '@angular/core';\nimport { submit } from '@angular/forms/signals';\nimport { EMPTY, firstValueFrom, from, isObservable, Observable, switchMap } from 'rxjs';\nimport { EventBus } from '../../events/event.bus';\nimport { SubmitEvent } from '../../events/constants/submit.event';\nimport { FormConfig } from '../../models/form-config';\nimport { RegisteredFieldTypes } from '../../models/registry/field-registry';\n\n/**\n * Options for creating a submission handler.\n */\nexport interface SubmissionHandlerOptions<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n /** Event bus instance for listening to submit events */\n eventBus: EventBus;\n /** Signal containing the form configuration */\n configSignal: Signal<FormConfig<TFields>>;\n /** Signal containing the form instance. Type is parameterized to support different form value shapes. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FieldTree type requires dynamic form model type\n formSignal: Signal<any>;\n}\n\n/**\n * Wraps a submission action to handle both Promise and Observable returns.\n * Converts Observables to Promises for compatibility with Angular Signal Forms' submit().\n *\n * @param action - The submission action function\n * @returns A wrapped function that always returns a Promise\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Form tree type is dynamic, action signatures vary\nfunction wrapSubmissionAction(action: (formTree: any) => any): (formTree: any) => Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (formTree: any): Promise<any> => {\n const result = action(formTree);\n // If the action returns an Observable, convert it to a Promise\n if (isObservable(result)) {\n return firstValueFrom(result);\n }\n return result;\n };\n}\n\n/**\n * Creates an Observable that handles form submission with optional submission action.\n *\n * This utility encapsulates the submission handling logic:\n * - Listens for submit events from the event bus\n * - If a submission.action is configured, wraps it and uses Angular Signal Forms' submit()\n * - Handles both Promise and Observable returns from the action\n * - Uses switchMap to cancel any in-flight submission when a new one starts\n *\n * The returned Observable should be subscribed to with takeUntilDestroyed() in the component.\n *\n * @param options - Configuration options for the submission handler\n * @returns Observable that processes submissions (emits when submission completes)\n *\n * @example\n * ```typescript\n * // In component constructor\n * createSubmissionHandler({\n * eventBus: this.eventBus,\n * configSignal: this.config,\n * formSignal: this.form,\n * })\n * .pipe(takeUntilDestroyed())\n * .subscribe();\n * ```\n */\nexport function createSubmissionHandler<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]>(\n options: SubmissionHandlerOptions<TFields>,\n): Observable<unknown> {\n const { eventBus, configSignal, formSignal } = options;\n\n return eventBus.on<SubmitEvent>('submit').pipe(\n switchMap(() => {\n const submissionConfig = configSignal().submission;\n\n // If no submission action is configured, let the submitted output handle it\n // This maintains backward compatibility for users handling submission manually\n if (!submissionConfig?.action) {\n return EMPTY;\n }\n\n const wrappedAction = wrapSubmissionAction(submissionConfig.action);\n\n // Use Angular Signal Forms' native submit() function\n // This automatically:\n // - Sets form.submitting() to true during execution\n // - Applies server errors to form fields on completion\n // - Sets form.submitting() to false when done\n return from(submit(formSignal(), wrappedAction));\n }),\n );\n}\n","/**\n * Native JavaScript utility functions to replace lodash-es\n * These are simple implementations for common object manipulation patterns\n */\n\n/**\n * Performs a deep equality comparison between two values.\n *\n * Handles:\n * - Primitives (including NaN via Object.is)\n * - Dates (by timestamp)\n * - Arrays (deep element comparison)\n * - Plain objects (deep property comparison)\n * - RegExp (by source and flags)\n * - Map and Set (by entries)\n * - Circular references (via WeakMap tracking)\n *\n * @param a - First value\n * @param b - Second value\n * @returns true if values are deeply equal\n *\n * @example\n * ```typescript\n * isEqual({ a: 1 }, { a: 1 }); // true\n * isEqual([1, 2], [1, 2]); // true\n * isEqual({ a: 1 }, { a: 2 }); // false\n * isEqual(new Date('2024-01-01'), new Date('2024-01-01')); // true\n * isEqual(/abc/gi, /abc/gi); // true\n * ```\n */\nexport function isEqual(a: unknown, b: unknown): boolean {\n return isEqualInternal(a, b, new WeakMap(), new WeakMap());\n}\n\n/**\n * Internal implementation with circular reference tracking.\n * @internal\n */\nfunction isEqualInternal(a: unknown, b: unknown, seenA: WeakMap<object, object>, seenB: WeakMap<object, object>): boolean {\n // Same reference or both null/undefined\n if (a === b) return true;\n\n // Handle NaN (NaN === NaN is false, but we want it to be equal)\n if (typeof a === 'number' && typeof b === 'number') {\n return Object.is(a, b);\n }\n\n // One is null/undefined but not both\n if (a == null || b == null) return false;\n\n // Different types\n if (typeof a !== typeof b) return false;\n\n // Non-object primitives (strings, booleans, symbols, bigints)\n if (typeof a !== 'object') {\n return Object.is(a, b);\n }\n\n // At this point, both a and b are objects (typeof a === 'object')\n const objA = a as object;\n const objB = b as object;\n\n // Check for circular references\n if (seenA.has(objA) || seenB.has(objB)) {\n // If we've seen these objects before, check if they were paired together\n return seenA.get(objA) === objB && seenB.get(objB) === objA;\n }\n\n // Mark these objects as seen (paired together)\n seenA.set(objA, objB);\n seenB.set(objB, objA);\n\n // Different constructors means different types (e.g., Date vs Object)\n if (objA.constructor !== objB.constructor) return false;\n\n // Handle dates\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // Handle RegExp\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.source === b.source && a.flags === b.flags;\n }\n\n // Handle Map\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (const [key, value] of a) {\n if (!b.has(key) || !isEqualInternal(value, b.get(key), seenA, seenB)) {\n return false;\n }\n }\n return true;\n }\n\n // Handle Set\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) {\n // For non-primitive values in Sets, we need deep comparison\n // This is O(n^2) but Sets rarely contain objects\n if (typeof value === 'object' && value !== null) {\n let found = false;\n for (const bValue of b) {\n if (typeof bValue === 'object' && bValue !== null && isEqualInternal(value, bValue, seenA, seenB)) {\n found = true;\n break;\n }\n }\n if (!found) return false;\n } else {\n return false;\n }\n }\n }\n return true;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => isEqualInternal(item, b[index], seenA, seenB));\n }\n\n // Handle plain objects\n const recordA = a as Record<string | symbol, unknown>;\n const recordB = b as Record<string | symbol, unknown>;\n\n // Get both string and symbol keys\n const keysA = [...Object.keys(recordA), ...Object.getOwnPropertySymbols(recordA)];\n const keysB = [...Object.keys(recordB), ...Object.getOwnPropertySymbols(recordB)];\n\n if (keysA.length !== keysB.length) return false;\n\n // Create a Set for O(1) lookup\n const keySetB = new Set(keysB);\n\n return keysA.every((key) => keySetB.has(key) && isEqualInternal(recordA[key], recordB[key], seenA, seenB));\n}\n\n/**\n * Creates a new object without the specified keys\n * Native replacement for lodash omit()\n *\n * @param obj - Source object\n * @param keys - Keys to omit\n * @returns New object without specified keys\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: 2, c: 3 };\n * omit(obj, ['b']); // { a: 1, c: 3 }\n * ```\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n const result = { ...obj };\n keys.forEach((key) => delete result[key]);\n return result as Omit<T, K>;\n}\n\n/**\n * Creates an object from an array, keyed by a specified property\n * Native replacement for lodash keyBy()\n *\n * @param array - Source array\n * @param key - Property to use as key\n * @returns Object keyed by the specified property\n *\n * @example\n * ```typescript\n * const users = [{ id: 'a', name: 'Alice' }, { id: 'b', name: 'Bob' }];\n * keyBy(users, 'id'); // { a: { id: 'a', name: 'Alice' }, b: { id: 'b', name: 'Bob' } }\n * ```\n */\nexport function keyBy<T extends object>(array: T[], key: keyof T): Record<string, T> {\n return array.reduce(\n (acc, item) => {\n acc[String(item[key])] = item;\n return acc;\n },\n {} as Record<string, T>,\n );\n}\n\n/**\n * Maps object values through a transformation function\n * Native replacement for lodash mapValues()\n *\n * @param obj - Source object\n * @param fn - Transformation function\n * @returns New object with transformed values\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: 2 };\n * mapValues(obj, (v) => v * 2); // { a: 2, b: 4 }\n * ```\n */\nexport function mapValues<T, U>(obj: Record<string, T>, fn: (value: T, key: string) => U): Record<string, U> {\n return Object.entries(obj).reduce(\n (acc, [key, value]) => {\n acc[key] = fn(value, key);\n return acc;\n },\n {} as Record<string, U>,\n );\n}\n\n/**\n * Options for memoize function\n */\n/** Default maximum cache size for memoized functions */\nconst DEFAULT_MEMOIZE_MAX_SIZE = 100;\n\nexport interface MemoizeOptions<TFunc extends (...args: never[]) => unknown> {\n /** Optional function to generate cache key from arguments */\n resolver?: (...args: Parameters<TFunc>) => string;\n /** Maximum number of entries to keep in cache. Uses LRU eviction when exceeded. Defaults to 100. */\n maxSize?: number;\n}\n\n/**\n * Memoizes a function with LRU cache eviction and optional custom cache key resolver.\n *\n * @param fn - Function to memoize\n * @param resolverOrOptions - Optional key resolver function or options object\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * const expensive = (a: number, b: number) => a + b;\n * const memoized = memoize(expensive); // Uses default maxSize of 100\n *\n * // With custom resolver\n * const withResolver = memoize(expensive, (a, b) => `${a}-${b}`);\n *\n * // With custom maxSize\n * const small = memoize(expensive, { maxSize: 10 });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function memoize<TFunc extends (...args: any[]) => any>(\n fn: TFunc,\n resolverOrOptions?: ((...args: Parameters<TFunc>) => string) | MemoizeOptions<TFunc>,\n): TFunc {\n const options: MemoizeOptions<TFunc> =\n typeof resolverOrOptions === 'function' ? { resolver: resolverOrOptions } : (resolverOrOptions ?? {});\n\n const { resolver, maxSize = DEFAULT_MEMOIZE_MAX_SIZE } = options;\n const cache = new Map<string, ReturnType<TFunc>>();\n\n return ((...args: Parameters<TFunc>): ReturnType<TFunc> => {\n const key = resolver ? resolver(...args) : JSON.stringify(args);\n\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n cache.delete(key);\n cache.set(key, cachedValue);\n return cachedValue;\n }\n\n const result = fn(...args);\n\n if (cache.size >= maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n }\n }\n\n cache.set(key, result);\n return result;\n }) as TFunc;\n}\n\n/**\n * Normalizes a fields collection to an array.\n * Handles both array format and object format (keyed by field key).\n *\n * @param fields - Fields as array or object\n * @returns Fields as array\n */\nexport function normalizeFieldsArray<T>(fields: readonly T[] | Record<string, T>): T[] {\n return Array.isArray(fields) ? [...fields] : Object.values(fields);\n}\n\n/**\n * Gets the keys that differ between two objects.\n *\n * Compares top-level keys and returns those whose values are different.\n * Uses deep equality comparison for nested values.\n *\n * @param previous - Previous object state\n * @param current - Current object state\n * @returns Set of keys that have different values\n *\n * @example\n * ```typescript\n * const prev = { a: 1, b: 2, c: 3 };\n * const curr = { a: 1, b: 5, d: 4 };\n * getChangedKeys(prev, curr); // Set { 'b', 'c', 'd' }\n * ```\n */\nexport function getChangedKeys(\n previous: Record<string, unknown> | null | undefined,\n current: Record<string, unknown> | null | undefined,\n): Set<string> {\n const changedKeys = new Set<string>();\n\n // Handle null/undefined cases\n if (!previous && !current) return changedKeys;\n if (!previous) {\n return new Set(Object.keys(current ?? {}));\n }\n if (!current) {\n return new Set(Object.keys(previous));\n }\n\n // Collect all keys from both objects\n const allKeys = new Set([...Object.keys(previous), ...Object.keys(current)]);\n\n // Check each key for differences\n for (const key of allKeys) {\n const prevValue = previous[key];\n const currValue = current[key];\n\n // Key added or removed\n if (!(key in previous) || !(key in current)) {\n changedKeys.add(key);\n continue;\n }\n\n // Value changed\n if (!isEqual(prevValue, currValue)) {\n changedKeys.add(key);\n }\n }\n\n return changedKeys;\n}\n","import { InjectionToken, Signal } from '@angular/core';\nimport type { FieldSignalContext, ArrayContext } from '../mappers/types';\nimport type { ValidationMessages } from './validation-types';\nimport type { FormOptions } from './form-config';\n\n/**\n * Injection token for providing field signal context to mappers and components.\n *\n * The field signal context is the \"nervous system\" of the dynamic form library,\n * providing access to:\n * - The form instance and structure\n * - Current form values (as signals)\n * - Default values\n * - Validation messages\n * - The injector for creating components\n *\n * This token is provided by the DynamicForm component and can be scoped\n * for nested forms (Groups, Arrays) via child injectors.\n *\n * @example\n * ```typescript\n * // In a mapper function\n * export function mapValueField(fieldDef: BaseValueField<any, any>): Binding[] {\n * const context = inject(FIELD_SIGNAL_CONTEXT);\n * const form = context.form();\n * // ... use context\n * }\n *\n * // In a component\n * export class MyFieldComponent {\n * private context = inject(FIELD_SIGNAL_CONTEXT);\n * }\n * ```\n */\nexport const FIELD_SIGNAL_CONTEXT = new InjectionToken<FieldSignalContext>('FIELD_SIGNAL_CONTEXT', {\n providedIn: null, // Not provided at root - must be provided by DynamicForm\n factory: () => {\n throw new Error(\n 'FIELD_SIGNAL_CONTEXT was not provided. ' +\n 'This token must be provided by DynamicFormComponent or a container field component. ' +\n 'If you are calling a mapper function directly, ensure it runs within runInInjectionContext() ' +\n 'with an injector that provides FIELD_SIGNAL_CONTEXT.',\n );\n },\n});\n\n/**\n * Injection token for providing array context metadata to mappers and components.\n *\n * This token is optionally provided by ArrayFieldComponent when creating injectors\n * for array items. It contains metadata about the array item's position and parent.\n *\n * Mappers can inject this token with {optional: true} to access array context:\n *\n * @example\n * ```typescript\n * // In a mapper function\n * export function buttonMapper(fieldDef: FieldDef<any>): Binding[] {\n * const arrayContext = inject(ARRAY_CONTEXT, { optional: true });\n * if (arrayContext) {\n * // Use arrayContext.index, arrayContext.arrayKey, etc.\n * }\n * }\n * ```\n */\nexport const ARRAY_CONTEXT = new InjectionToken<ArrayContext>('ARRAY_CONTEXT');\n\n/**\n * Injection token for form-level default props.\n *\n * Default props are form-wide property defaults that are merged with field-level props.\n * Field props take precedence over default props.\n *\n * Unlike FIELD_SIGNAL_CONTEXT which is re-provided by container components (Group, Array),\n * DEFAULT_PROPS is provided ONCE at the DynamicForm level and inherited by all children\n * via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a mapper function\n * const defaultPropsSignal = inject(DEFAULT_PROPS);\n *\n * return computed(() => {\n * const defaultProps = defaultPropsSignal?.(); // Read inside computed for reactivity\n * const baseInputs = buildBaseInputs(fieldDef, defaultProps);\n * // ...\n * });\n * ```\n */\nexport const DEFAULT_PROPS = new InjectionToken<Signal<Record<string, unknown> | undefined>>('DEFAULT_PROPS');\n\n/**\n * Injection token for form-level default validation messages.\n *\n * Default validation messages act as fallbacks when fields have validation\n * errors but no field-level `validationMessages` defined.\n *\n * Like DEFAULT_PROPS, this token is provided ONCE at the DynamicForm level\n * and inherited by all children via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a mapper or component\n * const defaultMessagesSignal = inject(DEFAULT_VALIDATION_MESSAGES);\n *\n * return computed(() => {\n * const defaultMessages = defaultMessagesSignal?.(); // Read inside computed for reactivity\n * const message = defaultMessages?.required ?? 'Field is required';\n * // ...\n * });\n * ```\n */\nexport const DEFAULT_VALIDATION_MESSAGES = new InjectionToken<Signal<ValidationMessages | undefined>>('DEFAULT_VALIDATION_MESSAGES');\n\n/**\n * Injection token for form-level options.\n *\n * Form options control form-wide behavior including button disabled states.\n * Used by button mappers to determine default disabled behavior.\n *\n * Like DEFAULT_PROPS, this token is provided ONCE at the DynamicForm level\n * and inherited by all children via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a button mapper\n * const formOptionsSignal = inject(FORM_OPTIONS);\n *\n * return computed(() => {\n * const formOptions = formOptionsSignal?.(); // Read inside computed for reactivity\n * const disableWhenInvalid = formOptions?.submitButton?.disableWhenInvalid ?? true;\n * // ...\n * });\n * ```\n */\nexport const FORM_OPTIONS = new InjectionToken<Signal<FormOptions | undefined>>('FORM_OPTIONS');\n","/**\n * Base error class for all Dynamic Forms errors.\n *\n * This class centralizes the `[Dynamic Forms]` prefix, ensuring consistent\n * error messaging across the library without requiring each error site to\n * manually include the prefix.\n */\nexport class DynamicFormError extends Error {\n private static readonly PREFIX = '[Dynamic Forms]';\n\n constructor(message: string) {\n super(`${DynamicFormError.PREFIX} ${message}`);\n this.name = 'DynamicFormError';\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { MapperFn } from '../mappers/types';\n\n/**\n * Defines how a field type handles form values and data collection.\n *\n * - 'include': Field contributes to form values (default for input fields)\n * - 'exclude': Field is excluded from form values (for display/layout fields)\n * - 'flatten': Field's children are flattened to parent level (for container fields)\n */\nexport type ValueHandlingMode = 'include' | 'exclude' | 'flatten';\n\n/**\n * Configuration interface for registering custom field types.\n *\n * Defines how a field type should be handled by the dynamic form system,\n * including its component loading strategy and field-to-component mapping logic.\n * Supports both eager-loaded and lazy-loaded components.\n *\n * @typeParam T - The field definition type this field type handles\n *\n * @example\n * ```typescript\n * const CustomInputType: FieldTypeDefinition<InputFieldDef> = {\n * name: 'custom-input',\n * loadComponent: () => import('./custom-input.component').then(m => m.CustomInputComponent),\n * mapper: customInputMapper\n * };\n *\n * // Register with providers\n * provideDynamicForm(CustomInputType)\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Intentionally using `any` for maximum flexibility in field type registration\nexport interface FieldTypeDefinition<T extends FieldDef<any> = any> {\n /** Unique identifier for the field type */\n name: string;\n /** Field definition type marker (internal use) */\n _fieldDef?: T;\n /**\n * Function to load the component (supports lazy loading).\n * Returns a Promise that resolves to the component class or module with default export.\n *\n * Optional - omit for componentless fields (e.g., hidden fields) that only\n * contribute to form values without rendering any UI.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Component loading returns dynamic module structure\n loadComponent?: () => Promise<any>;\n /**\n * Mapper function that converts field definition to component bindings.\n *\n * Optional - omit for componentless fields (like hidden fields) that don't need\n * input mapping. When omitted for componentless fields (no loadComponent), an empty\n * signal is returned. When omitted for regular fields with a component, falls back\n * to baseFieldMapper.\n */\n mapper?: MapperFn<T>;\n /** How this field type handles form values and data collection (defaults to 'include') */\n valueHandling?: ValueHandlingMode;\n /**\n * List of prop keys to forward to the meta object.\n *\n * Some props (like `type` for inputs, `rows`/`cols` for textareas) are actually\n * native HTML attributes. Specifying them here causes them to be merged into\n * the meta object before being passed to the component, ensuring they're applied\n * via the meta tracking mechanism.\n *\n * Note: Meta values always take precedence over forwarded props.\n *\n * @example\n * ```typescript\n * {\n * name: 'input',\n * propsToMeta: ['type'],\n * // ...\n * }\n * ```\n */\n propsToMeta?: string[];\n}\n\n/**\n * Injection token for the global field type registry.\n *\n * Provides access to the map of registered field types throughout the application.\n * The registry is populated by the provideDynamicForm function and used by\n * field rendering components to resolve field types to their implementations.\n *\n * @example\n * ```typescript\n * constructor(@Inject(FIELD_REGISTRY) private registry: Map<string, FieldTypeDefinition>) {\n * const inputType = registry.get('input');\n * }\n * ```\n */\nexport const FIELD_REGISTRY = new InjectionToken<Map<string, FieldTypeDefinition>>('FIELD_REGISTRY', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n\n/**\n * Gets the value handling mode for a specific field type from the registry.\n *\n * @param fieldType - The field type identifier\n * @param registry - The field type registry\n * @returns The value handling mode ('include' is the default if not specified)\n */\nexport function getFieldValueHandling(fieldType: string, registry: Map<string, FieldTypeDefinition>): ValueHandlingMode {\n const definition = registry.get(fieldType);\n return definition?.valueHandling ?? 'include';\n}\n","import { inject, Type } from '@angular/core';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { FIELD_REGISTRY, FieldTypeDefinition } from '../../models/field-type';\n\n/**\n * Injection function for accessing the dynamic form field registry.\n *\n * Provides a convenient API for interacting with registered field types,\n * including type checking, component loading, and registration management.\n * Must be called within an injection context.\n *\n * @returns Object with methods for field registry interaction\n *\n * @example\n * ```typescript\n * @Component({...})\n * export class MyComponent {\n * private fieldRegistry = injectFieldRegistry();\n *\n * async loadCustomField() {\n * if (this.fieldRegistry.hasType('custom-input')) {\n * const component = await this.fieldRegistry.loadTypeComponent('custom-input');\n * // Use component...\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // In a service\n * @Injectable()\n * export class FormBuilderService {\n * private fieldRegistry = injectFieldRegistry();\n *\n * getAvailableFieldTypes(): string[] {\n * return this.fieldRegistry.getTypes().map(type => type.name);\n * }\n * }\n * ```\n *\n * @public\n */\nexport function injectFieldRegistry() {\n const registry = inject(FIELD_REGISTRY);\n\n return {\n /**\n * Retrieves a field type definition by its registered name.\n *\n * @param name - The registered name of the field type\n * @returns The field type definition if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const inputType = fieldRegistry.getType('input');\n * if (inputType) {\n * console.log('Input field type found:', inputType.name);\n * }\n * ```\n */\n getType(name: string): FieldTypeDefinition | undefined {\n return registry.get(name);\n },\n\n /**\n * Checks if a field type is registered in the registry.\n *\n * @param name - The name of the field type to check\n * @returns True if the field type exists, false otherwise\n *\n * @example\n * ```typescript\n * if (fieldRegistry.hasType('custom-input')) {\n * // Safe to use custom-input field type\n * const component = await fieldRegistry.loadTypeComponent('custom-input');\n * }\n * ```\n */\n hasType(name: string): boolean {\n return registry.has(name);\n },\n\n /**\n * Loads a field type component with support for lazy loading.\n *\n * Handles both synchronous component references and asynchronous\n * dynamic imports. Automatically extracts default exports from ES modules.\n *\n * Returns `undefined` for componentless field types (e.g., hidden fields)\n * that only contribute to form values without rendering UI.\n *\n * @param name - The name of the field type to load\n * @returns Promise resolving to the component constructor, or undefined for componentless fields\n * @throws {Error} When field type is not registered or loading fails\n *\n * @example\n * ```typescript\n * const component = await fieldRegistry.loadTypeComponent('input');\n * if (component) {\n * const componentRef = vcr.createComponent(component);\n * }\n * // For componentless fields like 'hidden', component will be undefined\n * ```\n */\n async loadTypeComponent(name: string): Promise<Type<unknown> | undefined> {\n const fieldType = registry.get(name);\n\n if (!fieldType) {\n throw new DynamicFormError(`Field type \"${name}\" is not registered`);\n }\n\n // Componentless field types (e.g., hidden) don't have loadComponent\n if (!fieldType.loadComponent) {\n return undefined;\n }\n\n // Handle async loading\n try {\n const result = await fieldType.loadComponent();\n // Handle ES module imports - extract default export if needed\n const moduleResult = result as { default?: Type<unknown> } | Type<unknown>;\n return (typeof moduleResult === 'object' && 'default' in moduleResult && moduleResult.default) || (result as Type<unknown>);\n } catch (error) {\n throw new DynamicFormError(`Failed to load component for field type \"${name}\": ${error}`);\n }\n },\n\n /**\n * Gets all registered field type definitions.\n *\n * @returns Array of all field type definitions in the registry\n *\n * @example\n * ```typescript\n * const allTypes = fieldRegistry.getTypes();\n * const typeNames = allTypes.map(type => type.name);\n * console.log('Available field types:', typeNames);\n * ```\n */\n getTypes(): FieldTypeDefinition[] {\n return Array.from(registry.values());\n },\n\n /**\n * Registers multiple field types at once.\n *\n * Useful for bulk registration of custom field types. Overwrites\n * existing registrations with the same name.\n *\n * @param types - Array of field type definitions to register\n *\n * @example\n * ```typescript\n * fieldRegistry.registerTypes([\n * CustomInputType,\n * CustomSelectType,\n * CustomDatePickerType\n * ]);\n * ```\n */\n registerTypes(types: FieldTypeDefinition[]): void {\n types.forEach((type) => {\n registry.set(type.name, type);\n });\n },\n\n /**\n * Provides direct access to the underlying registry Map.\n *\n * Use with caution - direct modification can affect form behavior.\n * Primarily intended for advanced use cases and debugging.\n *\n * @returns The raw Map containing field type registrations\n *\n * @example\n * ```typescript\n * const rawRegistry = fieldRegistry.raw;\n * console.log('Registry size:', rawRegistry.size);\n * ```\n */\n get raw() {\n return registry;\n },\n };\n}\n","import { InjectionToken } from '@angular/core';\nimport type { Logger } from './logger.interface';\n\n/**\n * Injection token for the dynamic forms logger.\n *\n * Provided by provideDynamicForm() with ConsoleLogger as default.\n * Override with withLoggerConfig(false) to disable logging.\n */\nexport const DynamicFormLogger = new InjectionToken<Logger>('DynamicFormLogger');\n","import { Injectable, signal, Signal, isSignal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\n\n/**\n * Registry service that maintains references to root form fields.\n * This provides a type-safe way to access root form values from child fields\n * without relying on internal Angular Forms API navigation.\n *\n * This service should be provided at the component level to ensure proper\n * isolation between different form instances.\n *\n * IMPORTANT: This registry supports two registration patterns:\n * 1. registerFormValueSignal() - Register the SOURCE signal BEFORE form creation\n * This allows logic functions to read form values during schema evaluation.\n * 2. registerRootForm() - Register the FieldTree AFTER form creation\n * This provides access to the full form structure.\n *\n * For cross-field logic to work correctly, registerFormValueSignal() should be\n * called BEFORE the form() call.\n */\n@Injectable()\nexport class RootFormRegistryService {\n // Use a signal containing a Map to make registration reactive\n private readonly _rootForms = signal(new Map<string, FieldTree<unknown>>());\n // Store form value signals separately - these can be registered before form creation\n private readonly _formValueSignals = signal(new Map<string, Signal<Record<string, unknown>>>());\n private readonly formContexts = new Map<string, Record<string, unknown>>();\n\n /**\n * Registers the form value signal BEFORE form creation.\n *\n * This is the recommended pattern for cross-field logic:\n * 1. Create the formValue signal\n * 2. Register it with registerFormValueSignal()\n * 3. Create the form with form(formValue, schema(...))\n *\n * This allows logic functions to access form values during schema evaluation.\n */\n registerFormValueSignal(valueSignal: Signal<Record<string, unknown>>, formId = 'default'): void {\n this._formValueSignals.update((signals) => {\n const newSignals = new Map(signals);\n newSignals.set(formId, valueSignal);\n return newSignals;\n });\n }\n\n /**\n * Gets the registered form value signal by id.\n *\n * This allows direct access to the source signal, which can be read\n * reactively to get form values.\n */\n getFormValueSignal(formId = 'default'): Signal<Record<string, unknown>> | undefined {\n return this._formValueSignals().get(formId);\n }\n\n /**\n * Registers a root form field with an optional identifier.\n * If no id is provided, uses 'default' as the key.\n *\n * This triggers reactive updates for any computed signals that\n * depend on getRootForm().\n */\n registerRootForm(rootField: FieldTree<unknown>, formId = 'default'): void {\n this._rootForms.update((forms) => {\n const newForms = new Map(forms);\n newForms.set(formId, rootField);\n return newForms;\n });\n }\n\n /**\n * Gets a registered root form field by id.\n *\n * IMPORTANT: This method reads from a signal, which means any computed\n * signal that calls this method will automatically re-evaluate when\n * the form is registered or updated.\n */\n getRootForm(formId = 'default'): FieldTree<unknown> | undefined {\n return this._rootForms().get(formId);\n }\n\n /**\n * Gets the form value, preferring the direct signal if available.\n *\n * This method tries in order:\n * 1. Form value signal (if registered) - reads directly from source signal\n * 2. Root form's .value() (if registered) - reads from FieldTree\n * 3. Returns empty object if nothing is registered\n *\n * Reading from signals creates reactive dependencies, so computeds will\n * re-evaluate when form values change.\n */\n getFormValue(formId = 'default'): Record<string, unknown> {\n // First try the direct value signal (preferred, can be registered before form creation)\n const valueSignal = this._formValueSignals().get(formId);\n if (valueSignal) {\n const value = valueSignal();\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return value;\n }\n }\n\n // Fall back to root form's value\n const rootForm = this._rootForms().get(formId);\n if (rootForm) {\n try {\n let rootValue: unknown;\n\n // Check if rootForm is a Signal (callable function that returns FieldTree)\n if (isSignal(rootForm)) {\n const fieldTree = rootForm();\n if (fieldTree && typeof fieldTree === 'object' && 'value' in fieldTree) {\n rootValue = (fieldTree as { value: () => unknown }).value();\n }\n } else if ('value' in rootForm && typeof (rootForm as { value: unknown }).value === 'function') {\n rootValue = (rootForm as { value: () => unknown }).value();\n }\n\n if (rootValue && typeof rootValue === 'object' && !Array.isArray(rootValue)) {\n return rootValue as Record<string, unknown>;\n }\n } catch {\n // Ignore errors when reading form value\n }\n }\n\n return {};\n }\n\n /**\n * Registers form context (field paths and metadata) for a specific form.\n * This can be used to store additional context information.\n */\n registerFormContext(context: Record<string, unknown>, formId = 'default'): void {\n this.formContexts.set(formId, context);\n }\n\n /**\n * Gets form context by id.\n */\n getFormContext(formId = 'default'): Record<string, unknown> {\n return this.formContexts.get(formId) || {};\n }\n\n /**\n * Unregisters a form and its context.\n * This should be called when a form component is destroyed to prevent memory leaks.\n */\n unregisterForm(formId = 'default'): void {\n this._rootForms.update((forms) => {\n const newForms = new Map(forms);\n newForms.delete(formId);\n return newForms;\n });\n this.formContexts.delete(formId);\n }\n\n /**\n * Gets all registered form IDs.\n */\n getRegisteredFormIds(): string[] {\n return Array.from(this._rootForms().keys());\n }\n\n /**\n * Clears all registered forms. Useful for testing.\n */\n clear(): void {\n this._rootForms.set(new Map());\n this._formValueSignals.set(new Map());\n this.formContexts.clear();\n }\n}\n","import { inject, Injectable, isSignal, untracked } from '@angular/core';\nimport { ChildFieldContext, FieldContext } from '@angular/forms/signals';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { RootFormRegistryService } from './root-form-registry.service';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\n\nfunction isChildFieldContext<TValue>(context: FieldContext<TValue>): context is ChildFieldContext<TValue> {\n return 'key' in context && isSignal(context.key);\n}\n\n/**\n * Service that provides field evaluation context by combining\n * field context with root form registry information.\n *\n * This service should be provided at the component level to ensure proper\n * isolation between different form instances.\n */\n@Injectable()\nexport class FieldContextRegistryService {\n private rootFormRegistry = inject(RootFormRegistryService);\n private logger = inject(DynamicFormLogger);\n\n /**\n * Creates an evaluation context for a field by combining:\n * - The field's current value\n * - The root form value from the registry\n * - The field path (if available from form context)\n * - Custom functions (if provided)\n */\n createEvaluationContext<TValue>(\n fieldContext: FieldContext<TValue>,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n formId = 'default',\n ): EvaluationContext {\n // Use untracked() to read the field value WITHOUT creating a reactive dependency.\n // This prevents infinite loops when logic functions are evaluated inside computed signals.\n const fieldValue = untracked(() => fieldContext.value());\n\n // Get form value using the unified method, wrapped in untracked() to prevent\n // reactive dependencies. This allows validators and dynamic values to access\n // form values without causing infinite loops.\n //\n // Without untracked():\n // 1. Validator runs and reads formValue via this context\n // 2. This creates a signal dependency on the form's value\n // 3. Any field change updates the form value signal\n // 4. All validators that read formValue re-run\n // 5. They read formValue again, creating new dependencies\n // 6. Infinite loop until browser freezes\n //\n // With untracked():\n // - Form value is read as a snapshot, no dependency is created\n // - Validators still run when their own field value changes (via fieldValue)\n // - Cross-field validation still works, just without cascading re-evaluation\n const formValue = untracked(() => this.rootFormRegistry.getFormValue(formId));\n const fieldPath = this.extractFieldPath(fieldContext);\n\n return {\n fieldValue,\n formValue,\n fieldPath,\n customFunctions: customFunctions || {},\n logger: this.logger,\n };\n }\n\n /**\n * Extracts the field path (key) for a given field context.\n */\n private extractFieldPath(fieldContext: FieldContext<unknown>): string {\n if (isChildFieldContext(fieldContext)) {\n try {\n return String(fieldContext.key());\n } catch (error) {\n this.logger.warn('Unable to extract field key:', error);\n }\n }\n\n // For root fields or when key is not available\n return '';\n }\n\n /**\n * Creates a REACTIVE evaluation context for logic functions.\n *\n * Unlike createEvaluationContext, this method does NOT use untracked(),\n * which allows logic functions (hidden, readonly, disabled, required) to\n * create reactive dependencies on form values.\n *\n * When a dependent field value changes, the logic function will be re-evaluated.\n *\n * IMPORTANT: For this to work correctly, the form value signal should be\n * registered with rootFormRegistry.registerFormValueSignal() BEFORE the\n * form is created. This ensures the logic function can read form values\n * during schema evaluation.\n *\n * NOTE: This should ONLY be used for logic functions, not validators.\n * Validators should use createEvaluationContext with untracked() to prevent\n * infinite reactive loops. Validators with cross-field dependencies should be\n * hoisted to form-level using validateTree.\n */\n createReactiveEvaluationContext<TValue>(\n fieldContext: FieldContext<TValue>,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n formId = 'default',\n ): EvaluationContext {\n const fieldValue = fieldContext.value();\n const formValue = this.rootFormRegistry.getFormValue(formId);\n const fieldPath = this.extractFieldPath(fieldContext);\n\n return {\n fieldValue,\n formValue,\n fieldPath,\n customFunctions: customFunctions || {},\n logger: this.logger,\n };\n }\n\n /**\n * Creates an evaluation context for display-only components (text fields, pages)\n * that don't have their own FieldContext.\n *\n * This is useful for:\n * - Text fields (display-only, not part of form schema)\n * - Pages (containers that need to evaluate visibility logic)\n *\n * Uses reactive form value access to allow logic re-evaluation when form values change.\n *\n * @param fieldPath - The key/path of the display-only component\n * @param customFunctions - Optional custom functions for expression evaluation\n * @param formId - Optional form identifier (defaults to 'default')\n */\n createDisplayOnlyContext(\n fieldPath: string,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n formId = 'default',\n ): EvaluationContext {\n const formValue = this.rootFormRegistry.getFormValue(formId);\n\n return {\n fieldValue: undefined,\n formValue,\n fieldPath,\n customFunctions: customFunctions || {},\n logger: this.logger,\n };\n }\n}\n","import { Injectable } from '@angular/core';\nimport { CustomFunction, CustomFunctionOptions, CustomFunctionScope } from '../expressions/custom-function-types';\nimport { AsyncCustomValidator, CustomValidator, HttpCustomValidator } from '../validation/validator-types';\n\n/**\n * Registry service for custom functions and validators\n *\n * This service maintains four separate registries:\n *\n * 1. **Custom Functions** - For conditional expressions (when/readonly/disabled)\n * - Used in: when conditions, readonly logic, disabled logic\n * - Return type: any value (typically boolean)\n * - Example: `isAdult: (ctx) => ctx.age >= 18`\n *\n * 2. **Custom Validators** - For synchronous validation using Angular's public FieldContext API\n * - Used in: validators array on fields\n * - Return type: ValidationError | ValidationError[] | null\n * - Example: `noSpaces: (ctx) => ctx.value().includes(' ') ? { kind: 'noSpaces' } : null`\n *\n * 3. **Async Validators** - For asynchronous validation (debouncing, database lookups, etc.)\n * - Used in: validators array on fields with type 'customAsync'\n * - Return type: Observable<ValidationError | ValidationError[] | null>\n * - Example: `checkUsername: (ctx) => userService.checkAvailability(ctx.value())`\n *\n * 4. **HTTP Validators** - For HTTP-based validation with automatic request cancellation\n * - Used in: validators array on fields with type 'customHttp'\n * - Configuration object with url, method, mapResponse, etc.\n * - Example: `{ url: '/api/check', method: 'GET', mapResponse: ... }`\n *\n * @example\n * ```typescript\n * // Register a custom function for expressions\n * registry.registerCustomFunction('isAdult', (ctx) => ctx.age >= 18);\n *\n * // Use in field configuration\n * {\n * key: 'alcoholPreference',\n * when: { function: 'isAdult' }\n * }\n *\n * // Register a custom validator\n * registry.registerValidator('noSpaces', (ctx) => {\n * const value = ctx.value();\n * return typeof value === 'string' && value.includes(' ')\n * ? { kind: 'noSpaces' }\n * : null;\n * });\n *\n * // Use in field configuration\n * {\n * key: 'username',\n * validators: [{ type: 'custom', functionName: 'noSpaces' }],\n * validationMessages: {\n * noSpaces: 'Spaces are not allowed'\n * }\n * }\n * ```\n */\n@Injectable()\nexport class FunctionRegistryService {\n private readonly customFunctions = new Map<string, CustomFunction>();\n private readonly customFunctionScopes = new Map<string, CustomFunctionScope>();\n private readonly derivationFunctions = new Map<string, CustomFunction>();\n private readonly validators = new Map<string, CustomValidator>();\n private readonly asyncValidators = new Map<string, AsyncCustomValidator>();\n private readonly httpValidators = new Map<string, HttpCustomValidator>();\n\n /**\n * Register a custom function for conditional expressions\n *\n * Custom functions are used for control flow logic (when/readonly/disabled),\n * NOT for validation. They return any value, typically boolean.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns any value\n * @param options - Optional configuration for the function\n *\n * @example\n * ```typescript\n * // Form-level function (default) - may access other fields\n * registry.registerCustomFunction('isAdult', (ctx) => ctx.formValue.age >= 18);\n *\n * // Field-level function - only uses current field value (performance optimization)\n * registry.registerCustomFunction('isEmpty', (ctx) => !ctx.fieldValue, { scope: 'field' });\n * ```\n */\n registerCustomFunction(name: string, fn: CustomFunction, options?: CustomFunctionOptions): void {\n this.customFunctions.set(name, fn);\n // Store scope (default to 'form' for conservative cross-field detection)\n this.customFunctionScopes.set(name, options?.scope ?? 'form');\n }\n\n /**\n * Get the scope of a registered custom function.\n *\n * @param name - The function name\n * @returns The function scope, or undefined if not registered\n */\n getCustomFunctionScope(name: string): CustomFunctionScope | undefined {\n return this.customFunctionScopes.get(name);\n }\n\n /**\n * Check if a custom function is field-scoped (no cross-field dependencies).\n *\n * @param name - The function name\n * @returns true if the function is field-scoped, false if form-scoped or not registered\n */\n isFieldScopedFunction(name: string): boolean {\n return this.customFunctionScopes.get(name) === 'field';\n }\n\n /**\n * Get all custom functions as an object\n */\n getCustomFunctions(): Record<string, CustomFunction> {\n return Object.fromEntries(this.customFunctions);\n }\n\n /**\n * Clear all custom functions and their scopes\n */\n clearCustomFunctions(): void {\n this.customFunctions.clear();\n this.customFunctionScopes.clear();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Derivation Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a derivation function for value derivation logic.\n *\n * Derivation functions compute derived values and are called when a\n * `DerivationLogicConfig` references them by `functionName`.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns the derived value\n *\n * @example\n * ```typescript\n * registry.registerDerivationFunction('getCurrencyForCountry', (ctx) => {\n * const countryToCurrency = { 'USA': 'USD', 'Germany': 'EUR', 'UK': 'GBP' };\n * return countryToCurrency[ctx.formValue.country] ?? 'USD';\n * });\n * ```\n */\n registerDerivationFunction(name: string, fn: CustomFunction): void {\n this.derivationFunctions.set(name, fn);\n }\n\n /**\n * Get a derivation function by name\n */\n getDerivationFunction(name: string): CustomFunction | undefined {\n return this.derivationFunctions.get(name);\n }\n\n /**\n * Get all derivation functions as an object\n */\n getDerivationFunctions(): Record<string, CustomFunction> {\n return Object.fromEntries(this.derivationFunctions);\n }\n\n /**\n * Set derivation functions from a config object.\n * Only updates functions if their references have changed.\n *\n * @param derivations - Object mapping function names to derivation functions\n */\n setDerivationFunctions(derivations: Record<string, CustomFunction> | undefined): void {\n this.setRegistryIfChanged(this.derivationFunctions, derivations);\n }\n\n /**\n * Clear all derivation functions\n */\n clearDerivationFunctions(): void {\n this.derivationFunctions.clear();\n }\n\n /**\n * Register a custom validator using Angular's public FieldContext API\n *\n * Validators receive the full FieldContext, allowing access to:\n * - Current field value: `ctx.value()`\n * - Field state: `ctx.state` (errors, touched, dirty, etc.)\n * - Other field values: `ctx.valueOf(path)` (public API!)\n * - Other field states: `ctx.stateOf(path)`\n * - Parameters from JSON configuration via second argument\n *\n * @param name - Unique identifier for the validator\n * @param fn - Validator function (ctx, params?) => ValidationError | ValidationError[] | null\n *\n * @example Single Field Validation\n * ```typescript\n * registry.registerValidator('noSpaces', (ctx) => {\n * const value = ctx.value();\n * if (typeof value === 'string' && value.includes(' ')) {\n * return { kind: 'noSpaces' };\n * }\n * return null;\n * });\n * ```\n *\n * @example Cross-Field Validation (Public API)\n * ```typescript\n * registry.registerValidator('lessThan', (ctx, params) => {\n * const value = ctx.value();\n * const compareToPath = params?.field as string;\n *\n * // Use valueOf() to access other fields - public API!\n * const otherValue = ctx.valueOf(compareToPath as any);\n *\n * if (otherValue !== undefined && value >= otherValue) {\n * return { kind: 'notLessThan' };\n * }\n * return null;\n * });\n * ```\n *\n * @example Multiple Errors (Cross-Field Validation)\n * ```typescript\n * registry.registerValidator('validateDateRange', (ctx) => {\n * const errors: ValidationError[] = [];\n * const startDate = ctx.valueOf('startDate' as any);\n * const endDate = ctx.valueOf('endDate' as any);\n *\n * if (!startDate) errors.push({ kind: 'startDateRequired' });\n * if (!endDate) errors.push({ kind: 'endDateRequired' });\n * if (startDate && endDate && startDate > endDate) {\n * errors.push({ kind: 'invalidDateRange' });\n * }\n *\n * return errors.length > 0 ? errors : null;\n * });\n * ```\n */\n registerValidator(name: string, fn: CustomValidator): void {\n this.validators.set(name, fn);\n }\n\n /**\n * Get a validator by name\n */\n getValidator(name: string): CustomValidator | undefined {\n return this.validators.get(name);\n }\n\n /**\n * Clear all validators\n */\n clearValidators(): void {\n this.validators.clear();\n }\n\n /**\n * Register an async validator using Angular's public validateAsync() API\n *\n * Async validators return Observables for asynchronous validation logic.\n * Use for debouncing, database lookups, or complex async business logic.\n *\n * @param name - Unique identifier for the async validator\n * @param fn - Async validator function (ctx, params?) => Observable<ValidationError | ValidationError[] | null>\n *\n * @example Debounced Username Check\n * ```typescript\n * registry.registerAsyncValidator('checkUsernameAvailable', (ctx) => {\n * const username = ctx.value();\n * return of(username).pipe(\n * debounceTime(300),\n * switchMap(name => userService.checkAvailability(name)),\n * map(available => available ? null : { kind: 'usernameTaken' })\n * );\n * });\n * ```\n *\n * @example Async Cross-Field Validation\n * ```typescript\n * registry.registerAsyncValidator('validatePasswordStrength', (ctx) => {\n * const password = ctx.value();\n * const email = ctx.valueOf('email' as any);\n * return passwordService.checkStrength(password, email).pipe(\n * map(result => result.strong ? null : { kind: 'weakPassword' })\n * );\n * });\n * ```\n */\n registerAsyncValidator(name: string, fn: AsyncCustomValidator): void {\n this.asyncValidators.set(name, fn);\n }\n\n /**\n * Get an async validator by name\n */\n getAsyncValidator(name: string): AsyncCustomValidator | undefined {\n return this.asyncValidators.get(name);\n }\n\n /**\n * Clear all async validators\n */\n clearAsyncValidators(): void {\n this.asyncValidators.clear();\n }\n\n /**\n * Register an HTTP validator configuration using Angular's public validateHttp() API\n *\n * HTTP validators provide optimized HTTP validation with automatic request cancellation,\n * caching, and debouncing. Preferred over AsyncCustomValidator for HTTP requests.\n *\n * @param name - Unique identifier for the HTTP validator\n * @param config - HTTP validator configuration object\n *\n * @example Username Availability Check\n * ```typescript\n * registry.registerHttpValidator('checkUsername', {\n * url: (ctx) => `/api/users/check-username?username=${encodeURIComponent(ctx.value())}`,\n * method: 'GET',\n * mapResponse: (response, ctx) => {\n * return response.available ? null : { kind: 'usernameTaken' };\n * }\n * });\n * ```\n *\n * @example POST Request with Body\n * ```typescript\n * registry.registerHttpValidator('validateAddress', {\n * url: '/api/validate-address',\n * method: 'POST',\n * body: (ctx) => ({\n * street: ctx.valueOf('street' as any),\n * city: ctx.valueOf('city' as any),\n * zipCode: ctx.value()\n * }),\n * mapResponse: (response) => {\n * return response.valid ? null : { kind: 'invalidAddress' };\n * },\n * debounceTime: 500\n * });\n * ```\n */\n registerHttpValidator(name: string, config: HttpCustomValidator): void {\n this.httpValidators.set(name, config);\n }\n\n /**\n * Get an HTTP validator by name\n */\n getHttpValidator(name: string): HttpCustomValidator | undefined {\n return this.httpValidators.get(name);\n }\n\n /**\n * Clear all HTTP validators\n */\n clearHttpValidators(): void {\n this.httpValidators.clear();\n }\n\n /**\n * Generic helper to set registry values only if they have changed\n * @param registry - The Map to update\n * @param values - Object mapping keys to values\n */\n private setRegistryIfChanged<T>(registry: Map<string, T>, values: Record<string, T> | undefined): void {\n if (!values) return;\n\n const entries = Object.entries(values);\n const hasChanges = entries.some(([name, value]) => registry.get(name) !== value);\n\n if (hasChanges) {\n entries.forEach(([name, value]) => registry.set(name, value));\n }\n }\n\n /**\n * Set validators from a config object\n * Only updates validators if their references have changed\n *\n * @param validators - Object mapping validator names to validator functions\n */\n setValidators(validators: Record<string, CustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.validators, validators);\n }\n\n /**\n * Set async validators from a config object\n * Only updates validators if their references have changed\n *\n * @param asyncValidators - Object mapping validator names to async validator configs\n */\n setAsyncValidators(asyncValidators: Record<string, AsyncCustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.asyncValidators, asyncValidators);\n }\n\n /**\n * Set HTTP validators from a config object\n * Only updates validators if their references have changed\n *\n * @param httpValidators - Object mapping validator names to HTTP validator configs\n */\n setHttpValidators(httpValidators: Record<string, HttpCustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.httpValidators, httpValidators);\n }\n\n /**\n * Clear everything (functions and all validators)\n */\n clearAll(): void {\n this.clearCustomFunctions();\n this.clearDerivationFunctions();\n this.clearValidators();\n this.clearAsyncValidators();\n this.clearHttpValidators();\n }\n}\n","/**\n * Compares two values using the specified comparison operator.\n *\n * Supports various comparison types including equality, numerical comparisons,\n * string operations, and regular expression matching. Type coercion is applied\n * for numerical and string operations as needed.\n *\n * @param actual - The value to compare\n * @param expected - The value to compare against\n * @param operator - Comparison operator to use\n * @returns True if the comparison succeeds, false otherwise\n *\n * @example\n * ```typescript\n * // Equality checks\n * compareValues(10, 10, 'equals') // true\n * compareValues('test', 'other', 'notEquals') // true\n *\n * // Numerical comparisons\n * compareValues(15, 10, 'greater') // true\n * compareValues('5', 3, 'greaterOrEqual') // true (coerced to numbers)\n *\n * // String operations\n * compareValues('hello world', 'world', 'contains') // true\n * compareValues('prefix-test', 'prefix', 'startsWith') // true\n * compareValues('test.jpg', '.jpg', 'endsWith') // true\n *\n * // Regular expression matching\n * compareValues('test123', '^test\\\\d+$', 'matches') // true\n * compareValues('invalid', '[invalid', 'matches') // false (invalid regex)\n * ```\n */\nexport function compareValues(actual: unknown, expected: unknown, operator: string): boolean {\n switch (operator) {\n case 'equals':\n return actual === expected;\n case 'notEquals':\n return actual !== expected;\n case 'greater':\n return Number(actual) > Number(expected);\n case 'less':\n return Number(actual) < Number(expected);\n case 'greaterOrEqual':\n return Number(actual) >= Number(expected);\n case 'lessOrEqual':\n return Number(actual) <= Number(expected);\n case 'contains':\n return String(actual).includes(String(expected));\n case 'startsWith':\n return String(actual).startsWith(String(expected));\n case 'endsWith':\n return String(actual).endsWith(String(expected));\n case 'matches':\n try {\n return new RegExp(String(expected)).test(String(actual));\n } catch {\n return false;\n }\n default:\n return false;\n }\n}\n\n/**\n * Retrieves a nested value from an object using dot notation path.\n *\n * Safely traverses object properties using a dot-separated path string.\n * Returns undefined if any part of the path is missing or if the traversal\n * encounters a non-object value.\n *\n * @param obj - The object to traverse\n * @param path - Dot-separated path to the desired property\n * @returns The value at the specified path, or undefined if not found\n *\n * @example\n * ```typescript\n * const data = {\n * user: {\n * profile: {\n * name: 'John',\n * age: 30\n * },\n * settings: { theme: 'dark' }\n * }\n * };\n *\n * getNestedValue(data, 'user.profile.name') // 'John'\n * getNestedValue(data, 'user.settings.theme') // 'dark'\n * getNestedValue(data, 'user.profile.email') // undefined\n * getNestedValue(data, 'nonexistent.path') // undefined\n * getNestedValue(null, 'any.path') // undefined\n * ```\n */\nexport function getNestedValue(obj: unknown, path: string): unknown {\n return path.split('.').reduce((current: unknown, key: string) => {\n return current && typeof current === 'object' ? (current as Record<string, unknown>)[key] : undefined;\n }, obj);\n}\n","import { DynamicFormError } from '../../../errors/dynamic-form-error';\n\n/**\n * Token types for expression parsing\n */\nexport enum TokenType {\n // Literals\n NUMBER = 'NUMBER',\n STRING = 'STRING',\n TRUE = 'TRUE',\n FALSE = 'FALSE',\n NULL = 'NULL',\n UNDEFINED = 'UNDEFINED',\n\n // Identifiers\n IDENTIFIER = 'IDENTIFIER',\n\n // Operators\n PLUS = 'PLUS',\n MINUS = 'MINUS',\n MULTIPLY = 'MULTIPLY',\n DIVIDE = 'DIVIDE',\n MODULO = 'MODULO',\n\n // Comparison\n EQUAL = 'EQUAL',\n NOT_EQUAL = 'NOT_EQUAL',\n GREATER = 'GREATER',\n LESS = 'LESS',\n GREATER_EQUAL = 'GREATER_EQUAL',\n LESS_EQUAL = 'LESS_EQUAL',\n\n // Logical\n AND = 'AND',\n OR = 'OR',\n NOT = 'NOT',\n\n // Punctuation\n DOT = 'DOT',\n COMMA = 'COMMA',\n LPAREN = 'LPAREN',\n RPAREN = 'RPAREN',\n LBRACKET = 'LBRACKET',\n RBRACKET = 'RBRACKET',\n\n // Special\n EOF = 'EOF',\n}\n\n/**\n * Token with type, value, and position\n */\nexport interface Token {\n type: TokenType;\n value: string;\n position: number;\n}\n\n/**\n * AST Node types\n */\nexport type ASTNode = LiteralNode | IdentifierNode | MemberAccessNode | BinaryOpNode | UnaryOpNode | CallExpressionNode | ArrayLiteralNode;\n\nexport interface LiteralNode {\n type: 'Literal';\n value: string | number | boolean | null | undefined;\n}\n\nexport interface IdentifierNode {\n type: 'Identifier';\n name: string;\n}\n\nexport interface MemberAccessNode {\n type: 'MemberAccess';\n object: ASTNode;\n property: string;\n}\n\nexport interface BinaryOpNode {\n type: 'BinaryOp';\n operator: string;\n left: ASTNode;\n right: ASTNode;\n}\n\nexport interface UnaryOpNode {\n type: 'UnaryOp';\n operator: string;\n operand: ASTNode;\n}\n\nexport interface CallExpressionNode {\n type: 'CallExpression';\n callee: ASTNode;\n arguments: ASTNode[];\n}\n\nexport interface ArrayLiteralNode {\n type: 'ArrayLiteral';\n elements: ASTNode[];\n}\n\n/**\n * Parser error with position information\n */\nexport class ExpressionParserError extends DynamicFormError {\n constructor(\n message: string,\n public position: number,\n public expression: string,\n ) {\n super(`${message} at position ${position} in expression: ${expression}`);\n this.name = 'ExpressionParserError';\n }\n}\n","import { Token, TokenType, ExpressionParserError } from './types';\n\n/**\n * Tokenizes an expression string into tokens\n */\nexport class Tokenizer {\n private position = 0;\n private readonly expression: string;\n\n constructor(expression: string) {\n this.expression = expression;\n }\n\n /**\n * Tokenize the entire expression\n */\n tokenize(): Token[] {\n const tokens: Token[] = [];\n\n while (this.position < this.expression.length) {\n this.skipWhitespace();\n\n if (this.position >= this.expression.length) {\n break;\n }\n\n const token = this.nextToken();\n tokens.push(token);\n }\n\n tokens.push({ type: TokenType.EOF, value: '', position: this.position });\n return tokens;\n }\n\n private skipWhitespace(): void {\n while (this.position < this.expression.length && /\\s/.test(this.expression[this.position])) {\n this.position++;\n }\n }\n\n private nextToken(): Token {\n const char = this.expression[this.position];\n\n // String literals\n if (char === '\"' || char === \"'\") {\n return this.readString(char);\n }\n\n // Numbers\n if (/[0-9]/.test(char)) {\n return this.readNumber();\n }\n\n // Identifiers and keywords\n if (/[a-zA-Z_$]/.test(char)) {\n return this.readIdentifierOrKeyword();\n }\n\n // Operators and punctuation\n return this.readOperatorOrPunctuation();\n }\n\n private readString(quote: string): Token {\n const start = this.position;\n this.position++; // Skip opening quote\n\n let value = '';\n while (this.position < this.expression.length) {\n const char = this.expression[this.position];\n\n if (char === quote) {\n this.position++; // Skip closing quote\n return { type: TokenType.STRING, value, position: start };\n }\n\n if (char === '\\\\' && this.position + 1 < this.expression.length) {\n // Handle escape sequences\n this.position++;\n const nextChar = this.expression[this.position];\n switch (nextChar) {\n case 'n':\n value += '\\n';\n break;\n case 't':\n value += '\\t';\n break;\n case 'r':\n value += '\\r';\n break;\n case '\\\\':\n value += '\\\\';\n break;\n case quote:\n value += quote;\n break;\n default:\n value += nextChar;\n }\n this.position++;\n } else {\n value += char;\n this.position++;\n }\n }\n\n throw new ExpressionParserError('Unterminated string literal', start, this.expression);\n }\n\n private readNumber(): Token {\n const start = this.position;\n let value = '';\n\n while (this.position < this.expression.length && /[0-9.]/.test(this.expression[this.position])) {\n value += this.expression[this.position];\n this.position++;\n }\n\n return { type: TokenType.NUMBER, value, position: start };\n }\n\n private readIdentifierOrKeyword(): Token {\n const start = this.position;\n let value = '';\n\n while (this.position < this.expression.length && /[a-zA-Z0-9_$]/.test(this.expression[this.position])) {\n value += this.expression[this.position];\n this.position++;\n }\n\n // Check for keywords\n const type = this.getKeywordType(value);\n return { type, value, position: start };\n }\n\n private getKeywordType(value: string): TokenType {\n switch (value) {\n case 'true':\n return TokenType.TRUE;\n case 'false':\n return TokenType.FALSE;\n case 'null':\n return TokenType.NULL;\n case 'undefined':\n return TokenType.UNDEFINED;\n default:\n return TokenType.IDENTIFIER;\n }\n }\n\n private readOperatorOrPunctuation(): Token {\n const start = this.position;\n const char = this.expression[this.position];\n const nextChar = this.position + 1 < this.expression.length ? this.expression[this.position + 1] : '';\n const thirdChar = this.position + 2 < this.expression.length ? this.expression[this.position + 2] : '';\n\n // Three-character operators - check these first!\n const threeChar = char + nextChar + thirdChar;\n if (threeChar === '===') {\n this.position += 3;\n return { type: TokenType.EQUAL, value: '===', position: start };\n }\n if (threeChar === '!==') {\n this.position += 3;\n return { type: TokenType.NOT_EQUAL, value: '!==', position: start };\n }\n\n // Two-character operators\n const twoChar = char + nextChar;\n switch (twoChar) {\n case '==':\n this.position += 2;\n return { type: TokenType.EQUAL, value: '==', position: start };\n case '!=':\n this.position += 2;\n return { type: TokenType.NOT_EQUAL, value: '!=', position: start };\n case '>=':\n this.position += 2;\n return { type: TokenType.GREATER_EQUAL, value: '>=', position: start };\n case '<=':\n this.position += 2;\n return { type: TokenType.LESS_EQUAL, value: '<=', position: start };\n case '&&':\n this.position += 2;\n return { type: TokenType.AND, value: '&&', position: start };\n case '||':\n this.position += 2;\n return { type: TokenType.OR, value: '||', position: start };\n }\n\n // Single-character operators and punctuation\n this.position++;\n switch (char) {\n case '+':\n return { type: TokenType.PLUS, value: '+', position: start };\n case '-':\n return { type: TokenType.MINUS, value: '-', position: start };\n case '*':\n return { type: TokenType.MULTIPLY, value: '*', position: start };\n case '/':\n return { type: TokenType.DIVIDE, value: '/', position: start };\n case '%':\n return { type: TokenType.MODULO, value: '%', position: start };\n case '>':\n return { type: TokenType.GREATER, value: '>', position: start };\n case '<':\n return { type: TokenType.LESS, value: '<', position: start };\n case '!':\n return { type: TokenType.NOT, value: '!', position: start };\n case '.':\n return { type: TokenType.DOT, value: '.', position: start };\n case ',':\n return { type: TokenType.COMMA, value: ',', position: start };\n case '(':\n return { type: TokenType.LPAREN, value: '(', position: start };\n case ')':\n return { type: TokenType.RPAREN, value: ')', position: start };\n case '[':\n return { type: TokenType.LBRACKET, value: '[', position: start };\n case ']':\n return { type: TokenType.RBRACKET, value: ']', position: start };\n default:\n throw new ExpressionParserError(`Unexpected character: ${char}`, start, this.expression);\n }\n }\n}\n","import { Token, TokenType, ASTNode, ExpressionParserError } from './types';\nimport { Tokenizer } from './tokenizer';\n\n/**\n * Parses tokens into an Abstract Syntax Tree (AST)\n * Uses recursive descent parsing with operator precedence\n */\nexport class Parser {\n private tokens: Token[] = [];\n private current = 0;\n private readonly expression: string;\n\n constructor(expression: string) {\n this.expression = expression;\n }\n\n /**\n * Parse the expression into an AST\n */\n parse(): ASTNode {\n const tokenizer = new Tokenizer(this.expression);\n this.tokens = tokenizer.tokenize();\n this.current = 0;\n\n if (this.isAtEnd()) {\n throw new ExpressionParserError('Empty expression', 0, this.expression);\n }\n\n return this.parseExpression();\n }\n\n private parseExpression(): ASTNode {\n return this.parseLogicalOr();\n }\n\n private parseLogicalOr(): ASTNode {\n let node = this.parseLogicalAnd();\n\n while (this.match(TokenType.OR)) {\n const operator = this.previous().value;\n const right = this.parseLogicalAnd();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseLogicalAnd(): ASTNode {\n let node = this.parseEquality();\n\n while (this.match(TokenType.AND)) {\n const operator = this.previous().value;\n const right = this.parseEquality();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseEquality(): ASTNode {\n let node = this.parseComparison();\n\n while (this.match(TokenType.EQUAL, TokenType.NOT_EQUAL)) {\n const operator = this.previous().value;\n const right = this.parseComparison();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseComparison(): ASTNode {\n let node = this.parseAddition();\n\n while (this.match(TokenType.GREATER, TokenType.GREATER_EQUAL, TokenType.LESS, TokenType.LESS_EQUAL)) {\n const operator = this.previous().value;\n const right = this.parseAddition();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseAddition(): ASTNode {\n let node = this.parseMultiplication();\n\n while (this.match(TokenType.PLUS, TokenType.MINUS)) {\n const operator = this.previous().value;\n const right = this.parseMultiplication();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseMultiplication(): ASTNode {\n let node = this.parseUnary();\n\n while (this.match(TokenType.MULTIPLY, TokenType.DIVIDE, TokenType.MODULO)) {\n const operator = this.previous().value;\n const right = this.parseUnary();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseUnary(): ASTNode {\n if (this.match(TokenType.NOT, TokenType.MINUS, TokenType.PLUS)) {\n const operator = this.previous().value;\n const operand = this.parseUnary();\n return { type: 'UnaryOp', operator, operand };\n }\n\n return this.parsePostfix();\n }\n\n private parsePostfix(): ASTNode {\n let node = this.parsePrimary();\n\n while (true) {\n if (this.match(TokenType.DOT)) {\n // Member access: obj.property\n if (!this.check(TokenType.IDENTIFIER)) {\n throw new ExpressionParserError('Expected property name after \".\"', this.peek().position, this.expression);\n }\n const property = this.advance().value;\n node = { type: 'MemberAccess', object: node, property };\n } else if (this.match(TokenType.LPAREN)) {\n // Function call: func()\n const args = this.parseArgumentList();\n this.consume(TokenType.RPAREN, 'Expected \")\" after arguments');\n node = { type: 'CallExpression', callee: node, arguments: args };\n } else {\n break;\n }\n }\n\n return node;\n }\n\n private parsePrimary(): ASTNode {\n // Literals\n if (this.match(TokenType.TRUE)) {\n return { type: 'Literal', value: true };\n }\n\n if (this.match(TokenType.FALSE)) {\n return { type: 'Literal', value: false };\n }\n\n if (this.match(TokenType.NULL)) {\n return { type: 'Literal', value: null };\n }\n\n if (this.match(TokenType.UNDEFINED)) {\n return { type: 'Literal', value: undefined };\n }\n\n if (this.match(TokenType.NUMBER)) {\n return { type: 'Literal', value: parseFloat(this.previous().value) };\n }\n\n if (this.match(TokenType.STRING)) {\n return { type: 'Literal', value: this.previous().value };\n }\n\n // Array literal\n if (this.match(TokenType.LBRACKET)) {\n const elements = this.parseArrayElements();\n this.consume(TokenType.RBRACKET, 'Expected \"]\" after array elements');\n return { type: 'ArrayLiteral', elements };\n }\n\n // Identifier\n if (this.match(TokenType.IDENTIFIER)) {\n return { type: 'Identifier', name: this.previous().value };\n }\n\n // Grouped expression\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseExpression();\n this.consume(TokenType.RPAREN, 'Expected \")\" after expression');\n return expr;\n }\n\n throw new ExpressionParserError(`Unexpected token: ${this.peek().value}`, this.peek().position, this.expression);\n }\n\n private parseArgumentList(): ASTNode[] {\n const args: ASTNode[] = [];\n\n if (!this.check(TokenType.RPAREN)) {\n do {\n args.push(this.parseExpression());\n } while (this.match(TokenType.COMMA));\n }\n\n return args;\n }\n\n private parseArrayElements(): ASTNode[] {\n const elements: ASTNode[] = [];\n\n if (!this.check(TokenType.RBRACKET)) {\n do {\n elements.push(this.parseExpression());\n } while (this.match(TokenType.COMMA));\n }\n\n return elements;\n }\n\n private match(...types: TokenType[]): boolean {\n for (const type of types) {\n if (this.check(type)) {\n this.advance();\n return true;\n }\n }\n return false;\n }\n\n private check(type: TokenType): boolean {\n if (this.isAtEnd()) return false;\n return this.peek().type === type;\n }\n\n private advance(): Token {\n if (!this.isAtEnd()) this.current++;\n return this.previous();\n }\n\n private isAtEnd(): boolean {\n return this.peek().type === TokenType.EOF;\n }\n\n private peek(): Token {\n return this.tokens[this.current];\n }\n\n private previous(): Token {\n return this.tokens[this.current - 1];\n }\n\n private consume(type: TokenType, message: string): Token {\n if (this.check(type)) return this.advance();\n\n throw new ExpressionParserError(message, this.peek().position, this.expression);\n }\n}\n","import { ASTNode, ExpressionParserError } from './types';\n\n/**\n * Evaluation context for safe expression evaluation\n */\nexport interface EvaluationScope {\n [key: string]: unknown;\n}\n\n/**\n * Security Model: Whitelist-only approach for method calls\n *\n * A method is considered SAFE if it meets ALL criteria:\n * 1. Pure data access/transformation (no side effects)\n * 2. No code execution capabilities\n * 3. No global state modification\n * 4. No prototype chain modification\n * 5. No information disclosure about system internals\n *\n * Methods NOT included (unsafe):\n * - constructor: Could enable code execution via Function constructor\n * - valueOf: Could enable type confusion attacks\n * - __proto__, __defineGetter__, etc: Direct prototype manipulation\n * - hasOwnProperty, isPrototypeOf, propertyIsEnumerable: Leak object structure\n * - toLocaleString: Could expose locale/system information\n */\n\n/**\n * Type-safe method whitelists derived from TypeScript primitive types\n * Only methods explicitly listed here are allowed - this is a whitelist-only approach\n */\nconst STRING_SAFE_METHODS: ReadonlyArray<keyof string> = [\n 'charAt',\n 'charCodeAt',\n 'concat',\n 'endsWith',\n 'includes',\n 'indexOf',\n 'lastIndexOf',\n 'match',\n 'padEnd',\n 'padStart',\n 'repeat',\n 'replace',\n 'search',\n 'slice',\n 'split',\n 'startsWith',\n 'substring',\n 'toLowerCase',\n 'toUpperCase',\n 'trim',\n 'trimEnd',\n 'trimStart',\n 'toString',\n] as const;\n\nconst NUMBER_SAFE_METHODS: ReadonlyArray<keyof number> = ['toExponential', 'toFixed', 'toPrecision', 'toString'] as const;\n\nconst ARRAY_SAFE_METHODS: ReadonlyArray<keyof Array<unknown>> = [\n 'concat',\n 'every',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'includes',\n 'indexOf',\n 'join',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'toString',\n 'entries',\n 'keys',\n 'values',\n] as const;\n\nconst DATE_SAFE_METHODS: ReadonlyArray<keyof Date> = [\n 'getDate',\n 'getDay',\n 'getFullYear',\n 'getHours',\n 'getMilliseconds',\n 'getMinutes',\n 'getMonth',\n 'getSeconds',\n 'getTime',\n 'getTimezoneOffset',\n 'getUTCDate',\n 'getUTCDay',\n 'getUTCFullYear',\n 'getUTCHours',\n 'getUTCMilliseconds',\n 'getUTCMinutes',\n 'getUTCMonth',\n 'getUTCSeconds',\n 'toDateString',\n 'toISOString',\n 'toJSON',\n 'toString',\n 'toTimeString',\n 'toUTCString',\n] as const;\n\n/**\n * Whitelist of safe methods that can be called on values\n * Using Set for O(1) lookup performance\n */\nconst SAFE_METHODS: Record<string, ReadonlySet<string>> = {\n string: new Set(STRING_SAFE_METHODS as readonly string[]),\n number: new Set(NUMBER_SAFE_METHODS as readonly string[]),\n array: new Set(ARRAY_SAFE_METHODS as readonly string[]),\n date: new Set(DATE_SAFE_METHODS as readonly string[]),\n};\n\n/**\n * Blacklist of property names that should not be accessible\n * These properties can leak information about object structure or enable attacks\n */\nconst BLOCKED_PROPERTIES = new Set<string>([\n 'constructor',\n '__proto__',\n 'prototype',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__',\n]);\n\n/**\n * Safely evaluates an AST node with a given context\n */\nexport class Evaluator {\n private readonly scope: EvaluationScope;\n private readonly expression: string;\n\n constructor(scope: EvaluationScope, expression: string) {\n this.scope = scope;\n this.expression = expression;\n }\n\n /**\n * Evaluate an AST node\n */\n evaluate(node: ASTNode): unknown {\n switch (node.type) {\n case 'Literal':\n return node.value;\n\n case 'Identifier':\n return this.evaluateIdentifier(node.name);\n\n case 'MemberAccess':\n return this.evaluateMemberAccess(node);\n\n case 'BinaryOp':\n return this.evaluateBinaryOp(node);\n\n case 'UnaryOp':\n return this.evaluateUnaryOp(node);\n\n case 'CallExpression':\n return this.evaluateCallExpression(node);\n\n case 'ArrayLiteral':\n return this.evaluateArrayLiteral(node);\n\n default:\n throw new ExpressionParserError(`Unknown node type: ${(node as { type: string }).type}`, 0, this.expression);\n }\n }\n\n private evaluateIdentifier(name: string): unknown {\n if (name in this.scope) {\n return this.scope[name];\n }\n return undefined;\n }\n\n private evaluateMemberAccess(node: { object: ASTNode; property: string }): unknown {\n const obj = this.evaluate(node.object);\n\n if (obj === null || obj === undefined) {\n return undefined;\n }\n\n // Block access to dangerous properties that could leak information or enable attacks\n if (BLOCKED_PROPERTIES.has(node.property)) {\n throw new ExpressionParserError(`Property \"${node.property}\" is not accessible for security reasons`, 0, this.expression);\n }\n\n // Allow property access on plain objects and primitives\n if (typeof obj === 'object' || typeof obj === 'string' || typeof obj === 'number') {\n return (obj as Record<string, unknown>)[node.property];\n }\n\n return undefined;\n }\n\n private evaluateBinaryOp(node: { operator: string; left: ASTNode; right: ASTNode }): unknown {\n // Handle short-circuit evaluation for logical operators\n if (node.operator === '&&') {\n const left = this.evaluate(node.left);\n return left ? this.evaluate(node.right) : left;\n }\n if (node.operator === '||') {\n const left = this.evaluate(node.left);\n return left ? left : this.evaluate(node.right);\n }\n\n // For all other operators, evaluate both sides\n const left = this.evaluate(node.left);\n const right = this.evaluate(node.right);\n\n switch (node.operator) {\n // Arithmetic\n case '+':\n return (left as number) + (right as number);\n case '-':\n return (left as number) - (right as number);\n case '*':\n return (left as number) * (right as number);\n case '/':\n if (right === 0) return null;\n return (left as number) / (right as number);\n case '%':\n if (right === 0) return null;\n return (left as number) % (right as number);\n\n // Comparison - using == and != intentionally for loose equality\n case '==':\n return left == right;\n case '===':\n return left === right;\n case '!=':\n return left != right;\n case '!==':\n return left !== right;\n case '>':\n return (left as number) > (right as number);\n case '<':\n return (left as number) < (right as number);\n case '>=':\n return (left as number) >= (right as number);\n case '<=':\n return (left as number) <= (right as number);\n\n default:\n throw new ExpressionParserError(`Unknown binary operator: ${node.operator}`, 0, this.expression);\n }\n }\n\n private evaluateUnaryOp(node: { operator: string; operand: ASTNode }): unknown {\n const operand = this.evaluate(node.operand);\n\n switch (node.operator) {\n case '!':\n return !operand;\n case '-':\n return -(operand as number);\n case '+':\n return +(operand as number);\n default:\n throw new ExpressionParserError(`Unknown unary operator: ${node.operator}`, 0, this.expression);\n }\n }\n\n private evaluateCallExpression(node: { callee: ASTNode; arguments: ASTNode[] }): unknown {\n // Only allow method calls (member access), not arbitrary function calls\n if (node.callee.type !== 'MemberAccess') {\n throw new ExpressionParserError('Only method calls are allowed, not arbitrary function calls', 0, this.expression);\n }\n\n const obj = this.evaluate(node.callee.object);\n const methodName = node.callee.property;\n\n // Block access to dangerous properties (must check before method call)\n if (BLOCKED_PROPERTIES.has(methodName)) {\n throw new ExpressionParserError(`Property \"${methodName}\" is not accessible for security reasons`, 0, this.expression);\n }\n\n // Check if the method is in the instance method whitelist\n if (!this.isMethodSafe(obj, methodName)) {\n throw new ExpressionParserError(`Method \"${methodName}\" is not allowed for security reasons`, 0, this.expression);\n }\n\n // Evaluate arguments\n const args = node.arguments.map((arg) => this.evaluate(arg));\n\n // Call the method with proper `this` binding\n const method = (obj as Record<string, unknown>)[methodName];\n if (typeof method === 'function') {\n // Use .call() to properly bind `this` context\n return (method as (...args: unknown[]) => unknown).call(obj, ...args);\n }\n\n return undefined;\n }\n\n private evaluateArrayLiteral(node: { elements: ASTNode[] }): unknown {\n return node.elements.map((element) => this.evaluate(element));\n }\n\n private isMethodSafe(obj: unknown, methodName: string): boolean {\n if (obj === null || obj === undefined) {\n return false;\n }\n\n const type = Array.isArray(obj) ? 'array' : obj instanceof Date ? 'date' : typeof obj;\n\n const safeMethods = SAFE_METHODS[type];\n if (!safeMethods) {\n return false;\n }\n\n return safeMethods.has(methodName);\n }\n}\n","import { Parser } from './parser';\nimport { Evaluator, EvaluationScope } from './evaluator';\nimport { ASTNode, ExpressionParserError } from './types';\n\n/**\n * Maximum cache size to prevent memory issues\n */\nconst MAX_AST_CACHE_SIZE = 1000;\n\n/**\n * LRU Cache implementation for AST nodes\n * Tracks access order to evict least-recently-used entries\n */\nclass LRUCache<K, V> {\n private cache = new Map<K, V>();\n private maxSize: number;\n\n constructor(maxSize: number) {\n this.maxSize = maxSize;\n }\n\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n // Move to end (most recently used)\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n return value;\n }\n\n set(key: K, value: V): void {\n // Delete if exists to update position\n if (this.cache.has(key)) {\n this.cache.delete(key);\n }\n\n // Add to end (most recently used)\n this.cache.set(key, value);\n\n // Evict least recently used if over limit\n if (this.cache.size > this.maxSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) {\n this.cache.delete(firstKey);\n }\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n/**\n * Cache for parsed AST nodes to improve performance\n */\nconst astCache = new LRUCache<string, ASTNode>(MAX_AST_CACHE_SIZE);\n\n/**\n * Secure expression parser that uses AST-based evaluation instead of eval() or new Function()\n *\n * This parser provides:\n * - Security: No arbitrary code execution, only whitelisted operations\n * - Performance: AST caching for repeated expressions\n * - Better errors: Clear error messages with position information\n * - Type safety: Strongly typed AST and evaluation\n */\nexport class ExpressionParser {\n /**\n * Parse an expression string into an AST\n * Results are cached for performance using LRU eviction\n */\n static parse(expression: string): ASTNode {\n // Check cache first\n const cached = astCache.get(expression);\n if (cached) {\n return cached;\n }\n\n // Parse the expression\n const parser = new Parser(expression);\n const ast = parser.parse();\n\n // Cache the result (LRU cache handles eviction automatically)\n astCache.set(expression, ast);\n\n return ast;\n }\n\n /**\n * Evaluate an expression with a given scope\n */\n static evaluate(expression: string, scope: EvaluationScope): unknown {\n try {\n const ast = this.parse(expression);\n const evaluator = new Evaluator(scope, expression);\n return evaluator.evaluate(ast);\n } catch (error) {\n if (error instanceof ExpressionParserError) {\n throw error;\n }\n // Wrap other errors for consistency\n throw new ExpressionParserError(\n `Error evaluating expression: ${error instanceof Error ? error.message : String(error)}`,\n 0,\n expression,\n );\n }\n }\n\n /**\n * Clear the AST cache\n */\n static clearCache(): void {\n astCache.clear();\n }\n\n /**\n * Get cache statistics\n */\n static getCacheStats(): { size: number; maxSize: number } {\n return {\n size: astCache.size,\n maxSize: MAX_AST_CACHE_SIZE,\n };\n }\n}\n","import { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { compareValues, getNestedValue } from './value-utils';\nimport { ExpressionParser } from './parser/expression-parser';\n\n/**\n * Evaluate conditional expression\n * Uses secure AST-based parsing for JavaScript expressions\n */\nexport function evaluateCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n switch (expression.type) {\n case 'fieldValue':\n return evaluateFieldValueCondition(expression, context);\n\n case 'formValue':\n return evaluateFormValueCondition(expression, context);\n\n case 'javascript':\n return evaluateJavaScriptExpression(expression, context);\n\n case 'custom':\n return evaluateCustomFunction(expression, context);\n\n case 'and':\n return evaluateAndCondition(expression, context);\n\n case 'or':\n return evaluateOrCondition(expression, context);\n\n default:\n return false;\n }\n}\n\nfunction evaluateFieldValueCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.fieldPath || !expression.operator) return false;\n\n const fieldValue = getNestedValue(context.formValue, expression.fieldPath);\n return compareValues(fieldValue, expression.value, expression.operator);\n}\n\nfunction evaluateFormValueCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.operator) return false;\n return compareValues(context.formValue, expression.value, expression.operator);\n}\n\nfunction evaluateJavaScriptExpression(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.expression) return false;\n\n try {\n // Use secure AST-based expression parser instead of new Function()\n const result = ExpressionParser.evaluate(expression.expression, context);\n return !!result;\n } catch (error) {\n context.logger.error('Error evaluating JavaScript expression:', expression.expression, error);\n return false;\n }\n}\n\nfunction evaluateCustomFunction(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.expression) return false;\n\n const customFn = context.customFunctions?.[expression.expression];\n if (!customFn) {\n context.logger.error('Custom function not found:', expression.expression);\n return false;\n }\n\n try {\n return !!customFn(context);\n } catch (error) {\n context.logger.error('Error executing custom function:', expression.expression, error);\n return false;\n }\n}\n\nfunction evaluateAndCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.conditions || expression.conditions.length === 0) return false;\n\n // All conditions must be true for AND logic\n return expression.conditions.every((condition) => evaluateCondition(condition, context));\n}\n\nfunction evaluateOrCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n if (!expression.conditions || expression.conditions.length === 0) return false;\n\n // At least one condition must be true for OR logic\n return expression.conditions.some((condition) => evaluateCondition(condition, context));\n}\n","import { inject, Injector, signal, Signal, untracked } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { debounceTime, distinctUntilChanged, startWith } from 'rxjs';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { evaluateCondition } from './condition-evaluator';\n\n/**\n * Cache key combining both services to represent the injection context.\n */\ninterface InjectionContextKey {\n functionRegistry: FunctionRegistryService;\n fieldContextRegistry: FieldContextRegistryService;\n}\n\n/**\n * Cache for memoized logic functions, keyed by injection context.\n * Uses WeakMap with FunctionRegistryService as outer key to automatically clean up.\n * Inner structure: Map<FieldContextRegistryService, Map<expressionKey, LogicFn>>\n */\nconst logicFunctionCache = new WeakMap<\n FunctionRegistryService,\n WeakMap<FieldContextRegistryService, Map<string, LogicFn<unknown, boolean>>>\n>();\n\n/**\n * Serializes a value to a deterministic string for cache key generation.\n * Unlike JSON.stringify, this sorts object keys to ensure consistent output\n * regardless of property insertion order.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || value === undefined) {\n return String(value);\n }\n\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const pairs = sortedKeys.map((key) => JSON.stringify(key) + ':' + stableStringify(obj[key]));\n return '{' + pairs.join(',') + '}';\n}\n\n/**\n * Serializes a conditional expression to a deterministic string key for caching.\n * Uses stable stringification to ensure equivalent objects produce the same key\n * regardless of property order.\n */\nfunction serializeExpression(expression: ConditionalExpression): string {\n return stableStringify(expression);\n}\n\n/**\n * Gets or creates the cache map for a specific injection context.\n */\nfunction getContextCache(ctx: InjectionContextKey): Map<string, LogicFn<unknown, boolean>> {\n let outerCache = logicFunctionCache.get(ctx.functionRegistry);\n if (!outerCache) {\n outerCache = new WeakMap();\n logicFunctionCache.set(ctx.functionRegistry, outerCache);\n }\n\n let innerCache = outerCache.get(ctx.fieldContextRegistry);\n if (!innerCache) {\n innerCache = new Map();\n outerCache.set(ctx.fieldContextRegistry, innerCache);\n }\n\n return innerCache;\n}\n\n/**\n * Create a logic function from a conditional expression.\n *\n * This function is used for creating logic functions for hidden, readonly, disabled, and required.\n * It uses the REACTIVE evaluation context, which allows the logic function to create\n * reactive dependencies on form values. When dependent fields change, the logic function\n * will be automatically re-evaluated.\n *\n * NOTE: For validators, use createEvaluationContext directly (with untracked) to prevent\n * infinite reactive loops. Validators with cross-field dependencies should be hoisted\n * to form-level using validateTree.\n *\n * @param expression The conditional expression to evaluate\n * @returns A LogicFn that evaluates the condition in the context of a field\n */\nexport function createLogicFunction<TValue>(expression: ConditionalExpression): LogicFn<TValue, boolean> {\n // Inject services during factory creation, not during execution\n const functionRegistry = inject(FunctionRegistryService);\n const fieldContextRegistry = inject(FieldContextRegistryService);\n\n // Get cache for this injection context\n const contextCache = getContextCache({ functionRegistry, fieldContextRegistry });\n\n // Generate cache key from serialized expression\n const cacheKey = serializeExpression(expression);\n\n // Check cache first\n const cached = contextCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n // Create REACTIVE evaluation context for logic functions\n // This allows logic to re-evaluate when dependent fields change\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n return evaluateCondition(expression, evaluationContext);\n };\n\n // Cache the function\n contextCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n\n/**\n * Cache for debounced logic functions.\n * Keyed by injection context similar to logicFunctionCache, but includes debounceMs in the key.\n */\nconst debouncedLogicFunctionCache = new WeakMap<\n FunctionRegistryService,\n WeakMap<FieldContextRegistryService, Map<string, LogicFn<unknown, boolean>>>\n>();\n\n/**\n * Gets or creates the cache map for debounced functions in a specific injection context.\n */\nfunction getDebouncedContextCache(ctx: InjectionContextKey): Map<string, LogicFn<unknown, boolean>> {\n let outerCache = debouncedLogicFunctionCache.get(ctx.functionRegistry);\n if (!outerCache) {\n outerCache = new WeakMap();\n debouncedLogicFunctionCache.set(ctx.functionRegistry, outerCache);\n }\n\n let innerCache = outerCache.get(ctx.fieldContextRegistry);\n if (!innerCache) {\n innerCache = new Map();\n outerCache.set(ctx.fieldContextRegistry, innerCache);\n }\n\n return innerCache;\n}\n\n/**\n * Store for debounced signals per field context.\n * Uses WeakMap with FieldContext objects as keys to automatically clean up\n * when the context is garbage collected.\n */\nconst debouncedSignalStore = new WeakMap<\n FunctionRegistryService,\n WeakMap<object, { immediateValue: ReturnType<typeof signal<boolean>>; debouncedValue: Signal<boolean | undefined> }>\n>();\n\n/**\n * Gets or creates the debounced signal store for a function registry.\n */\nfunction getDebouncedSignalStore(functionRegistry: FunctionRegistryService) {\n let store = debouncedSignalStore.get(functionRegistry);\n if (!store) {\n store = new WeakMap();\n debouncedSignalStore.set(functionRegistry, store);\n }\n return store;\n}\n\n/**\n * Create a debounced logic function from a conditional expression.\n *\n * This function wraps the condition evaluation in a debounce mechanism,\n * so state changes only take effect after the specified delay.\n * Useful for avoiding UI flicker during rapid typing.\n *\n * @param expression The conditional expression to evaluate\n * @param debounceMs The debounce duration in milliseconds\n * @returns A LogicFn that evaluates the condition with debouncing\n */\nexport function createDebouncedLogicFunction<TValue>(expression: ConditionalExpression, debounceMs: number): LogicFn<TValue, boolean> {\n // Inject services during factory creation, not during execution\n const functionRegistry = inject(FunctionRegistryService);\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const injector = inject(Injector);\n\n // Get cache for this injection context\n const contextCache = getDebouncedContextCache({ functionRegistry, fieldContextRegistry });\n\n // Generate cache key including debounceMs\n const cacheKey = `${serializeExpression(expression)}:${debounceMs}`;\n\n // Check cache first\n const cached = contextCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n // Get or create the signal store for this context\n const signalStore = getDebouncedSignalStore(functionRegistry);\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n // Create a unique key using the context object itself as identifier\n // Since FieldContext doesn't have a path property, we use a WeakMap approach\n // by storing the debounced signal directly on the context\n const contextKey = ctx as unknown as object;\n let signalPair = signalStore.get(contextKey);\n\n if (!signalPair) {\n // Create a signal to hold the immediate evaluation result\n const immediateValue = signal(false);\n\n // Create a debounced signal using RxJS\n const immediateValue$ = toObservable(immediateValue, { injector }).pipe(\n debounceTime(debounceMs),\n distinctUntilChanged(),\n startWith(false),\n );\n\n const debouncedValue = toSignal(immediateValue$, { injector, initialValue: false });\n\n signalPair = { immediateValue, debouncedValue };\n signalStore.set(contextKey, signalPair);\n }\n\n // Create REACTIVE evaluation context for logic functions\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n // Evaluate the condition and update the immediate signal\n const result = evaluateCondition(expression, evaluationContext);\n\n // Update immediate value (this triggers the debounce chain)\n // signalPair is guaranteed to exist here due to the initialization above\n const { immediateValue, debouncedValue } = signalPair;\n untracked(() => {\n if (immediateValue() !== result) {\n immediateValue.set(result);\n }\n });\n\n // Return the debounced value\n return debouncedValue() ?? false;\n };\n\n // Cache the function\n contextCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n","import { inject } from '@angular/core';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\n\n/**\n * Cache for memoized dynamic value functions, keyed by service instance.\n * Uses WeakMap to automatically clean up when service is garbage collected.\n * Inner Map is keyed by expression string.\n */\nconst dynamicValueFunctionCache = new WeakMap<FieldContextRegistryService, Map<string, LogicFn<unknown, unknown>>>();\n\n/**\n * Create a dynamic value function from an expression string.\n * Uses secure AST-based parsing instead of eval() or new Function().\n *\n * @param expression The expression string to evaluate\n * @returns A LogicFn that evaluates the expression in the context of a field\n */\nexport function createDynamicValueFunction<TValue, TReturn>(expression: string): LogicFn<TValue, TReturn> {\n // Inject services during factory creation, not during execution\n // This captures the service instance in the closure\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const logger = inject(DynamicFormLogger);\n\n // Get or create cache for this injection context\n let contextCache = dynamicValueFunctionCache.get(fieldContextRegistry);\n if (!contextCache) {\n contextCache = new Map<string, LogicFn<unknown, unknown>>();\n dynamicValueFunctionCache.set(fieldContextRegistry, contextCache);\n }\n\n // Check cache first\n const cached = contextCache.get(expression);\n if (cached) {\n return cached as LogicFn<TValue, TReturn>;\n }\n\n const fn: LogicFn<TValue, TReturn> = (ctx: FieldContext<TValue>) => {\n // Create evaluation context using the registry-based approach\n const evaluationContext = fieldContextRegistry.createEvaluationContext(ctx);\n\n try {\n // Use secure AST-based expression parser (already has LRU cache)\n return ExpressionParser.evaluate(expression, evaluationContext) as TReturn;\n } catch (error) {\n logger.error('Error evaluating dynamic expression:', expression, error);\n return undefined as TReturn;\n }\n };\n\n // Cache the function\n contextCache.set(expression, fn as LogicFn<unknown, unknown>);\n return fn;\n}\n","import { ConditionalExpression } from '../expressions/conditional-expression';\n\n/**\n * Special form-state conditions for button disabled logic.\n *\n * These conditions evaluate form or page-level state rather than field values,\n * and are primarily used for controlling button disabled states.\n *\n * @example\n * ```typescript\n * // Disable submit button when form is invalid or submitting\n * {\n * key: 'submit',\n * type: 'submit',\n * label: 'Submit',\n * logic: [\n * { type: 'disabled', condition: 'formInvalid' },\n * { type: 'disabled', condition: 'formSubmitting' },\n * ]\n * }\n *\n * // Disable next button when current page is invalid\n * nextButton({\n * key: 'next',\n * label: 'Next',\n * logic: [\n * { type: 'disabled', condition: 'pageInvalid' },\n * ]\n * })\n * ```\n *\n * @public\n */\nexport type FormStateCondition =\n /** True when form.valid() === false */\n | 'formInvalid'\n /** True when form.submitting() === true */\n | 'formSubmitting'\n /** True when fields on the current page are invalid (for paged forms) */\n | 'pageInvalid';\n\n/**\n * Logic type for controlling field state (hidden, readonly, disabled, required).\n *\n * @public\n */\nexport type StateLogicType = 'hidden' | 'readonly' | 'disabled' | 'required';\n\n/**\n * Base configuration for conditional field state logic.\n *\n * @internal\n */\ninterface BaseStateLogicConfig {\n /**\n * Logic type identifier for field state.\n *\n * - `hidden`: Hide the field from view (still participates in form state)\n * - `readonly`: Make the field read-only\n * - `disabled`: Disable user interaction\n * - `required`: Make the field required\n */\n type: StateLogicType;\n\n /**\n * Condition that determines when this logic applies.\n *\n * Can be:\n * - `boolean`: Static value (always applies or never applies)\n * - `ConditionalExpression`: Expression evaluated against field/form values\n * - `FormStateCondition`: Special form/page state check (for buttons)\n *\n * @example\n * ```typescript\n * // Static condition\n * condition: true\n *\n * // Field value condition\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'status',\n * operator: 'equals',\n * value: 'locked'\n * }\n *\n * // Form state condition (for buttons)\n * condition: 'formSubmitting'\n * ```\n */\n condition: ConditionalExpression | boolean | FormStateCondition;\n}\n\n/**\n * State logic that evaluates immediately on change (default).\n *\n * @internal\n */\ninterface ImmediateStateLogicConfig extends BaseStateLogicConfig {\n /**\n * Trigger for immediate evaluation.\n * @default 'onChange'\n */\n trigger?: 'onChange';\n /** Not allowed for onChange trigger */\n debounceMs?: never;\n}\n\n/**\n * State logic that evaluates after a debounce period.\n *\n * @internal\n */\ninterface DebouncedStateLogicConfig extends BaseStateLogicConfig {\n /**\n * Trigger for debounced evaluation.\n * Evaluates after the value has stabilized for the debounce duration.\n */\n trigger: 'debounced';\n /**\n * Debounce duration in milliseconds.\n * @default 500\n */\n debounceMs?: number;\n}\n\n/**\n * Configuration for conditional field state logic.\n *\n * Defines how field behavior changes based on conditions.\n * Supports hiding, disabling, making readonly, or requiring fields\n * based on form state or field values.\n *\n * @example\n * ```typescript\n * // Hide email field when contact method is not email\n * {\n * type: 'hidden',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'contactMethod',\n * operator: 'notEquals',\n * value: 'email'\n * }\n * }\n *\n * // Disable button when form is submitting\n * {\n * type: 'disabled',\n * condition: 'formSubmitting'\n * }\n *\n * // Debounced visibility (avoids flicker during rapid typing)\n * {\n * type: 'hidden',\n * trigger: 'debounced',\n * debounceMs: 300,\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'search',\n * operator: 'isEmpty'\n * }\n * }\n * ```\n *\n * @public\n */\nexport type StateLogicConfig = ImmediateStateLogicConfig | DebouncedStateLogicConfig;\n\n/**\n * Trigger timing for when logic is evaluated.\n *\n * - `onChange`: Evaluate immediately when any dependency changes (default)\n * - `debounced`: Evaluate after the value has stabilized for a duration\n *\n * Use `debounced` for self-transforms (lowercase, trim) or to avoid\n * UI flicker during rapid typing.\n *\n * @public\n */\nexport type LogicTrigger = 'onChange' | 'debounced';\n\n/**\n * @deprecated Use `LogicTrigger` instead. Will be removed in a future version.\n * @public\n */\nexport type DerivationTrigger = LogicTrigger;\n\n/**\n * Base configuration for value derivation logic.\n *\n * @internal\n */\ninterface BaseDerivationLogicConfig {\n /**\n * Logic type identifier for value derivation.\n */\n type: 'derivation';\n\n /**\n * Optional name for this derivation for debugging purposes.\n *\n * When provided, this name appears in derivation debug logs,\n * making it easier to identify specific derivations in complex forms.\n *\n * @example\n * ```typescript\n * {\n * type: 'derivation',\n * debugName: 'Calculate line total',\n * targetField: '$.lineTotal',\n * expression: 'formValue.quantity * formValue.unitPrice'\n * }\n * ```\n */\n debugName?: string;\n\n /**\n * The field whose value will be modified.\n *\n * Can be:\n * - Absolute path: 'fieldName' or 'nested.field.path'\n * - Relative path for arrays: '$.siblingField' (same index as source)\n *\n * @example\n * ```typescript\n * targetField: 'phonePrefix' // Absolute path\n * targetField: 'address.country' // Nested path\n * targetField: '$.lineTotal' // Relative path (array sibling)\n * ```\n */\n targetField: string;\n\n /**\n * Condition that determines when this derivation applies.\n *\n * Can be:\n * - `boolean`: Static value (always applies or never applies)\n * - `ConditionalExpression`: Expression evaluated against field/form values\n *\n * Defaults to `true` (always apply).\n *\n * Note: FormStateCondition is not supported for derivations.\n *\n * @example\n * ```typescript\n * // Always compute (default)\n * condition: true\n *\n * // Conditional derivation\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'country',\n * operator: 'equals',\n * value: 'USA'\n * }\n * ```\n */\n condition?: ConditionalExpression | boolean;\n\n /**\n * Static value to set on the target field.\n *\n * Use when the derived value is a constant.\n * Mutually exclusive with `expression` and `functionName`.\n *\n * @example\n * ```typescript\n * value: '+1' // String\n * value: 100 // Number\n * value: true // Boolean\n * value: { code: 'US' } // Object\n * ```\n */\n value?: unknown;\n\n /**\n * JavaScript expression to evaluate for the derived value.\n *\n * Has access to `formValue` object containing all form values.\n * Uses the same secure AST-based parser as other expressions.\n * Mutually exclusive with `value` and `functionName`.\n *\n * @example\n * ```typescript\n * expression: 'formValue.quantity * formValue.unitPrice'\n * expression: 'formValue.firstName + \" \" + formValue.lastName'\n * expression: 'formValue.price * (1 - formValue.discount / 100)'\n * ```\n */\n expression?: string;\n\n /**\n * Name of a registered custom derivation function.\n *\n * The function receives the evaluation context and returns the derived value.\n * Register functions in `customFnConfig.derivations`.\n * Mutually exclusive with `value` and `expression`.\n *\n * @example\n * ```typescript\n * functionName: 'getCurrencyForCountry'\n * functionName: 'calculateTax'\n * functionName: 'formatPhoneNumber'\n * ```\n */\n functionName?: string;\n\n /**\n * Explicit field dependencies for derivations.\n *\n * When using `functionName`, you can optionally specify which fields\n * the function depends on. This enables more efficient re-evaluation\n * by only triggering when specific dependencies change.\n *\n * If not provided with `functionName`, defaults to all fields ('*').\n * For `expression`, dependencies are automatically extracted from the expression.\n * For `value`, no dependencies are needed (static value).\n *\n * @example\n * ```typescript\n * // Only re-evaluate when country changes\n * {\n * type: 'derivation',\n * targetField: 'currency',\n * functionName: 'getCurrencyForCountry',\n * dependsOn: ['country']\n * }\n *\n * // Override automatic detection for complex expressions\n * {\n * type: 'derivation',\n * targetField: 'total',\n * expression: 'calculateTotal(formValue)',\n * dependsOn: ['quantity', 'unitPrice', 'discount']\n * }\n * ```\n */\n dependsOn?: string[];\n}\n\n/**\n * Derivation logic that evaluates immediately on change (default).\n *\n * @internal\n */\ninterface OnChangeDerivationLogicConfig extends BaseDerivationLogicConfig {\n /**\n * Trigger for immediate evaluation.\n * @default 'onChange'\n */\n trigger?: 'onChange';\n /** Not allowed for onChange trigger */\n debounceMs?: never;\n}\n\n/**\n * Derivation logic that evaluates after a debounce period.\n *\n * Use this for self-transforms (lowercase, trim, format) to avoid\n * interrupting the user while they're actively typing.\n *\n * @internal\n */\ninterface DebouncedDerivationLogicConfig extends BaseDerivationLogicConfig {\n /**\n * Trigger for debounced evaluation.\n * Evaluates after the value has stabilized for the debounce duration.\n */\n trigger: 'debounced';\n /**\n * Debounce duration in milliseconds.\n * @default 500\n */\n debounceMs?: number;\n}\n\n/**\n * Configuration for value derivation logic.\n *\n * Enables programmatic value derivation based on conditions.\n * When the condition is met, the target field's value is set\n * using a static value, expression, or custom function.\n *\n * @example\n * ```typescript\n * // Set phone prefix based on country selection\n * {\n * type: 'derivation',\n * targetField: 'phonePrefix',\n * value: '+1',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'country',\n * operator: 'equals',\n * value: 'USA'\n * }\n * }\n *\n * // Compute total from quantity and price\n * {\n * type: 'derivation',\n * targetField: 'total',\n * expression: 'formValue.quantity * formValue.unitPrice'\n * }\n *\n * // Use custom function for complex logic\n * {\n * type: 'derivation',\n * targetField: 'currency',\n * functionName: 'getCurrencyForCountry'\n * }\n *\n * // Self-transform with debounced trigger\n * // (applies after user stops typing)\n * {\n * type: 'derivation',\n * targetField: 'email',\n * expression: 'formValue.email.toLowerCase()',\n * trigger: 'debounced',\n * debounceMs: 500\n * }\n *\n * // Relative path for array items\n * {\n * type: 'derivation',\n * targetField: '$.lineTotal', // Same array index as source field\n * expression: 'formValue.quantity * formValue.unitPrice'\n * }\n * ```\n *\n * @public\n */\nexport type DerivationLogicConfig = OnChangeDerivationLogicConfig | DebouncedDerivationLogicConfig;\n\n/**\n * Union type for all logic configurations.\n *\n * - `StateLogicConfig`: For field state changes (hidden, readonly, disabled, required)\n * - `DerivationLogicConfig`: For value derivation\n *\n * @public\n */\nexport type LogicConfig = StateLogicConfig | DerivationLogicConfig;\n\n/**\n * Log level for derivation debug output.\n *\n * - 'none': No debug logging\n * - 'summary': Log cycle completion with counts (default in dev mode)\n * - 'verbose': Log individual derivation evaluations with details\n *\n * @public\n */\nexport type DerivationLogLevel = 'none' | 'summary' | 'verbose';\n\n/**\n * Configuration for derivation debug logging.\n *\n * @public\n */\nexport interface DerivationLogConfig {\n /** Log level for derivation debugging. Defaults to 'none'. */\n level: DerivationLogLevel;\n}\n\n/**\n * Creates the default derivation log configuration.\n *\n * Defaults to 'none' (silent). Users can enable logging via `withLoggerConfig`.\n *\n * @returns Default DerivationLogConfig\n *\n * @public\n */\nexport function createDefaultDerivationLogConfig(): DerivationLogConfig {\n return {\n level: 'none',\n };\n}\n\n/**\n * Checks if logging should occur at the specified level.\n *\n * @param config - Current log configuration\n * @param minLevel - Minimum level required for logging\n * @returns True if logging should occur\n *\n * @public\n */\nexport function shouldLog(config: DerivationLogConfig, minLevel: 'summary' | 'verbose'): boolean {\n if (config.level === 'none') return false;\n if (minLevel === 'summary') return config.level === 'summary' || config.level === 'verbose';\n return config.level === 'verbose';\n}\n\n/**\n * Type guard to check if a condition is a FormStateCondition.\n *\n * @param condition - The condition to check\n * @returns true if the condition is a FormStateCondition\n *\n * @public\n */\nexport function isFormStateCondition(\n condition: StateLogicConfig['condition'] | DerivationLogicConfig['condition'],\n): condition is FormStateCondition {\n return typeof condition === 'string' && ['formInvalid', 'formSubmitting', 'pageInvalid'].includes(condition);\n}\n\n/**\n * Type guard to check if a logic config is a StateLogicConfig.\n *\n * @param config - The logic config to check\n * @returns true if the config is for field state logic\n *\n * @public\n */\nexport function isStateLogicConfig(config: LogicConfig): config is StateLogicConfig {\n return config.type === 'hidden' || config.type === 'readonly' || config.type === 'disabled' || config.type === 'required';\n}\n\n/**\n * Type guard to check if a logic config is a DerivationLogicConfig.\n *\n * @param config - The logic config to check\n * @returns true if the config is for value derivation\n *\n * @public\n */\nexport function isDerivationLogicConfig(config: LogicConfig): config is DerivationLogicConfig {\n return config.type === 'derivation';\n}\n","import { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport {\n FormStateCondition,\n isFormStateCondition,\n isStateLogicConfig,\n LogicConfig,\n StateLogicConfig,\n} from '../../models/logic/logic-config';\nimport { CustomValidatorConfig, ValidatorConfig } from '../../models/validation/validator-config';\nimport { SchemaApplicationConfig } from '../../models/schemas/schema-definition';\nimport { CustomFunctionScope } from '../expressions/custom-function-types';\n\n/**\n * Regular expression to detect formValue property access in expressions.\n * Matches patterns like: formValue.fieldName, formValue['fieldName'], formValue[\"fieldName\"]\n */\nconst FORM_VALUE_ACCESS_PATTERN = /\\bformValue\\s*(?:\\.|\\[)/;\n\n/**\n * Regular expressions to extract field paths from formValue expressions.\n *\n * Enhanced to capture full nested paths including dot notation chains:\n * - formValue.fieldName → captures 'fieldName'\n * - formValue.parent.child.grandchild → captures 'parent.child.grandchild'\n * - formValue['field-name'] → captures 'field-name'\n * - formValue[\"field.with.dots\"] → captures 'field.with.dots'\n *\n * Note: Computed property access (formValue[variableName]) is NOT supported\n * and must use explicit dependsOn configuration.\n */\nconst FORM_VALUE_DOT_PATTERN = /\\bformValue\\.([\\w.]+)/g;\nconst FORM_VALUE_BRACKET_SINGLE_PATTERN = /\\bformValue\\s*\\[\\s*'([\\w.-]+)'\\s*\\]/g;\nconst FORM_VALUE_BRACKET_DOUBLE_PATTERN = /\\bformValue\\s*\\[\\s*\"([\\w.-]+)\"\\s*\\]/g;\n\n/**\n * Context for cross-field detection, providing access to function scope information.\n */\nexport interface CrossFieldDetectionContext {\n /**\n * Lookup function to get the scope of a registered custom function.\n *\n * @param functionName The name of the custom function\n * @returns The function's scope, or undefined if not registered\n */\n getFunctionScope?: (functionName: string) => CustomFunctionScope | undefined;\n}\n\n/**\n * Detects if a ConditionalExpression references other fields (cross-field).\n *\n * This is the core detection function that handles ALL expression types:\n * - `fieldValue` with `fieldPath` → Always cross-field\n * - `formValue` → Always cross-field\n * - `javascript` with `formValue.*` in expression → Cross-field\n * - `custom` → Checks registered function scope, defaults to cross-field if unknown\n * - `and`/`or` → Recursively check nested conditions\n *\n * @param expr The conditional expression to analyze\n * @param context Optional context providing function scope lookup\n * @returns true if the expression references other fields\n */\nexport function isCrossFieldExpression(\n expr: ConditionalExpression | boolean | FormStateCondition | undefined,\n context?: CrossFieldDetectionContext,\n): boolean {\n // Boolean, undefined, or FormStateCondition (form-level state checks) are not cross-field\n if (expr === undefined || typeof expr === 'boolean' || isFormStateCondition(expr)) {\n return false;\n }\n\n switch (expr.type) {\n case 'fieldValue':\n // fieldPath means it references another field's value\n return !!expr.fieldPath;\n\n case 'formValue':\n // formValue type always accesses the form state\n return true;\n\n case 'javascript':\n // Check for formValue.* patterns in the expression string\n return FORM_VALUE_ACCESS_PATTERN.test(expr.expression || '');\n\n case 'custom': {\n // For custom functions, determine scope from registry or default to cross-field.\n // The expression.expression property holds the function name.\n //\n // Look up function scope from registry if context is provided\n const functionName = expr.expression;\n if (context?.getFunctionScope && functionName) {\n const scope = context.getFunctionScope(functionName);\n if (scope === 'field') {\n // Function is explicitly marked as field-scoped (no cross-field deps)\n return false;\n }\n // 'form' scope or undefined → treat as cross-field\n }\n\n // Default: conservative approach - assume cross-field\n return true;\n }\n\n case 'and':\n case 'or':\n // Recursively check nested conditions, passing context through\n return (expr.conditions || []).some((c) => isCrossFieldExpression(c, context));\n\n default:\n return false;\n }\n}\n\n/**\n * Extracts field dependencies from a ConditionalExpression.\n *\n * Returns an array of field keys that the expression depends on.\n * For `formValue` type without specific field, returns ['*'] to indicate\n * dependency on the entire form.\n *\n * @param expr The conditional expression to analyze\n * @returns Array of field keys that this expression depends on\n */\nexport function extractExpressionDependencies(expr: ConditionalExpression | boolean | undefined): string[] {\n if (expr === undefined || typeof expr === 'boolean') {\n return [];\n }\n\n const deps = new Set<string>();\n\n switch (expr.type) {\n case 'fieldValue':\n if (expr.fieldPath) {\n // Extract root field name (before any dots for nested paths)\n deps.add(expr.fieldPath.split('.')[0]);\n }\n break;\n\n case 'formValue':\n // Full form access - depends on everything\n deps.add('*');\n break;\n\n case 'javascript':\n // Extract from formValue.* patterns in expression\n extractFromExpressionString(expr.expression || '', deps);\n break;\n\n case 'custom':\n // Custom functions have full form access - conservative approach\n deps.add('*');\n break;\n\n case 'and':\n case 'or':\n // Recursively extract from nested conditions\n for (const condition of expr.conditions || []) {\n extractExpressionDependencies(condition).forEach((d) => deps.add(d));\n }\n break;\n }\n\n return Array.from(deps);\n}\n\n/**\n * Extracts field names from a JavaScript expression string.\n * Handles both dot notation (formValue.field) and bracket notation (formValue['field']).\n */\nexport function extractStringDependencies(expression: string): string[] {\n const deps = new Set<string>();\n extractFromExpressionString(expression, deps);\n return Array.from(deps);\n}\n\n/**\n * Internal helper that populates a Set with dependencies from an expression string.\n *\n * Extracts both root fields and full nested paths for precise dependency tracking:\n * - 'formValue.parent.child' → adds 'parent' (root) and 'parent.child' (full path)\n * - 'formValue.simple' → adds 'simple'\n */\nfunction extractFromExpressionString(expression: string, deps: Set<string>): void {\n // Extract from dot notation: formValue.fieldName or formValue.parent.child.grandchild\n const dotMatches = expression.matchAll(FORM_VALUE_DOT_PATTERN);\n for (const match of dotMatches) {\n const fullPath = match[1];\n // Always add the root field (first segment) as the primary dependency\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n // Also add the full path for more precise dependency tracking if nested\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n\n // Extract from bracket notation with single quotes: formValue['fieldName']\n const bracketSingleMatches = expression.matchAll(FORM_VALUE_BRACKET_SINGLE_PATTERN);\n for (const match of bracketSingleMatches) {\n const fullPath = match[1];\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n\n // Extract from bracket notation with double quotes: formValue[\"fieldName\"]\n const bracketDoubleMatches = expression.matchAll(FORM_VALUE_BRACKET_DOUBLE_PATTERN);\n for (const match of bracketDoubleMatches) {\n const fullPath = match[1];\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n}\n\n// ============================================================================\n// Validator Detection\n// ============================================================================\n\n/**\n * Detects if a custom validator configuration references formValue (cross-field validation).\n *\n * @param config The custom validator configuration to check\n * @returns true if the validator references formValue\n */\nexport function isCrossFieldValidator(config: CustomValidatorConfig): boolean {\n if (!config.expression) {\n return false;\n }\n return FORM_VALUE_ACCESS_PATTERN.test(config.expression);\n}\n\n/**\n * Detects if a built-in validator has a dynamic expression that references formValue.\n *\n * Built-in validators (min, max, pattern, etc.) can have dynamic expressions\n * like `{ type: 'min', expression: 'formValue.minAge' }`.\n *\n * @param config The validator configuration to check\n * @returns true if the validator has a cross-field dynamic expression\n */\nexport function isCrossFieldBuiltInValidator(config: ValidatorConfig): boolean {\n if (config.type === 'custom') {\n return false; // Custom validators handled separately\n }\n\n // Check if expression property references formValue\n if ('expression' in config && typeof config.expression === 'string') {\n return FORM_VALUE_ACCESS_PATTERN.test(config.expression);\n }\n\n return false;\n}\n\n/**\n * Detects if a validator's `when` condition is cross-field.\n *\n * @param config The validator configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the when condition references other fields\n */\nexport function hasCrossFieldWhenCondition(config: ValidatorConfig, context?: CrossFieldDetectionContext): boolean {\n if (!('when' in config) || !config.when) {\n return false;\n }\n return isCrossFieldExpression(config.when as ConditionalExpression, context);\n}\n\n// ============================================================================\n// Logic Detection\n// ============================================================================\n\n/**\n * Detects if a StateLogicConfig has a cross-field condition.\n *\n * Note: This function only handles state logic (hidden, readonly, disabled, required).\n * Derivation logic is handled separately by the derivation system.\n *\n * @param config The state logic configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the logic condition references other fields\n */\nexport function isCrossFieldStateLogic(config: StateLogicConfig, context?: CrossFieldDetectionContext): boolean {\n return isCrossFieldExpression(config.condition, context);\n}\n\n/**\n * Detects if a LogicConfig has a cross-field condition.\n *\n * @param config The logic configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the logic condition references other fields\n *\n * @deprecated Use `isCrossFieldStateLogic` for state logic configs.\n * Derivation logic is handled by the derivation system.\n */\nexport function isCrossFieldLogic(config: LogicConfig, context?: CrossFieldDetectionContext): boolean {\n // Only check state logic configs\n if (!isStateLogicConfig(config)) {\n return false;\n }\n return isCrossFieldExpression(config.condition, context);\n}\n\n// ============================================================================\n// Schema Detection\n// ============================================================================\n\n/**\n * Detects if a SchemaApplicationConfig has a cross-field condition.\n *\n * @param config The schema application configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the schema condition references other fields\n */\nexport function isCrossFieldSchema(config: SchemaApplicationConfig, context?: CrossFieldDetectionContext): boolean {\n if (config.type !== 'applyWhen' || !config.condition) {\n return false;\n }\n return isCrossFieldExpression(config.condition, context);\n}\n","import type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport {\n email,\n FieldContext,\n LogicFn,\n max,\n maxLength,\n min,\n minLength,\n pattern,\n required,\n validate,\n validateAsync,\n validateHttp,\n ValidationError,\n} from '@angular/forms/signals';\nimport { inject } from '@angular/core';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport {\n AsyncValidatorConfig,\n CustomValidatorConfig,\n HttpValidatorConfig,\n ValidatorConfig,\n} from '../../models/validation/validator-config';\nimport { createLogicFunction } from '../expressions/logic-function-factory';\nimport { createDynamicValueFunction } from '../values/dynamic-value-factory';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { isCrossFieldValidator, isCrossFieldBuiltInValidator, hasCrossFieldWhenCondition } from '../cross-field/cross-field-detector';\n\nfunction applyEmailValidator(path: SchemaPath<string>): void {\n email(path);\n}\n\nfunction applyMinValidator(path: SchemaPath<number>, value: number, expression?: string): void {\n if (expression) {\n min(path, createDynamicValueFunction<string | number | null, number | undefined>(expression));\n } else {\n min(path, value);\n }\n}\n\nfunction applyMaxValidator(path: SchemaPath<number>, value: number, expression?: string): void {\n if (expression) {\n max(path, createDynamicValueFunction<string | number | null, number | undefined>(expression));\n } else {\n max(path, value);\n }\n}\n\nfunction applyMinLengthValidator(path: SchemaPath<string>, value: number, expression?: string): void {\n if (expression) {\n minLength(path, createDynamicValueFunction<string, number>(expression));\n } else {\n minLength(path, value);\n }\n}\n\nfunction applyMaxLengthValidator(path: SchemaPath<string>, value: number, expression?: string): void {\n if (expression) {\n maxLength(path, createDynamicValueFunction<string, number>(expression));\n } else {\n maxLength(path, value);\n }\n}\n\nfunction applyPatternValidator(path: SchemaPath<string>, value: RegExp, expression?: string): void {\n if (expression) {\n pattern(\n path,\n createDynamicValueFunction<string | undefined, RegExp | undefined>(expression) as LogicFn<string | undefined, RegExp | undefined>,\n );\n } else {\n pattern(path, value);\n }\n}\n\nfunction createConditionalLogic(when: ConditionalExpression | undefined): LogicFn<unknown, boolean> | undefined {\n return when ? (createLogicFunction(when) as LogicFn<unknown, boolean>) : undefined;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic forms require any at the Angular API boundary\nexport function applyValidator(config: ValidatorConfig, fieldPath: SchemaPath<any> | SchemaPathTree<any>): void {\n const path = fieldPath as SchemaPath<unknown>;\n\n if (isCrossFieldBuiltInValidator(config) || hasCrossFieldWhenCondition(config)) {\n return;\n }\n\n switch (config.type) {\n case 'required':\n if (config.when) {\n required(path, { when: createLogicFunction(config.when) });\n } else {\n required(path);\n }\n break;\n case 'email':\n applyEmailValidator(fieldPath as SchemaPath<string>);\n break;\n case 'min':\n if (typeof config.value === 'number') {\n applyMinValidator(fieldPath as SchemaPath<number>, config.value, config.expression);\n }\n break;\n case 'max':\n if (typeof config.value === 'number') {\n applyMaxValidator(fieldPath as SchemaPath<number>, config.value, config.expression);\n }\n break;\n case 'minLength':\n if (typeof config.value === 'number') {\n applyMinLengthValidator(fieldPath as SchemaPath<string>, config.value, config.expression);\n }\n break;\n case 'maxLength':\n if (typeof config.value === 'number') {\n applyMaxLengthValidator(fieldPath as SchemaPath<string>, config.value, config.expression);\n }\n break;\n case 'pattern':\n if (config.value instanceof RegExp || typeof config.value === 'string') {\n const regexPattern = typeof config.value === 'string' ? new RegExp(config.value) : config.value;\n applyPatternValidator(fieldPath as SchemaPath<string>, regexPattern, config.expression);\n }\n break;\n case 'custom':\n applyCustomValidator(config, path);\n break;\n case 'customAsync':\n applyAsyncValidator(config, path);\n break;\n case 'customHttp':\n applyHttpValidator(config, path);\n break;\n }\n}\n\nfunction applyCustomValidator(config: CustomValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n if (isCrossFieldValidator(config)) {\n return;\n }\n\n let validatorFn: (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null;\n\n if (config.expression) {\n validatorFn = createExpressionValidator(config);\n } else if (config.functionName) {\n validatorFn = createFunctionValidator(config);\n } else {\n const logger = inject(DynamicFormLogger);\n logger.warn('Custom validator must have either \"expression\" or \"functionName\"');\n return;\n }\n\n const whenLogic = createConditionalLogic(config.when);\n validate(fieldPath, (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return null;\n return validatorFn(ctx);\n });\n}\n\nfunction createFunctionValidator(\n config: CustomValidatorConfig,\n): (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null {\n const logger = inject(DynamicFormLogger);\n const functionName = config.functionName;\n if (!functionName) {\n logger.warn('Custom validator missing functionName');\n return () => null;\n }\n\n const registry = inject(FunctionRegistryService);\n const validatorFn = registry.getValidator(functionName);\n\n if (!validatorFn) {\n logger.warn(\n `Custom validator \"${functionName}\" not found in registry. ` +\n `Ensure it's registered using customFnConfig.validators or check the function name for typos.`,\n );\n return () => null;\n }\n\n return (ctx: FieldContext<unknown>) => validatorFn(ctx, config.params);\n}\n\nfunction createExpressionValidator(\n config: CustomValidatorConfig,\n): (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null {\n const logger = inject(DynamicFormLogger);\n const expression = config.expression;\n if (!expression) {\n logger.warn('Custom validator missing expression');\n return () => null;\n }\n\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n\n return (ctx: FieldContext<unknown>) => {\n try {\n const evaluationContext = fieldContextRegistry.createEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n const result = ExpressionParser.evaluate(expression, evaluationContext);\n\n if (result) {\n return null;\n }\n\n const kind = config.kind || 'custom';\n const validationError: ValidationError & Record<string, unknown> = { kind };\n\n if (config.errorParams) {\n Object.entries(config.errorParams).forEach(([key, expression]) => {\n try {\n validationError[key] = ExpressionParser.evaluate(expression, evaluationContext);\n } catch (err) {\n logger.warn(`Error evaluating errorParam \"${key}\":`, expression, err);\n }\n });\n }\n\n return validationError;\n } catch (error) {\n // Gracefully degrade on errors (e.g., typos in field names, undefined functions)\n // Log for debugging while keeping form functional\n logger.error('Error evaluating custom validator expression:', expression, error);\n return { kind: config.kind || 'custom' };\n }\n };\n}\n\n/**\n * Apply async validator to field path using Angular's public validateAsync() API\n *\n * Angular's validateAsync uses the resource API, which requires:\n * - params: Function that computes params from field context\n * - factory: Function that creates ResourceRef from params signal\n * - onSuccess: Maps resource result to validation errors\n * - onError: Optional handler for resource errors\n */\nfunction applyAsyncValidator(config: AsyncValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n const logger = inject(DynamicFormLogger);\n const registry = inject(FunctionRegistryService);\n const validatorConfig = registry.getAsyncValidator(config.functionName);\n\n if (!validatorConfig) {\n logger.warn(\n `Async validator \"${config.functionName}\" not found in registry. ` +\n `Ensure it's registered using customFnConfig.asyncValidators or check the function name for typos.`,\n );\n return;\n }\n\n const whenLogic = createConditionalLogic(config.when);\n const asyncOptions = {\n params: (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return undefined;\n return validatorConfig.params(ctx, config.params);\n },\n factory: validatorConfig.factory,\n onSuccess: validatorConfig.onSuccess,\n onError: validatorConfig.onError,\n };\n\n validateAsync(fieldPath, asyncOptions as Parameters<typeof validateAsync>[1]);\n}\n\n/**\n * Apply HTTP validator to field path using Angular's public validateHttp() API\n *\n * Angular's validateHttp requires:\n * - request: Function that returns URL string or HttpResourceRequest\n * - onSuccess: Maps HTTP response to validation errors (inverted logic!)\n * - onError: Optional handler for HTTP errors\n */\nfunction applyHttpValidator(config: HttpValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n const logger = inject(DynamicFormLogger);\n const registry = inject(FunctionRegistryService);\n const httpValidatorConfig = registry.getHttpValidator(config.functionName);\n\n if (!httpValidatorConfig) {\n logger.warn(\n `HTTP validator \"${config.functionName}\" not found in registry. ` +\n `Ensure it's registered using customFnConfig.httpValidators or check the function name for typos.`,\n );\n return;\n }\n\n const whenLogic = createConditionalLogic(config.when);\n const httpOptions = {\n request: (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return undefined;\n return httpValidatorConfig.request(ctx, config.params);\n },\n onSuccess: httpValidatorConfig.onSuccess,\n onError: httpValidatorConfig.onError,\n };\n\n validateHttp(fieldPath, httpOptions as Parameters<typeof validateHttp>[1]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic forms require any at the Angular API boundary\nexport function applyValidators(configs: ValidatorConfig[], fieldPath: SchemaPath<any> | SchemaPathTree<any>): void {\n configs.forEach((config) => applyValidator(config, fieldPath));\n}\n","import { Injector, Signal } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { debounceTime, distinctUntilChanged, tap } from 'rxjs';\n\n/**\n * Default debounce duration in milliseconds.\n */\nexport const DEFAULT_DEBOUNCE_MS = 500;\n\n/**\n * Creates a debounced effect that triggers a callback after a signal's value\n * has stabilized for the specified duration.\n *\n * Uses Angular's `toObservable` and `toSignal` with RxJS `debounceTime` for proper debouncing.\n * This approach is cleaner than manual setTimeout management and integrates\n * well with Angular's signal-based reactivity.\n *\n * @param source - The source signal to watch for changes\n * @param callback - Function to call with the debounced value\n * @param options - Configuration options\n * @param options.ms - Debounce duration in milliseconds (default: 500)\n * @param options.injector - Angular injector for the effect context\n *\n * @returns A signal that emits the debounced value (can be ignored if only side effects are needed)\n *\n * @example\n * ```typescript\n * // In a component or service\n * const searchInput = signal('');\n *\n * createDebouncedEffect(\n * searchInput,\n * (value) => console.log('Debounced search:', value),\n * { ms: 300, injector: this.injector }\n * );\n * ```\n *\n * @public\n */\nexport function createDebouncedEffect<T>(\n source: Signal<T>,\n callback: (value: T) => void,\n options: { ms?: number; injector: Injector },\n): Signal<T | undefined> {\n const { ms = DEFAULT_DEBOUNCE_MS, injector } = options;\n\n const source$ = toObservable(source, { injector }).pipe(\n debounceTime(ms),\n distinctUntilChanged(),\n tap((value) => callback(value)),\n );\n\n return toSignal(source$, { injector });\n}\n\n/**\n * Creates a debounced signal that emits values from the source signal\n * only after the value has stabilized for the specified duration.\n *\n * Unlike `createDebouncedEffect`, this doesn't execute a side effect callback.\n * Use this when you just need a debounced version of a signal.\n *\n * @param source - The source signal to debounce\n * @param options - Configuration options\n * @param options.ms - Debounce duration in milliseconds (default: 500)\n * @param options.injector - Angular injector for the effect context\n *\n * @returns A signal that emits the debounced value\n *\n * @example\n * ```typescript\n * const input = signal('');\n * const debouncedInput = createDebouncedSignal(input, { ms: 300, injector });\n *\n * effect(() => {\n * console.log('Debounced value:', debouncedInput());\n * });\n * ```\n *\n * @public\n */\nexport function createDebouncedSignal<T>(source: Signal<T>, options: { ms?: number; injector: Injector }): Signal<T | undefined> {\n const { ms = DEFAULT_DEBOUNCE_MS, injector } = options;\n\n const source$ = toObservable(source, { injector }).pipe(debounceTime(ms), distinctUntilChanged());\n\n return toSignal(source$, { injector });\n}\n","import { disabled, hidden, readonly, required, LogicFn } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { LogicConfig, isStateLogicConfig, LogicTrigger } from '../../models/logic/logic-config';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { createLogicFunction, createDebouncedLogicFunction } from '../expressions/logic-function-factory';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\n\ntype AnyLogicFn<TValue> = LogicFn<TValue, boolean> | (() => boolean);\n\n/**\n * Extracts the trigger from a StateLogicConfig, handling the discriminated union.\n */\nfunction getConfigTrigger(config: LogicConfig): LogicTrigger {\n if (!isStateLogicConfig(config)) {\n return 'onChange';\n }\n return config.trigger ?? 'onChange';\n}\n\n/**\n * Extracts debounceMs from a StateLogicConfig if trigger is 'debounced'.\n */\nfunction getConfigDebounceMs(config: LogicConfig): number | undefined {\n if (!isStateLogicConfig(config)) {\n return undefined;\n }\n // Type narrowing: debounceMs only exists when trigger is 'debounced'\n if (config.trigger === 'debounced') {\n return config.debounceMs;\n }\n return undefined;\n}\n\nexport function applyLogic<TValue>(config: LogicConfig, fieldPath: SchemaPath<TValue> | SchemaPathTree<TValue>): void {\n const path = fieldPath as SchemaPath<TValue>;\n const trigger = getConfigTrigger(config);\n const debounceMs = getConfigDebounceMs(config) ?? DEFAULT_DEBOUNCE_MS;\n\n if (typeof config.condition === 'boolean') {\n applyLogicFn(config.type, path, () => config.condition as boolean);\n return;\n }\n\n // Create appropriate logic function based on trigger\n const logicFn =\n trigger === 'debounced'\n ? createDebouncedLogicFunction(config.condition as ConditionalExpression, debounceMs)\n : createLogicFunction(config.condition as ConditionalExpression);\n\n applyLogicFn(config.type, path, logicFn);\n}\n\nfunction applyLogicFn<TValue>(type: LogicConfig['type'], path: SchemaPath<TValue>, logicFn: AnyLogicFn<TValue>): void {\n switch (type) {\n case 'hidden':\n hidden(path, logicFn);\n break;\n case 'readonly':\n readonly(path, logicFn);\n break;\n case 'disabled':\n disabled(path, logicFn);\n break;\n case 'required':\n required(path, { when: logicFn });\n break;\n }\n}\n\nexport function applyMultipleLogic<TValue>(configs: LogicConfig[], fieldPath: SchemaPath<TValue> | SchemaPathTree<TValue>): void {\n configs.forEach((config) => applyLogic(config, fieldPath));\n}\n","import { Injectable } from '@angular/core';\nimport { SchemaDefinition } from '../../models/schemas/schema-definition';\n\n@Injectable()\nexport class SchemaRegistryService {\n private readonly registeredSchemas = new Map<string, SchemaDefinition>();\n\n /**\n * Register a reusable schema\n */\n registerSchema(schema: SchemaDefinition): void {\n this.registeredSchemas.set(schema.name, schema);\n }\n\n /**\n * Get registered schema by name\n */\n getSchema(name: string): SchemaDefinition | undefined {\n return this.registeredSchemas.get(name);\n }\n\n /**\n * Get all registered schemas\n */\n getAllSchemas(): Map<string, SchemaDefinition> {\n return new Map(this.registeredSchemas);\n }\n\n /**\n * Clear all registered schemas\n */\n clearSchemas(): void {\n this.registeredSchemas.clear();\n }\n\n /**\n * Resolve schema from string reference or direct definition\n */\n resolveSchema(schema: string | SchemaDefinition): SchemaDefinition | null {\n if (typeof schema === 'string') {\n return this.getSchema(schema) || null;\n }\n return schema;\n }\n}\n","import type { Logger } from '../../providers/features/logger/logger.interface';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\n\n/**\n * Create a type predicate function from a predicate string.\n *\n * Uses the secure ExpressionParser with whitelist-based evaluation instead of\n * new Function() / eval. This provides security through:\n * - AST-based parsing (no code execution)\n * - Whitelisted operators only\n * - Whitelisted methods only (Array.isArray, typeof, instanceof, etc.)\n * - No access to global scope beyond whitelisted constructors\n *\n * @param predicate - A JavaScript expression that evaluates to boolean. The value to check is available as `value`.\n * @param logger - Logger for error reporting\n * @returns A type predicate function\n *\n * @example\n * createTypePredicateFunction('typeof value === \"string\"')\n * createTypePredicateFunction('Array.isArray(value)')\n * createTypePredicateFunction('value instanceof Date')\n */\nexport function createTypePredicateFunction<T = unknown>(predicate: string, logger: Logger): (value: unknown) => value is T {\n return (value: unknown): value is T => {\n try {\n // Evaluate using secure AST-based parser with value in scope\n const result = ExpressionParser.evaluate(predicate, { value });\n return Boolean(result);\n } catch (error) {\n logger.error('Error evaluating type predicate:', predicate, error);\n return false;\n }\n };\n}\n","import { inject } from '@angular/core';\nimport { apply, applyEach, applyWhen, applyWhenValue, SchemaOrSchemaFn } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { SchemaApplicationConfig, SchemaDefinition } from '../models/schemas/schema-definition';\nimport { SchemaRegistryService } from './registry/schema-registry.service';\nimport { createLogicFunction } from './expressions/logic-function-factory';\nimport { createTypePredicateFunction } from './values/type-predicate-factory';\nimport { applyValidator } from './validation/validator-factory';\nimport { applyLogic } from './logic/logic-applicator';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\n\n/**\n * Apply schema configuration.\n * Accepts both SchemaPath and SchemaPathTree for flexibility.\n *\n * Note: We cast fieldPath to suppress TypeScript's union type errors. This is safe because:\n * 1. We only use signal forms (not AbstractControl), so SchemaPathTree is always the supported branch\n * 2. The Angular apply functions accept SchemaPath with any value type\n * 3. The actual schema application happens at runtime via the schema function\n */\nexport function applySchema(config: SchemaApplicationConfig, fieldPath: SchemaPath<unknown> | SchemaPathTree<unknown>): void {\n const logger = inject(DynamicFormLogger);\n const schemaRegistry = inject(SchemaRegistryService);\n const schema = schemaRegistry.resolveSchema(config.schema);\n\n if (!schema) {\n const availableSchemas = Array.from(schemaRegistry.getAllSchemas().keys()).join(', ') || '<none>';\n logger.error(\n `Schema not found: '${config.schema}'. ` +\n `Available schemas: ${availableSchemas}. ` +\n `Ensure the schema is registered in your schema registry.`,\n );\n return;\n }\n\n const schemaFn = createSchemaFunction(schema);\n\n // Cast to suppress union type errors - safe because we only use signal forms (see function docs)\n const path = fieldPath as SchemaPath<unknown>;\n\n switch (config.type) {\n case 'apply':\n apply(path, schemaFn);\n break;\n\n case 'applyWhen':\n if (config.condition) {\n const conditionFn = createLogicFunction(config.condition);\n applyWhen(path, conditionFn, schemaFn);\n }\n break;\n\n case 'applyWhenValue':\n if (config.typePredicate) {\n const predicate = createTypePredicateFunction(config.typePredicate, logger);\n applyWhenValue(path, predicate, schemaFn);\n }\n break;\n\n case 'applyEach':\n applyEach(path as SchemaPath<unknown[]>, schemaFn);\n break;\n }\n}\n\n/**\n * Create a schema function from schema definition.\n *\n * Schema functions receive SchemaPathTree which includes both the base SchemaPath\n * and nested child access properties. The validator/logic/schema application functions\n * accept SchemaPath | SchemaPathTree, so we can pass the path directly.\n */\nexport function createSchemaFunction(schema: SchemaDefinition): SchemaOrSchemaFn<unknown> {\n return (path: SchemaPathTree<unknown>) => {\n // Apply validators - path is SchemaPathTree which is accepted by applyValidator\n schema.validators?.forEach((validatorConfig) => {\n applyValidator(validatorConfig, path);\n });\n\n // Apply logic - path is SchemaPathTree which is accepted by applyLogic\n schema.logic?.forEach((logicConfig) => {\n applyLogic(logicConfig, path);\n });\n\n // Apply sub-schemas - path is SchemaPathTree which is accepted by applySchema\n schema.subSchemas?.forEach((subSchemaConfig) => {\n applySchema(subSchemaConfig, path);\n });\n };\n}\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { GroupAllowedChildren } from '../../models/types/nesting-constraints';\n\n/**\n * Group field interface for creating logical field groupings that map to object values\n * Groups create nested form structures where child field values are collected into an object\n * This is a programmatic grouping only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Groups should contain rows and leaf fields, but NOT pages or other groups.\n * Runtime validation enforces these rules.\n *\n * Note: Groups are container fields and do not support `meta` since they have no native form element.\n */\nexport interface GroupField<TFields extends readonly GroupAllowedChildren[] = readonly GroupAllowedChildren[]> extends FieldDef<never> {\n type: 'group';\n\n readonly fields: TFields;\n\n /** Groups do not have a label property - they are logical containers only **/\n readonly label?: never;\n\n /** Groups do not support meta - they have no native form element **/\n readonly meta?: never;\n}\n\n/**\n * Type guard for GroupField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isGroupField(field: FieldDef<any>): field is GroupField {\n return field.type === 'group' && 'fields' in field;\n}\n\nexport type GroupComponent<T extends GroupAllowedChildren[]> = FieldComponent<GroupField<T>>;\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { ArrayAllowedChildren } from '../../models/types/nesting-constraints';\n\n/**\n * Array field interface for creating dynamic field collections that map to array values.\n *\n * Key concepts:\n * - The `fields` array defines the TEMPLATE (single field definition), not instances\n * - Array items are created/removed dynamically at runtime via event bus\n * - For primitive arrays: Use a leaf field as template → `['value1', 'value2']`\n * - For object arrays: Use a group field as template → `[{key1: val1}, {key2: val2}]`\n *\n * @example\n * // Primitive array (flat values)\n * {\n * key: 'tags',\n * type: 'array',\n * fields: [{ key: 'tag', type: 'input' }]\n * }\n * // Creates: { tags: ['tag1', 'tag2', 'tag3'] }\n *\n * @example\n * // Object array (nested groups)\n * {\n * key: 'contacts',\n * type: 'array',\n * fields: [{\n * type: 'group',\n * fields: [\n * { key: 'name', type: 'input' },\n * { key: 'email', type: 'input' }\n * ]\n * }]\n * }\n * // Creates: { contacts: [{name: '', email: ''}, {name: '', email: ''}] }\n *\n * Nesting constraints: Arrays can contain rows, leaf fields, or groups (for object arrays),\n * but NOT pages or other arrays. Runtime validation enforces these rules.\n *\n * Note: Arrays are container fields and do not support `meta` since they have no native form element.\n */\nexport interface ArrayField<TFields extends readonly ArrayAllowedChildren[] = readonly ArrayAllowedChildren[]> extends FieldDef<never> {\n type: 'array';\n\n /**\n * Template field definition(s) that will be cloned for each array item.\n * Typically contains a single field definition:\n * - For flat arrays: A leaf field (input, select, checkbox, etc.)\n * - For object arrays: A group field containing multiple child fields\n */\n readonly fields: TFields;\n\n /** Array fields do not have a label property **/\n readonly label?: never;\n\n /** Arrays do not support meta - they have no native form element **/\n readonly meta?: never;\n}\n\n/**\n * Type guard for ArrayField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isArrayField(field: FieldDef<any>): field is ArrayField {\n return field.type === 'array' && 'fields' in field;\n}\n\nexport type ArrayComponent<T extends ArrayAllowedChildren[]> = FieldComponent<ArrayField<T>>;\n","import { FieldDef } from '../base/field-def';\n\n/**\n * Scalar types supported by hidden fields.\n * These are the primitive value types that can be stored.\n */\nexport type HiddenScalar = string | number | boolean;\n\n/**\n * All value types supported by hidden fields.\n * Supports both scalar values and arrays of scalars for storing\n * multiple IDs or similar data.\n */\nexport type HiddenValue = HiddenScalar | HiddenScalar[];\n\n/**\n * Hidden field definition for storing values without rendering UI.\n *\n * Hidden fields participate in the form schema and contribute to form values,\n * but do not render any visible component. They are useful for:\n * - Storing IDs when updating existing records\n * - Persisting metadata that shouldn't be user-editable\n * - Tracking computed values that need to be submitted\n *\n * Unlike the `hidden` property on other fields (which hides a rendered field),\n * this field type renders nothing at all - it's a componentless field.\n *\n * @example\n * ```typescript\n * // Store a record ID for updates\n * const idField: HiddenField<string> = {\n * type: 'hidden',\n * key: 'id',\n * value: '550e8400-e29b-41d4-a716-446655440000',\n * };\n *\n * // Store multiple tag IDs\n * const tagIdsField: HiddenField<number[]> = {\n * type: 'hidden',\n * key: 'tagIds',\n * value: [1, 2, 3],\n * };\n * ```\n *\n * @typeParam TValue - The type of value stored (must be HiddenValue compatible)\n */\nexport interface HiddenField<TValue extends HiddenValue = HiddenValue> extends FieldDef<never> {\n /** Discriminant for hidden field type */\n type: 'hidden';\n\n /**\n * The value to store in the form.\n * This is required - a hidden field without a value serves no purpose.\n */\n value: TValue;\n}\n\n/**\n * Type guard to check if a field is a hidden field.\n *\n * @param field - The field to check\n * @returns True if the field is a HiddenField\n */\nexport function isHiddenField(field: FieldDef<unknown>): field is HiddenField {\n return field.type === 'hidden';\n}\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { RowAllowedChildren } from '../../models/types/nesting-constraints';\nimport { isHiddenField } from './hidden-field';\nimport { isGroupField } from './group-field';\n\n/**\n * Row field interface for creating horizontal layouts\n * This is a special field type that contains other definitions arranged horizontally\n * The row itself doesn't have a value - it's a layout container\n * This is a programmatic field type only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Rows should contain groups and leaf fields, but NOT pages, other rows, or hidden fields.\n * Runtime validation enforces these rules.\n *\n * Note: Rows are container fields and do not support `meta` since they have no native form element.\n */\nexport interface RowField<TFields extends readonly RowAllowedChildren[] = readonly RowAllowedChildren[]> extends FieldDef<never> {\n type: 'row';\n\n /** Child definitions to render within this row */\n readonly fields: TFields;\n\n /** Row fields do not have a label property **/\n readonly label?: never;\n\n /** Rows do not support meta - they have no native form element **/\n readonly meta?: never;\n}\n\n/**\n * Type guard for RowField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isRowField(field: FieldDef<any>): field is RowField {\n return field.type === 'row' && 'fields' in field && Array.isArray((field as RowField).fields);\n}\n\n/**\n * Validates that a row field doesn't contain hidden fields.\n * Hidden fields are not allowed in rows because rows are for horizontal layouts,\n * and hidden fields don't render anything.\n *\n * @param rowField The row field to validate\n * @returns true if valid (no hidden fields), false otherwise\n */\nexport function validateRowNesting(rowField: RowField): boolean {\n return !hasHiddenFields(rowField.fields);\n}\n\n/**\n * Recursively checks if fields contain any hidden fields\n * @param fields Array of field definitions to check\n * @returns true if hidden fields found, false otherwise\n */\nfunction hasHiddenFields(fields: readonly FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isHiddenField(field)) {\n return true;\n }\n\n // Check group fields for nested hidden fields\n if (isGroupField(field)) {\n if (hasHiddenFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport type RowComponent = FieldComponent<RowField<RowAllowedChildren[]>>;\n","import { FieldDef } from '../base/field-def';\nimport { PageAllowedChildren } from '../../models/types/nesting-constraints';\nimport { isRowField } from './row-field';\nimport { isGroupField } from './group-field';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\n\n/**\n * Logic configuration for page fields.\n * Pages only support the 'hidden' logic type since they are layout containers,\n * not form controls (they can't be readonly, disabled, or required).\n */\nexport interface PageLogicConfig {\n /** Only 'hidden' is supported for pages */\n type: 'hidden';\n\n /**\n * Condition that determines when this page is hidden.\n * Can be a boolean or a conditional expression evaluated against form values.\n */\n condition: ConditionalExpression | boolean;\n}\n\n/**\n * Page field interface for creating top-level page layouts\n * This is a special field type that contains other field definitions\n * The page itself doesn't have a value - it's a layout container like row\n * Pages can only be used at the top level and cannot be nested\n * This is a programmatic field type only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Pages should contain rows, groups, and leaf fields, but NOT other pages.\n * Runtime validation enforces these rules.\n *\n * Note: Pages are container fields and do not support `meta` since they have no native form element.\n */\nexport interface PageField<TFields extends readonly PageAllowedChildren[] = PageAllowedChildren[]> extends FieldDef<never> {\n type: 'page';\n\n /** Child field definitions to render within this page */\n readonly fields: TFields;\n\n /** Page fields do not have a label property **/\n readonly label?: never;\n\n /** Pages do not support meta - they have no native form element **/\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional page visibility.\n * Only 'hidden' type logic is supported for pages.\n *\n * @example\n * ```typescript\n * {\n * key: 'businessPage',\n * type: 'page',\n * logic: [{\n * type: 'hidden',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'accountType',\n * operator: 'notEquals',\n * value: 'business',\n * },\n * }],\n * fields: [...]\n * }\n * ```\n */\n readonly logic?: PageLogicConfig[];\n}\n\n/**\n * Type guard for PageField with proper type narrowing\n */\nexport function isPageField(field: FieldDef<unknown>): field is PageField {\n return field.type === 'page' && 'fields' in field && Array.isArray((field as PageField).fields);\n}\n\n/**\n * Validates that a page field doesn't contain nested page fields\n * @param pageField The page field to validate\n * @returns true if valid (no nested pages), false otherwise\n */\nexport function validatePageNesting(pageField: PageField): boolean {\n return !hasNestedPages(pageField.fields);\n}\n\n/**\n * Type guard to check if a field is a container with fields property\n */\nfunction isContainerWithFields(field: FieldDef<unknown>): field is FieldDef<unknown> & { readonly fields: readonly FieldDef<unknown>[] } {\n return (isRowField(field) || isGroupField(field)) && 'fields' in field && Array.isArray((field as { fields: unknown }).fields);\n}\n\n/**\n * Recursively checks if fields contain any nested page fields\n * @param fields Array of field definitions to check\n * @returns true if nested pages found, false otherwise\n */\nfunction hasNestedPages(fields: readonly FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isPageField(field)) {\n return true;\n }\n\n // Check row and group fields for nested pages\n if (isContainerWithFields(field)) {\n if (hasNestedPages(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n","import {\n disabled,\n email,\n hidden,\n max,\n maxLength,\n min,\n minLength,\n pattern,\n readonly,\n required,\n applyEach,\n schema,\n} from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { FieldWithValidation } from '../definitions/base/field-with-validation';\nimport { applyValidator } from './validation/validator-factory';\nimport { applyLogic } from './logic/logic-applicator';\nimport { applySchema } from './schema-application';\nimport { isGroupField } from '../definitions/default/group-field';\nimport { isArrayField } from '../definitions/default/array-field';\nimport { isPageField } from '../definitions/default/page-field';\nimport { isRowField } from '../definitions/default/row-field';\n\n// Type alias for schema path parameters\ntype AnySchemaPath = SchemaPath<unknown> | SchemaPathTree<unknown>;\n\n// ============================================================================\n// Type-safe validator application functions\n// ============================================================================\n\ninterface StringValidationConfig {\n email?: boolean;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n}\n\ninterface NumberValidationConfig {\n min?: number;\n max?: number;\n}\n\n/**\n * Applies string-specific validators to a schema path.\n * This function is properly typed - no casts needed internally.\n */\nfunction applyStringValidators(path: SchemaPath<string>, config: StringValidationConfig): void {\n if (config.email) {\n email(path);\n }\n if (config.minLength !== undefined) {\n minLength(path, config.minLength);\n }\n if (config.maxLength !== undefined) {\n maxLength(path, config.maxLength);\n }\n if (config.pattern) {\n const regex = typeof config.pattern === 'string' ? new RegExp(config.pattern) : config.pattern;\n pattern(path, regex);\n }\n}\n\n/**\n * Applies number-specific validators to a schema path.\n * This function is properly typed - no casts needed internally.\n */\nfunction applyNumberValidators(path: SchemaPath<number>, config: NumberValidationConfig): void {\n if (config.min !== undefined) {\n min(path, config.min);\n }\n if (config.max !== undefined) {\n max(path, config.max);\n }\n}\n\n/**\n * Extracts string validation config from a field definition.\n * Returns undefined if no string validators are configured.\n */\nfunction getStringValidationConfig(fieldDef: FieldWithValidation): StringValidationConfig | undefined {\n if (!fieldDef.email && fieldDef.minLength === undefined && fieldDef.maxLength === undefined && !fieldDef.pattern) {\n return undefined;\n }\n return {\n email: fieldDef.email,\n minLength: fieldDef.minLength,\n maxLength: fieldDef.maxLength,\n pattern: fieldDef.pattern,\n };\n}\n\n/**\n * Extracts number validation config from a field definition.\n * Handles both 'min'/'max' (standard) and 'minValue'/'maxValue' (SliderField).\n * Returns undefined if no number validators are configured.\n */\nfunction getNumberValidationConfig(fieldDef: FieldWithValidation): NumberValidationConfig | undefined {\n const minVal = fieldDef.min ?? (fieldDef as { minValue?: number }).minValue;\n const maxVal = fieldDef.max ?? (fieldDef as { maxValue?: number }).maxValue;\n\n if (minVal === undefined && maxVal === undefined) {\n return undefined;\n }\n return { min: minVal, max: maxVal };\n}\n\n/**\n * Maps a field definition to the Angular Signal Forms schema.\n *\n * This is the main entry point that should be called from the dynamic form component.\n * It handles all field types: leaf fields, containers (page, row, group), and arrays.\n *\n * Cross-field logic (formValue.*) is handled automatically by createLogicFunction\n * which uses RootFormRegistryService.\n *\n * Cross-field validators are skipped at field level and applied at form level via validateTree.\n */\nexport function mapFieldToForm(fieldDef: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n // Layout containers (page, row) - flatten children to current level\n if (isPageField(fieldDef) || isRowField(fieldDef)) {\n mapContainerChildren(fieldDef.fields as FieldDef<unknown>[] | undefined, fieldPath);\n return;\n }\n\n // Group fields - map children under the group's path\n if (isGroupField(fieldDef)) {\n mapContainerChildren(fieldDef.fields, fieldPath);\n return;\n }\n\n // Array fields - use applyEach for item schema\n if (isArrayField(fieldDef)) {\n mapArrayFieldToForm(fieldDef, fieldPath);\n return;\n }\n\n // Leaf field - apply validation, logic, and configuration\n mapLeafField(fieldDef, fieldPath);\n}\n\n/**\n * Maps children of a container field (page, row, group) to the form schema.\n */\nfunction mapContainerChildren(fields: readonly FieldDef<unknown>[] | undefined, parentPath: AnySchemaPath): void {\n if (!fields) return;\n\n const pathRecord = parentPath as Record<string, AnySchemaPath>;\n\n for (const field of fields) {\n if (!field.key) continue;\n\n const childPath = pathRecord[field.key];\n if (childPath) {\n mapFieldToForm(field, childPath);\n }\n }\n}\n\n/**\n * Maps a leaf field (value-bearing field) to the form schema.\n */\nfunction mapLeafField(fieldDef: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n const validationField = fieldDef as FieldDef<unknown> & FieldWithValidation;\n const path = fieldPath as SchemaPath<unknown>;\n\n // Apply simple validation rules from field properties\n applySimpleValidationRules(validationField, path);\n\n if (validationField.validators) {\n for (const config of validationField.validators) {\n applyValidator(config, fieldPath);\n }\n }\n\n // Apply logic rules\n if (validationField.logic) {\n for (const config of validationField.logic) {\n applyLogic(config, fieldPath);\n }\n }\n\n // Apply schemas\n if (validationField.schemas) {\n for (const config of validationField.schemas) {\n applySchema(config, fieldPath);\n }\n }\n\n // Apply field state configuration\n applyFieldState(fieldDef, path);\n}\n\n/**\n * Applies simple validation rules from field properties.\n * Casts are isolated to the boundary between untyped field definitions and typed validator functions.\n */\nfunction applySimpleValidationRules(fieldDef: FieldWithValidation, path: SchemaPath<unknown>): void {\n if (fieldDef.required) {\n required(path);\n }\n\n // String validators - single cast at boundary\n const stringConfig = getStringValidationConfig(fieldDef);\n if (stringConfig) {\n applyStringValidators(path as SchemaPath<string>, stringConfig);\n }\n\n // Number validators - single cast at boundary\n const numberConfig = getNumberValidationConfig(fieldDef);\n if (numberConfig) {\n applyNumberValidators(path as SchemaPath<number>, numberConfig);\n }\n}\n\n/**\n * Applies field state configuration (disabled, readonly, hidden).\n */\nfunction applyFieldState(fieldDef: FieldDef<unknown>, path: SchemaPath<unknown>): void {\n if (fieldDef.disabled) {\n disabled(path);\n }\n\n if (fieldDef.readonly) {\n readonly(path);\n }\n\n if (fieldDef.hidden) {\n hidden(path, () => true);\n }\n}\n\n/**\n * Maps an array field to the form schema using applyEach.\n *\n * Array items use a template field definition. applyEach creates proper\n * FieldTree structure for each array item.\n */\nfunction mapArrayFieldToForm(arrayField: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n if (!isArrayField(arrayField) || !arrayField.fields?.length) {\n return;\n }\n\n const templateField = arrayField.fields[0];\n\n const itemSchema = schema<Record<string, unknown>>((itemPath) => {\n const pathRecord = itemPath as Record<string, AnySchemaPath>;\n\n if (isRowField(templateField) || isPageField(templateField)) {\n // Row/page templates flatten their children\n mapContainerChildren(templateField.fields as FieldDef<unknown>[] | undefined, itemPath);\n } else if (isGroupField(templateField)) {\n // Group template - access group's path first\n const groupKey = templateField.key;\n if (groupKey) {\n const groupPath = pathRecord[groupKey];\n if (groupPath) {\n mapContainerChildren(templateField.fields, groupPath);\n }\n } else {\n // No group key - apply children directly (edge case)\n mapContainerChildren(templateField.fields, itemPath);\n }\n } else {\n // Simple field template\n mapFieldToForm(templateField, itemPath);\n }\n });\n\n applyEach(fieldPath as SchemaPath<Record<string, unknown>[]>, itemSchema);\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../../models/field-type';\n\n/**\n * Generates appropriate default values for different field types in dynamic forms.\n *\n * Uses registry configuration to determine how each field type should handle values.\n * Supports exclude/flatten/include modes based on field type registration.\n *\n * @param field - Field definition to generate default value for\n * @param registry - Field type registry for value handling configuration\n * @returns Appropriate default value based on field type and configuration\n *\n * @example\n * ```typescript\n * // Basic input field defaults to empty string\n * getFieldDefaultValue({ type: 'input', key: 'email' }, registry); // ''\n *\n * // Excluded fields (like text/row) return undefined\n * getFieldDefaultValue({ type: 'text', key: 'label' }, registry); // undefined\n *\n * // Group field returns object with child defaults\n * getFieldDefaultValue({\n * type: 'group',\n * key: 'address',\n * fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city', value: 'New York' }\n * ]\n * }, registry); // { street: '', city: 'New York' }\n * ```\n */\nexport function getFieldDefaultValue(field: FieldDef<unknown>, registry: Map<string, FieldTypeDefinition>): unknown {\n const valueHandling = getFieldValueHandling(field.type, registry);\n\n // Fields with 'exclude' handling don't contribute values\n if (valueHandling === 'exclude') {\n return undefined;\n }\n\n // Flatten fields (row/page) return flattened object of children's values\n // This is used by array fields to get the template structure\n // Note: fieldsToDefaultValues will skip these at top-level since they have keys and return objects\n if (valueHandling === 'flatten' && 'fields' in field && field.fields) {\n const childFields = field.fields as readonly FieldDef<unknown>[];\n\n // Collect only fields that contribute values (exclude buttons, text, etc.)\n const flattenedValues: Record<string, unknown> = {};\n for (const childField of childFields) {\n if ('key' in childField && childField.key) {\n const childValue = getFieldDefaultValue(childField, registry);\n if (childValue !== undefined) {\n flattenedValues[childField.key] = childValue;\n }\n }\n }\n\n // Return flattened object if there are any values, otherwise undefined\n return Object.keys(flattenedValues).length > 0 ? flattenedValues : undefined;\n }\n\n // Group fields with 'include' handling create nested objects\n if (field.type === 'group' && 'fields' in field) {\n const fields = field.fields as readonly FieldDef<unknown>[];\n if (!fields || fields.length === 0) {\n return undefined;\n }\n\n const groupDefaults: Record<string, unknown> = {};\n for (const childField of fields) {\n const childValueHandling = getFieldValueHandling(childField.type, registry);\n\n // Flatten row/page fields into the group (they are presentational containers)\n if (childValueHandling === 'flatten' && 'fields' in childField && childField.fields) {\n const nestedFields = childField.fields as readonly FieldDef<unknown>[];\n for (const nestedField of nestedFields) {\n if ('key' in nestedField && nestedField.key) {\n const nestedValue = getFieldDefaultValue(nestedField, registry);\n if (nestedValue !== undefined) {\n groupDefaults[nestedField.key] = nestedValue;\n }\n }\n }\n } else if ('key' in childField && childField.key) {\n const childValue = getFieldDefaultValue(childField, registry);\n if (childValue !== undefined) {\n groupDefaults[childField.key] = childValue;\n }\n }\n }\n return groupDefaults;\n }\n\n // Use explicit value if provided, with type-specific handling for null\n if ('value' in field) {\n // If value is explicitly set (even to null/undefined), respect it\n if (field.value !== null && field.value !== undefined) {\n return field.value;\n }\n\n // Handle explicit null: use type-specific default\n if (field.value === null) {\n return field.type === 'checkbox' ? false : '';\n }\n\n // Handle explicit undefined: fall through to type-specific defaults\n }\n\n // Type-specific defaults when no value is specified\n if (field.type === 'checkbox') {\n return false;\n }\n\n if (field.type === 'array') {\n return [];\n }\n\n // Number inputs need a number type default for Angular signal forms\n // to use valueAsNumber for coercion. NaN is ideal because:\n // - typeof NaN === 'number' (triggers Angular's valueAsNumber path)\n // - NaN displays as empty in number inputs\n // - valueAsNumber returns NaN when input is cleared\n if (field.type === 'input' && 'props' in field) {\n const props = field.props as { type?: string } | undefined;\n if (props?.type === 'number') {\n return NaN;\n }\n }\n\n return '';\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isPageField } from '../../definitions/default/page-field';\nimport { isRowField } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { ContainerFieldTypes, LeafFieldTypes, RegisteredFieldTypes } from '../registry/field-registry';\n\n/**\n * Type guard to check if a field definition has child fields.\n * This is a looser check that works with FieldDef<unknown> without requiring RegisteredFieldTypes.\n */\nexport function hasChildFields<T>(\n field: FieldDef<T>,\n): field is FieldDef<T> & { fields: FieldDef<unknown>[] | Record<string, FieldDef<unknown>> } {\n return 'fields' in field && field.fields != null;\n}\n\n/** Container field type names */\nconst CONTAINER_TYPES = new Set(['page', 'row', 'group', 'array']);\n\n/**\n * Type guard to check if a field is a container field (page, row, group, or array)\n * Container fields have a 'fields' property and don't contribute values directly.\n * This overload works with RegisteredFieldTypes for full type narrowing.\n */\nexport function isContainerField(field: RegisteredFieldTypes): field is ContainerFieldTypes;\n/**\n * Type guard to check if a field is a container field (page, row, group, or array).\n * This overload works with any FieldDef for looser type checking.\n */\nexport function isContainerField(field: FieldDef<unknown>): boolean;\nexport function isContainerField(field: FieldDef<unknown> | RegisteredFieldTypes): boolean {\n return CONTAINER_TYPES.has(field.type);\n}\n\n/**\n * Type guard to check if a field is a leaf field (value or display field)\n * Leaf fields don't have children and either contribute values or display content\n */\nexport function isLeafField(field: RegisteredFieldTypes): field is LeafFieldTypes {\n return !isContainerField(field);\n}\n\n/**\n * Type guard to check if a field has a value property (value-bearing field)\n * These fields contribute to the form value output\n * Note: Using `unknown` in the Extract condition to match any value type\n */\nexport function isValueBearingField(field: RegisteredFieldTypes): field is Extract<RegisteredFieldTypes, { value: unknown }> {\n return 'value' in field;\n}\n\n/**\n * Type guard to check if a field is excluded from form values (display-only field)\n * Currently this includes text fields and any other fields without a value property\n */\nexport function isDisplayOnlyField(field: RegisteredFieldTypes): boolean {\n return field.type === 'text' || isContainerField(field);\n}\n\n// Re-export the specific type guards for convenience\nexport { isPageField, isRowField, isGroupField, isArrayField };\n","import { schema, Schema, SchemaPathTree, validateStandardSchema } from '@angular/forms/signals';\n// Import from secondary entry point - this is correct for ng-packagr's entry point architecture\n// (different from importing internal barrel files which should be avoided)\nimport { isStandardSchemaMarker, type FormSchema } from '@ng-forge/dynamic-forms/schema';\n\n/**\n * Applies a form-level schema validation to a schema path.\n * Supports both Standard Schema (Zod, Valibot, ArkType) and raw Angular schema callbacks.\n *\n * This is a helper function used internally by `createSchemaFromFields`\n * to apply form-level validation after field-level validation.\n *\n * @typeParam TModel - The form value type\n * @param path - The schema path to validate (from Angular's schema callback)\n * @param formLevelSchema - Form-level schema (Standard Schema marker or Angular callback)\n *\n * @remarks\n * Type assertions are required due to Angular's complex generic constraints:\n * - `validateStandardSchema` uses `IgnoreUnknownProperties<TSchema>` to accommodate Zod's strict types\n * - `SchemaPathTree` includes `SchemaPath` via conditional types that TypeScript can't narrow\n * These assertions are safe because the path originates from Angular's schema() function.\n *\n * @internal\n */\nexport function applyFormLevelSchema<TModel>(path: SchemaPathTree<TModel>, formLevelSchema: FormSchema<TModel>): void {\n if (isStandardSchemaMarker(formLevelSchema)) {\n // Standard Schema (Zod, Valibot, ArkType, etc.)\n // Cast via Parameters: validateStandardSchema's IgnoreUnknownProperties<TSchema> creates type incompatibility\n // that TypeScript cannot resolve. The cast is safe as path comes from Angular's schema() callback.\n (validateStandardSchema as (...args: unknown[]) => void)(path, formLevelSchema.schema);\n } else if (typeof formLevelSchema === 'function') {\n // Angular schema callback - execute directly with the path\n // Cast via Function: AngularSchemaCallback expects intersection type SchemaPath & SchemaPathTree.\n // SchemaPathTree structurally includes SchemaPath, so this is safe at runtime.\n (formLevelSchema as (path: unknown) => void)(path);\n }\n}\n\n/**\n * Creates a schema from only form-level schema (when no field-level schema exists).\n *\n * Use this when the form has fields without validation rules but still\n * needs form-level validation via a Standard Schema.\n *\n * @typeParam TModel - The form value type\n * @param formLevelSchema - Form-level Standard Schema\n * @returns Schema that applies form-level validation\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const FormSchema = z.object({\n * email: z.string().email(),\n * password: z.string().min(8),\n * });\n *\n * // Create schema from form-level schema only\n * const formSchema = createFormLevelSchema(standardSchema(FormSchema));\n * ```\n */\nexport function createFormLevelSchema<TModel>(formLevelSchema: FormSchema<TModel>): Schema<TModel> {\n return schema<TModel>((path) => {\n applyFormLevelSchema(path, formLevelSchema);\n });\n}\n","import { inject } from '@angular/core';\nimport { Schema, schema, validateTree, FieldContext, ValidationError, FieldTree } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { mapFieldToForm } from './form-mapping';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../models/field-type';\nimport { getFieldDefaultValue } from '../utils/default-value/default-value';\nimport { CrossFieldValidatorEntry } from './cross-field/cross-field-types';\nimport { FunctionRegistryService } from './registry/function-registry.service';\nimport { ExpressionParser } from './expressions/parser/expression-parser';\nimport { evaluateCondition } from './expressions/condition-evaluator';\nimport { CustomValidatorConfig, ValidatorConfig } from '../models/validation/validator-config';\nimport { hasChildFields } from '../models/types/type-guards';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\nimport type { Logger } from '../providers/features/logger/logger.interface';\nimport { EvaluationContext } from '../models/expressions/evaluation-context';\nimport { normalizeFieldsArray } from '../utils/object-utils';\nimport { applyFormLevelSchema } from './form-schema-merger';\nimport type { FormSchema } from '@ng-forge/dynamic-forms/schema';\n\nconst emailPattern = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nfunction getFieldTreeByKey<TModel>(ctx: FieldContext<TModel>, key: string): FieldTree<unknown> | undefined {\n return (ctx.fieldTree as Record<string, FieldTree<unknown>>)[key];\n}\n\n/**\n * Options for creating a schema from field definitions.\n */\nexport interface CreateSchemaOptions<TModel = unknown> {\n /**\n * Optional array of collected cross-field validators.\n */\n crossFieldValidators?: CrossFieldValidatorEntry[];\n\n /**\n * Optional form-level Standard Schema for additional validation.\n *\n * Supports Zod, Valibot, ArkType, and other Standard Schema compliant libraries.\n * Useful for cross-field validation rules.\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const PasswordSchema = z.object({\n * password: z.string().min(8),\n * confirmPassword: z.string(),\n * }).refine(\n * (data) => data.password === data.confirmPassword,\n * { message: 'Passwords must match', path: ['confirmPassword'] }\n * );\n *\n * const schema = createSchemaFromFields(fields, registry, {\n * formLevelSchema: standardSchema(PasswordSchema),\n * });\n * ```\n */\n formLevelSchema?: FormSchema<TModel>;\n}\n\n/**\n * Creates an Angular signal forms schema from field definitions\n * This is the single entry point at dynamic form level that replaces createSchemaFromFields\n * Uses the new modular signal forms adapter structure\n *\n * Cross-field logic (formValue.*) is handled automatically by createLogicFunction\n * which uses RootFormRegistryService. No special context needed.\n *\n * Cross-field validators are passed directly and applied at form level using validateTree.\n *\n * @param fields Field definitions to create schema from\n * @param registry Field type registry\n * @param optionsOrValidators Optional configuration object or array of cross-field validators (for backwards compatibility)\n */\nexport function createSchemaFromFields<TModel = unknown>(\n fields: FieldDef<unknown>[],\n registry: Map<string, FieldTypeDefinition>,\n optionsOrValidators?: CrossFieldValidatorEntry[] | CreateSchemaOptions<TModel>,\n): Schema<TModel> {\n // Inject services for cross-field validation\n // These will be available because createSchemaFromFields is called within runInInjectionContext\n const functionRegistry = inject(FunctionRegistryService);\n const logger = inject(DynamicFormLogger);\n\n // Normalize options - support both old array signature and new options object\n const options: CreateSchemaOptions<TModel> = Array.isArray(optionsOrValidators)\n ? { crossFieldValidators: optionsOrValidators }\n : (optionsOrValidators ?? {});\n\n const { crossFieldValidators, formLevelSchema } = options;\n\n return schema<TModel>((path) => {\n for (const fieldDef of fields) {\n const valueHandling = getFieldValueHandling(fieldDef.type, registry);\n\n // Handle different value handling modes\n if (valueHandling === 'exclude') {\n // Skip fields that don't contribute to form values\n continue;\n }\n\n if (valueHandling === 'flatten' && hasChildFields(fieldDef)) {\n for (const childField of normalizeFieldsArray(fieldDef.fields)) {\n if (!childField.key) continue;\n\n const childPath = (path as Record<string, SchemaPath<unknown>>)[childField.key];\n if (childPath) {\n mapFieldToForm(childField, childPath);\n }\n }\n continue;\n }\n\n // Regular field processing for 'include' fields\n const fieldPath = (path as Record<string, SchemaPath<unknown>>)[fieldDef.key];\n\n if (!fieldPath) {\n continue;\n }\n\n // Use the new modular form mapping function\n // This will progressively apply validators, logic, and schemas\n // Cross-field logic is handled automatically via RootFormRegistryService\n mapFieldToForm(fieldDef, fieldPath);\n }\n\n // Apply cross-field validators using validateTree\n if (crossFieldValidators && crossFieldValidators.length > 0) {\n applyCrossFieldTreeValidator(path as SchemaPathTree<TModel>, crossFieldValidators, functionRegistry, logger);\n }\n\n // Apply form-level Standard Schema validation\n if (formLevelSchema) {\n applyFormLevelSchema(path as SchemaPathTree<TModel>, formLevelSchema);\n }\n });\n}\n\n/**\n * Applies cross-field validators using Angular's validateTree API.\n *\n * This is the key integration point that routes cross-field validation errors\n * to the appropriate target fields via Angular's form state system.\n *\n * The validateTree function allows returning errors with a `fieldTree` property\n * that targets specific fields, which Angular automatically routes to those\n * fields' errors() signal.\n *\n * Supports two types of hoisted validators:\n * 1. Custom validators with cross-field expressions (e.g., `formValue.password === formValue.confirmPassword`)\n * 2. Built-in validators with cross-field `when` conditions (e.g., `required` when `country === 'USA'`)\n *\n * @param rootPath The root schema path tree\n * @param validators Array of collected cross-field validators\n * @param functionRegistry Registry containing custom functions for expression evaluation\n * @param logger Logger for error reporting\n */\nfunction applyCrossFieldTreeValidator<TModel>(\n rootPath: SchemaPathTree<TModel>,\n validators: CrossFieldValidatorEntry[],\n functionRegistry: FunctionRegistryService,\n logger: Logger,\n): void {\n // Get custom functions for expression evaluation\n const customFunctions = functionRegistry.getCustomFunctions();\n\n validateTree(rootPath as SchemaPath<TModel>, (ctx: FieldContext<TModel>) => {\n if (validators.length === 0) {\n return null; // ValidationSuccess - no errors\n }\n\n // Read form value reactively - don't wrap in untracked() so Angular can track dependencies\n const formValue = ctx.value() as Record<string, unknown>;\n const errors: ValidationError.WithOptionalField[] = [];\n\n for (const entry of validators) {\n const { sourceFieldKey, config } = entry;\n\n try {\n const error = evaluateCrossFieldValidator(entry, formValue, sourceFieldKey, ctx, customFunctions, logger);\n\n if (error) {\n errors.push(error);\n }\n } catch (err) {\n logger.error(`Error evaluating cross-field validator for ${sourceFieldKey}:`, err);\n\n // On error, add a validation error to indicate the failure\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n\n if (targetField) {\n const customConfig = config as CustomValidatorConfig;\n errors.push({\n kind: customConfig.kind || config.type || 'custom',\n fieldTree: targetField,\n });\n }\n }\n }\n\n return errors.length > 0 ? errors : null;\n });\n}\n\n/**\n * Evaluates a single cross-field validator entry and returns an error if validation fails.\n */\nfunction evaluateCrossFieldValidator<TModel>(\n entry: CrossFieldValidatorEntry,\n formValue: Record<string, unknown>,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n customFunctions: EvaluationContext['customFunctions'],\n logger: Logger,\n): ValidationError.WithOptionalField | null {\n const { config } = entry;\n const fieldValue = formValue[sourceFieldKey];\n\n // Create evaluation context for condition/expression evaluation\n const evaluationContext: EvaluationContext = {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions,\n logger,\n };\n\n // Check if this is a custom validator (with expression) or a built-in validator (with when condition)\n if (config.type === 'custom') {\n return evaluateCustomCrossFieldValidator(config as CustomValidatorConfig, evaluationContext, sourceFieldKey, ctx);\n } else {\n // Built-in validator with cross-field when condition\n return evaluateBuiltInCrossFieldValidator(config, evaluationContext, sourceFieldKey, ctx);\n }\n}\n\n/**\n * Evaluates a custom cross-field validator with an expression.\n */\nfunction evaluateCustomCrossFieldValidator<TModel>(\n config: CustomValidatorConfig,\n evaluationContext: EvaluationContext,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n): ValidationError.WithOptionalField | null {\n if (!config.expression) {\n return null;\n }\n\n const { fieldValue, formValue, logger, customFunctions } = evaluationContext;\n\n // First, evaluate the when condition if present\n // If the condition is false, the validator doesn't apply (validation passes)\n if (config.when) {\n const conditionMet = evaluateCondition(config.when, {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions: customFunctions || {},\n logger,\n });\n\n if (!conditionMet) {\n return null; // Condition not met, skip validation\n }\n }\n\n // Evaluate expression using the secure AST parser\n const result = ExpressionParser.evaluate(config.expression, evaluationContext);\n\n // If expression returns truthy, validation passes (no error)\n if (result) {\n return null;\n }\n\n // Validation failed - create error targeting the source field\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n if (!targetField) {\n return null;\n }\n\n const errorObj: Record<string, unknown> = {\n kind: config.kind || 'custom',\n fieldTree: targetField,\n };\n\n // Evaluate and include errorParams for message interpolation\n if (config.errorParams) {\n for (const [key, expression] of Object.entries(config.errorParams)) {\n try {\n errorObj[key] = ExpressionParser.evaluate(expression, evaluationContext);\n } catch {\n // Ignore evaluation errors for params\n }\n }\n }\n\n return errorObj as unknown as ValidationError.WithOptionalField;\n}\n\n/**\n * Evaluates a built-in validator with a cross-field when condition.\n * First checks the when condition, then applies the built-in validation logic.\n */\nfunction evaluateBuiltInCrossFieldValidator<TModel>(\n config: ValidatorConfig,\n evaluationContext: EvaluationContext,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n): ValidationError.WithOptionalField | null {\n const { fieldValue, formValue, logger, customFunctions } = evaluationContext;\n\n // First, evaluate the when condition\n // If the condition is false, the validator doesn't apply (validation passes)\n if (config.when) {\n const conditionMet = evaluateCondition(config.when, {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions: customFunctions || {},\n logger,\n });\n\n if (!conditionMet) {\n return null; // Condition not met, skip validation\n }\n }\n\n // Now apply the built-in validation logic based on the validator type\n const isValid = applyBuiltInValidationLogic(config, fieldValue);\n\n if (isValid) {\n return null; // Validation passed\n }\n\n // Validation failed - create error targeting the source field\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n if (!targetField) {\n return null;\n }\n\n return {\n kind: config.type,\n fieldTree: targetField,\n } as ValidationError.WithOptionalField;\n}\n\n/**\n * Applies built-in validation logic based on the validator type.\n * Returns true if validation passes, false if it fails.\n */\nfunction applyBuiltInValidationLogic(config: ValidatorConfig, fieldValue: unknown): boolean {\n switch (config.type) {\n case 'required':\n // Required: value must be non-null, non-undefined, and non-empty string\n if (fieldValue === null || fieldValue === undefined) {\n return false;\n }\n if (typeof fieldValue === 'string' && fieldValue.trim() === '') {\n return false;\n }\n return true;\n\n case 'min':\n // Min: numeric value must be >= min\n if (fieldValue === null || fieldValue === undefined) {\n return true; // Empty values pass min validation (use required for emptiness)\n }\n if ('value' in config && typeof config.value === 'number') {\n return (fieldValue as number) >= config.value;\n }\n return true;\n\n case 'max':\n // Max: numeric value must be <= max\n if (fieldValue === null || fieldValue === undefined) {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return (fieldValue as number) <= config.value;\n }\n return true;\n\n case 'minLength':\n // MinLength: string length must be >= minLength\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return String(fieldValue).length >= config.value;\n }\n return true;\n\n case 'maxLength':\n // MaxLength: string length must be <= maxLength\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return String(fieldValue).length <= config.value;\n }\n return true;\n\n case 'email':\n // Email: must match email pattern\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n\n return emailPattern.test(String(fieldValue));\n\n case 'pattern':\n // Pattern: must match regex pattern\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && config.value) {\n const regex = config.value instanceof RegExp ? config.value : new RegExp(String(config.value));\n return regex.test(String(fieldValue));\n }\n return true;\n\n default:\n // Unknown validator type, consider valid\n return true;\n }\n}\n\n/**\n * Utility to convert field definitions to default values object\n */\nexport function fieldsToDefaultValues<TModel = unknown>(fields: FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>): TModel {\n const defaultValues: Record<string, unknown> = {};\n\n for (const field of fields) {\n if (!field.key) continue;\n\n // Skip flatten fields (row/page) at top level - they are presentational containers\n const valueHandling = getFieldValueHandling(field.type, registry);\n if (valueHandling === 'flatten') {\n continue;\n }\n\n const value = getFieldDefaultValue(field, registry);\n if (value !== undefined) {\n defaultValues[field.key] = value;\n }\n }\n\n return defaultValues as TModel;\n}\n","import { Injectable } from '@angular/core';\nimport { filter, Observable, Subject } from 'rxjs';\nimport { FormEvent, FormEventConstructor } from './interfaces/form-event';\n\n/**\n * Event bus service for form-wide event communication.\n *\n * Provides type-safe event dispatching and subscription for form components\n * to communicate without direct coupling. Uses RxJS observables for reactive\n * event handling and supports both single event type and multiple event type subscriptions.\n *\n * @example\n * ```typescript\n * @Component({\n * providers: [EventBus]\n * })\n * export class MyFormComponent {\n * constructor(private eventBus: EventBus) {\n * // Subscribe to form submission events\n * this.eventBus.on<SubmitEvent>('submit').subscribe(() => {\n * console.log('Form was submitted');\n * });\n *\n * // Subscribe to multiple event types\n * this.eventBus.on<SubmitEvent | FormResetEvent>(['submit', 'form-reset']).subscribe(event => {\n * console.log('Form event:', event.type);\n * });\n * }\n *\n * onSubmit() {\n * // Dispatch a submit event\n * this.eventBus.dispatch(SubmitEvent);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class EventBus {\n private pipeline$ = new Subject<FormEvent>();\n\n events$ = this.pipeline$.asObservable();\n\n /**\n * Dispatches an event to all subscribers.\n *\n * Creates an instance of the provided event constructor and broadcasts it\n * through the event pipeline to all active subscribers.\n *\n * @param eventConstructor - Constructor function for the event to dispatch\n *\n * @example\n * ```typescript\n * // Dispatch a submit event\n * eventBus.dispatch(SubmitEvent);\n *\n * // Dispatch a custom event\n * eventBus.dispatch(CustomFormEvent);\n * ```\n */\n // TypeScript limitation: Must use ConstructorParameters which relies on `any` in FormEventConstructor\n dispatch<T extends FormEventConstructor>(eventConstructor: T, ...args: ConstructorParameters<T>): void {\n this.pipeline$.next(new eventConstructor(...args));\n }\n\n /**\n * Subscribes to events of a specific type.\n *\n * @param eventType - The type of event to subscribe to\n * @returns Observable that emits events of the specified type\n */\n on<T extends FormEvent>(eventType: T['type']): Observable<T>;\n /**\n * Subscribes to events of multiple types.\n *\n * @param eventType - Array of event types to subscribe to\n * @returns Observable that emits events matching any of the specified types\n */\n on<T extends FormEvent>(eventType: Array<T['type']>): Observable<T>;\n /**\n * Subscribes to form events with type-safe filtering.\n *\n * Provides a reactive stream of events filtered by type. Supports both single\n * event type subscriptions and multi-type subscriptions for flexible event handling.\n *\n * @param eventType - Event type string or array of event type strings to filter by\n * @returns Observable stream of filtered events\n *\n * @example\n * ```typescript\n * // Subscribe to a single event type\n * eventBus.on<SubmitEvent>('submit').subscribe(event => {\n * console.log('Submit event received');\n * });\n *\n * // Subscribe to multiple event types\n * eventBus.on<SubmitEvent | FormResetEvent | ValidationErrorEvent>(['submit', 'form-reset', 'validation-error']).subscribe(event => {\n * switch (event.type) {\n * case 'submit':\n * handleSubmit();\n * break;\n * case 'form-reset':\n * handleReset();\n * break;\n * case 'validation-error':\n * handleValidationError();\n * break;\n * }\n * });\n * ```\n */\n on<T extends FormEvent>(eventType: T['type'] | Array<T['type']>): Observable<T> {\n if (Array.isArray(eventType)) {\n return this.pipeline$.pipe(filter((event): event is T => eventType.includes(event.type)));\n }\n\n return this.pipeline$.pipe(filter((event): event is T => event.type === eventType));\n }\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class SubmitEvent implements FormEvent {\n readonly type = 'submit' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class ComponentInitializedEvent implements FormEvent {\n readonly type = 'component-initialized' as const;\n\n constructor(\n public componentType: 'dynamic-form' | 'page' | 'row' | 'group' | 'array',\n public componentId: string,\n ) {}\n}\n","import { Injector, Signal } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { Observable } from 'rxjs';\nimport { filter, map, scan, shareReplay, switchMap, take } from 'rxjs/operators';\nimport { EventBus } from '../../events/event.bus';\nimport { ComponentInitializedEvent } from '../../events/constants/component-initialized.event';\n\n/**\n * Creates an observable that tracks component initialization progress.\n *\n * This function returns an observable that emits when all expected components\n * have been initialized. It uses the scan operator to accumulate initialization\n * events and emits true when the count reaches the expected total.\n *\n * @param eventBus - The event bus instance to subscribe to\n * @param expectedCount - Total number of components expected to initialize\n * @returns Observable<boolean> that emits true when all components are initialized\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = 5; // 1 dynamic-form + 2 pages + 1 row + 1 group\n *\n * const allInitialized$ = createInitializationTracker(eventBus, totalComponents);\n *\n * allInitialized$.subscribe(isComplete => {\n * if (isComplete) {\n * console.log('All components are initialized!');\n * }\n * });\n * ```\n */\nexport function createInitializationTracker(eventBus: EventBus, expectedCount: number): Observable<boolean> {\n return eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n scan((count) => count + 1, 0),\n map((currentCount) => currentCount >= expectedCount),\n filter((isComplete) => isComplete),\n );\n}\n\n/**\n * Creates an observable that tracks component initialization progress with detailed status.\n *\n * This function returns an observable that emits the current count and completion status\n * for each initialization event, providing more granular tracking capabilities.\n *\n * @param eventBus - The event bus instance to subscribe to\n * @param expectedCount - Total number of components expected to initialize\n * @returns Observable with current count, expected count, and completion status\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = 5;\n *\n * const progress$ = createDetailedInitializationTracker(eventBus, totalComponents);\n *\n * progress$.subscribe(({ currentCount, expectedCount, isComplete }) => {\n * console.log(`Progress: ${currentCount}/${expectedCount} (${isComplete ? 'Complete' : 'In Progress'})`);\n * });\n * ```\n */\nexport function createDetailedInitializationTracker(\n eventBus: EventBus,\n expectedCount: number,\n): Observable<{ currentCount: number; expectedCount: number; isComplete: boolean }> {\n return eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n scan((count) => count + 1, 0),\n map((currentCount) => ({\n currentCount,\n expectedCount,\n isComplete: currentCount >= expectedCount,\n })),\n );\n}\n\n/**\n * Options for setting up initialization tracking.\n */\nexport interface InitializationTrackingOptions {\n eventBus: EventBus;\n totalComponentsCount: Signal<number>;\n injector: Injector;\n componentId: string;\n}\n\n/**\n * Creates an observable that tracks when all form components are initialized.\n * Uses shareReplay({ bufferSize: 1, refCount: false }) to ensure exactly one emission\n * that can be received by late subscribers and keeps the subscription alive.\n *\n * This utility function replaces the manual ReplaySubject pattern for tracking initialization.\n * The count includes container components (dynamic-form, pages, rows, groups).\n *\n * @param options - Configuration options for initialization tracking\n * @returns Observable<boolean> that emits true when all components are initialized\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = computed(() => countContainerComponents(fields));\n *\n * readonly initialized$ = setupInitializationTracking({\n * eventBus,\n * totalComponentsCount: totalComponents,\n * injector: this.injector,\n * componentId: 'dynamic-form'\n * });\n * ```\n */\nexport function setupInitializationTracking(options: InitializationTrackingOptions): Observable<boolean> {\n const { eventBus, totalComponentsCount, injector, componentId } = options;\n\n return toObservable(totalComponentsCount, { injector }).pipe(\n take(1),\n switchMap((count) => {\n if (count === 1) {\n // Only dynamic-form component, emit immediately when it initializes\n return eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n filter((event) => event.componentType === 'dynamic-form' && event.componentId === componentId),\n map(() => true),\n take(1),\n );\n }\n\n return createInitializationTracker(eventBus, count);\n }),\n shareReplay({ bufferSize: 1, refCount: false }),\n );\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isPageField } from '../../definitions/default/page-field';\nimport { RegisteredFieldTypes } from '../registry/field-registry';\n\n// Re-export isPageField for external usage\nexport { isPageField };\n\n/**\n * Interface for fields that contain child fields\n */\ninterface ContainerField<T> extends FieldDef<T> {\n fields: FieldDef<unknown>[];\n}\n\n/**\n * Type guard to check if a field is a container with fields\n */\nfunction isContainerWithFields<T>(field: FieldDef<T>): field is FieldDef<T> & ContainerField<T> {\n return (\n (field.type === 'row' || field.type === 'group' || field.type === 'page') &&\n 'fields' in field &&\n Array.isArray((field as ContainerField<T>).fields)\n );\n}\n\n/**\n * Form mode enumeration distinguishing between paged and non-paged forms\n */\nexport type FormMode = 'paged' | 'non-paged';\n\n/**\n * Result of form mode detection with validation details\n */\nexport interface FormModeDetectionResult {\n /** The detected form mode */\n mode: FormMode;\n /** Whether the form configuration is valid for the detected mode */\n isValid: boolean;\n /** Array of validation errors if form is invalid */\n errors: string[];\n}\n\n/**\n * Type guard for paged form configurations\n * A paged form has ALL root-level fields of type 'page'\n */\nexport function isPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n if (!fields || fields.length === 0) {\n return false;\n }\n\n return fields.every((field) => isPageField(field));\n}\n\n/**\n * Type guard for non-paged form configurations\n * A non-paged form has NO page fields at any level\n */\nexport function isNonPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n if (!fields || fields.length === 0) {\n return true; // Empty form is considered non-paged\n }\n\n return !hasAnyPageFields(fields);\n}\n\n/**\n * Detects the form mode and validates the configuration\n * @param fields The form field definitions\n * @returns Detection result with mode and validation status\n */\nexport function detectFormMode<TFields extends RegisteredFieldTypes[]>(fields: TFields): FormModeDetectionResult {\n if (!fields || fields.length === 0) {\n return {\n mode: 'non-paged',\n isValid: true,\n errors: [],\n };\n }\n\n const hasPageFields = fields.some((field) => isPageField(field));\n const allPagesAtRoot = fields.every((field) => isPageField(field));\n const hasNestedPages = hasNestedPageFields(fields);\n\n // Determine mode and validate\n if (hasPageFields) {\n const errors: string[] = [];\n\n // For paged forms, ALL root fields must be pages\n if (!allPagesAtRoot) {\n errors.push('Mixed page and non-page fields at root level. In paged forms, ALL root-level fields must be of type \"page\".');\n }\n\n // Check for nested pages in any page field\n if (hasNestedPages) {\n errors.push('Page fields cannot contain nested page fields at any level.');\n }\n\n return {\n mode: 'paged',\n isValid: errors.length === 0,\n errors,\n };\n } else {\n // Non-paged form\n const errors: string[] = [];\n\n // Non-paged forms cannot have page fields anywhere\n if (hasAnyPageFields(fields)) {\n errors.push('Page fields are not allowed in non-paged forms.');\n }\n\n return {\n mode: 'non-paged',\n isValid: errors.length === 0,\n errors,\n };\n }\n}\n\n/**\n * Recursively checks if any field definition is a page field\n * @param fields Array of field definitions to check\n * @returns true if any page field is found at any level\n */\nfunction hasAnyPageFields(fields: FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isPageField(field)) {\n return true;\n }\n\n // Check nested fields in container types\n if (isContainerWithFields(field) && (field.type === 'row' || field.type === 'group')) {\n if (hasAnyPageFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if fields contain nested page fields within their children\n * (This is different from hasAnyPageFields as it checks NESTED pages, not root pages)\n * @param fields Array of field definitions to check\n * @returns true if nested page fields found\n */\nfunction hasNestedPageFields(fields: FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n // If this is a page field, check if its children contain pages\n if (isPageField(field) && isContainerWithFields(field)) {\n if (hasAnyPageFields(field.fields)) {\n return true;\n }\n }\n\n // Check other container types for nested pages\n if (isContainerWithFields(field) && (field.type === 'row' || field.type === 'group')) {\n if (hasNestedPageFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Type predicate for valid paged form configurations\n */\nexport function isValidPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n const result = detectFormMode(fields);\n return result.mode === 'paged' && result.isValid;\n}\n\n/**\n * Type predicate for valid non-paged form configurations\n */\nexport function isValidNonPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n const result = detectFormMode(fields);\n return result.mode === 'non-paged' && result.isValid;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isRowField } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../../models/field-type';\nimport { normalizeFieldsArray } from '../object-utils';\n\n/**\n * Represents a field definition that has been processed through the flattening algorithm.\n *\n * Guarantees that the field has a valid key property, either from the original\n * field definition or auto-generated during the flattening process.\n *\n * @public\n */\nexport interface FlattenedField extends FieldDef<unknown> {\n /** Guaranteed non-empty key for form binding and field identification */\n readonly key: string;\n}\n\n/**\n * Flattens a hierarchical field structure into a linear array for form processing.\n *\n * Handles different field types with specific flattening strategies:\n * - **Page fields**: Children are flattened and merged into the result (no wrapper)\n * - **Row fields**: Children are flattened and merged into the result (no wrapper), unless preserveRows=true\n * - **Group fields**: Maintains group structure with flattened children nested under the group key\n * - **Array fields**: Maintains array structure with flattened children nested under the array key\n * - **Other fields**: Pass through unchanged with guaranteed key generation\n *\n * Auto-generates keys for fields missing the key property to ensure form binding works correctly.\n *\n * @param fields - Array of field definitions that may contain nested structures\n * @param registry - Field type registry for determining value handling behavior\n * @param options - Configuration options for flattening behavior\n * @param options.preserveRows - When true, keep row fields in structure for DOM rendering (grid layout)\n * @returns Flattened array of field definitions with guaranteed keys\n *\n * @example\n * ```typescript\n * const hierarchicalFields = [\n * {\n * type: 'row',\n * fields: [\n * { type: 'input', key: 'firstName' },\n * { type: 'input', key: 'lastName' }\n * ]\n * },\n * {\n * type: 'group',\n * key: 'address',\n * fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city' }\n * ]\n * }\n * ];\n *\n * const flattened = flattenFields(hierarchicalFields, registry);\n * // Result: [\n * // { type: 'input', key: 'firstName' },\n * // { type: 'input', key: 'lastName' },\n * // { type: 'group', key: 'address', fields: [...] }\n * // ]\n * ```\n *\n * @example\n * ```typescript\n * // Auto-key generation for fields without keys\n * const fieldsWithoutKeys = [\n * { type: 'input', label: 'Name' },\n * { type: 'button', label: 'Submit' }\n * ];\n *\n * const flattened = flattenFields(fieldsWithoutKeys, registry);\n * // Result: [\n * // { type: 'input', label: 'Name', key: 'auto_field_0' },\n * // { type: 'button', label: 'Submit', key: 'auto_field_1' }\n * // ]\n * ```\n *\n * @public\n */\nexport function flattenFields(\n fields: FieldDef<unknown>[],\n registry: Map<string, FieldTypeDefinition>,\n options: { preserveRows?: boolean } = {},\n): FlattenedField[] {\n const result: FlattenedField[] = [];\n let autoKeyCounter = 0;\n\n // Process each field using appropriate strategy based on field type and configuration\n for (const field of fields) {\n // Step 1: Determine how this field type should handle its value in the form\n // valueHandling can be: 'include', 'exclude', or 'flatten'\n const valueHandling = getFieldValueHandling(field.type, registry);\n\n // Step 2: Check if this is a row field that should be preserved for DOM rendering\n // Row fields need to render their container element for grid layouts to work\n if (options.preserveRows && isRowField(field)) {\n if (field.fields) {\n // Recursively flatten children while preserving row structure\n const flattenedChildren = flattenFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], registry, options);\n\n // Keep the row field in the result with its flattened children\n // This allows the row component to render its container while children are flattened\n result.push({\n ...field,\n fields: flattenedChildren,\n key: field.key || `auto_row_${autoKeyCounter++}`,\n } as FlattenedField);\n }\n } else if (valueHandling === 'flatten' && 'fields' in field) {\n // Step 3: Handle fields with 'flatten' value handling (typically page/row fields)\n // These fields are pure containers - merge their children directly into the parent level\n if (field.fields) {\n const fields = field.fields as FieldDef<unknown>[] | Record<string, FieldDef<unknown>>;\n const flattenedChildren = flattenFields(normalizeFieldsArray(fields), registry, options);\n\n // Spread children directly into result - the container field itself is discarded\n // This is used for page fields (form structure) and row fields (form values)\n result.push(...flattenedChildren);\n }\n } else if (isGroupField(field)) {\n // Step 4: Handle group fields - preserve structure for nested form values\n // Group fields create a nested object in the form value: { groupKey: { field1: value1, ... } }\n const childFieldsArray = Object.values(field.fields) as FieldDef<unknown>[];\n const flattenedChildren = flattenFields(childFieldsArray, registry, options);\n\n // Keep the group field with its recursively flattened children nested under its key\n result.push({\n ...field,\n fields: flattenedChildren,\n key: field.key || `auto_group_${autoKeyCounter++}`,\n } as FlattenedField);\n } else if (isArrayField(field)) {\n // Step 5: Handle array fields - preserve structure for array form values\n // Array fields create an array in the form value: { arrayKey: [item1, item2, ...] }\n const childFieldsArray = Object.values(field.fields) as FieldDef<unknown>[];\n const flattenedChildren = flattenFields(childFieldsArray, registry, options);\n\n // Keep the array field with its template definition nested under its key\n result.push({\n ...field,\n fields: flattenedChildren,\n key: field.key || `auto_array_${autoKeyCounter++}`,\n } as FlattenedField);\n } else {\n // Step 6: Handle all other fields (inputs, buttons, etc.) - pass through unchanged\n // These fields are leaf nodes that don't contain children and map directly to form controls\n const key = field.key || `auto_field_${autoKeyCounter++}`;\n result.push({\n ...field,\n key,\n } as FlattenedField);\n }\n }\n\n return result;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { isStateLogicConfig, LogicConfig, StateLogicConfig } from '../../models/logic/logic-config';\nimport { ValidatorConfig, CustomValidatorConfig, BuiltInValidatorConfig } from '../../models/validation/validator-config';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { SchemaApplicationConfig } from '../../models/schemas/schema-definition';\nimport { hasChildFields } from '../../models/types/type-guards';\nimport { normalizeFieldsArray } from '../../utils/object-utils';\nimport {\n isCrossFieldValidator,\n isCrossFieldBuiltInValidator,\n hasCrossFieldWhenCondition,\n isCrossFieldStateLogic,\n isCrossFieldSchema,\n extractExpressionDependencies,\n extractStringDependencies,\n} from './cross-field-detector';\nimport { CrossFieldValidatorEntry, CrossFieldLogicEntry, CrossFieldSchemaEntry, LogicType } from './cross-field-types';\n\n/** Collected cross-field entries from traversing field definitions. */\nexport interface CrossFieldCollection {\n validators: CrossFieldValidatorEntry[];\n logic: CrossFieldLogicEntry[];\n schemas: CrossFieldSchemaEntry[];\n}\n\n/** Creates an empty cross-field collection. */\nexport function createEmptyCollection(): CrossFieldCollection {\n return {\n validators: [],\n logic: [],\n schemas: [],\n };\n}\n\n/** Traverses field definitions and collects cross-field entries (validators, logic, schemas). */\nexport function collectCrossFieldEntries(fields: FieldDef<unknown>[]): CrossFieldCollection {\n const collection = createEmptyCollection();\n traverseFields(fields, collection);\n return collection;\n}\n\nfunction traverseFields(fields: FieldDef<unknown>[], collection: CrossFieldCollection): void {\n for (const field of fields) {\n collectFromField(field, collection);\n\n // Recursively process container fields (page, row, group, array)\n if (hasChildFields(field)) {\n traverseFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], collection);\n }\n }\n}\n\nfunction collectFromField(field: FieldDef<unknown>, collection: CrossFieldCollection): void {\n const fieldKey = field.key;\n if (!fieldKey) return;\n\n const validationField = field as FieldDef<unknown> & FieldWithValidation;\n\n // Collect cross-field validators\n if (validationField.validators) {\n for (const config of validationField.validators) {\n const entry = tryCreateValidatorEntry(fieldKey, config);\n if (entry) {\n collection.validators.push(entry);\n }\n }\n }\n\n // Collect cross-field logic\n if (validationField.logic) {\n for (const config of validationField.logic) {\n const entry = tryCreateLogicEntry(fieldKey, config);\n if (entry) {\n collection.logic.push(entry);\n }\n }\n }\n\n // Collect cross-field schemas\n if (validationField.schemas) {\n for (const config of validationField.schemas) {\n const entry = tryCreateSchemaEntry(fieldKey, config);\n if (entry) {\n collection.schemas.push(entry);\n }\n }\n }\n}\n\n/** Returns a validator entry if cross-field, null otherwise. */\nfunction tryCreateValidatorEntry(fieldKey: string, config: ValidatorConfig): CrossFieldValidatorEntry | null {\n // Check for custom validators with cross-field expressions\n if (config.type === 'custom') {\n const customConfig = config as CustomValidatorConfig;\n if (isCrossFieldValidator(customConfig)) {\n return {\n sourceFieldKey: fieldKey,\n config,\n dependsOn: extractStringDependencies(customConfig.expression || ''),\n category: 'validator',\n };\n }\n }\n\n // Check for built-in validators with cross-field dynamic expressions\n if (isCrossFieldBuiltInValidator(config)) {\n const builtInConfig = config as BuiltInValidatorConfig;\n return {\n sourceFieldKey: fieldKey,\n config: convertBuiltInToCustomValidator(builtInConfig),\n validatorType: config.type,\n dependsOn: extractStringDependencies(builtInConfig.expression || ''),\n category: 'validator',\n };\n }\n\n // Check for validators with cross-field when conditions\n if (hasCrossFieldWhenCondition(config)) {\n const whenCondition = config.when as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n config,\n validatorType: config.type,\n dependsOn: extractExpressionDependencies(whenCondition),\n category: 'validator',\n };\n }\n\n return null;\n}\n\n/**\n * Returns a logic entry if cross-field state logic, null otherwise.\n *\n * Note: Derivation logic is handled separately by the derivation system\n * and is not collected here.\n */\nfunction tryCreateLogicEntry(fieldKey: string, config: LogicConfig): CrossFieldLogicEntry | null {\n // Only process state logic (hidden, readonly, disabled, required)\n // Derivation logic is handled by the derivation collector\n if (!isStateLogicConfig(config)) {\n return null;\n }\n\n if (!isCrossFieldStateLogic(config)) {\n return null;\n }\n\n const condition = config.condition as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n logicType: config.type as LogicType,\n condition,\n config: config as StateLogicConfig,\n dependsOn: extractExpressionDependencies(condition),\n category: 'logic',\n };\n}\n\n/** Returns a schema entry if cross-field, null otherwise. */\nfunction tryCreateSchemaEntry(fieldKey: string, config: SchemaApplicationConfig): CrossFieldSchemaEntry | null {\n if (!isCrossFieldSchema(config)) {\n return null;\n }\n\n const condition = config.condition as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n config,\n condition,\n dependsOn: extractExpressionDependencies(condition),\n category: 'schema',\n };\n}\n\n/** Converts a built-in validator with cross-field expression to a custom validator. */\nfunction convertBuiltInToCustomValidator(config: BuiltInValidatorConfig): CustomValidatorConfig {\n const expression = config.expression;\n if (!expression) {\n throw new Error(`Built-in validator ${config.type} missing required expression for cross-field conversion`);\n }\n let validationExpression: string;\n\n switch (config.type) {\n case 'min':\n validationExpression = `fieldValue == null || fieldValue >= (${expression})`;\n break;\n case 'max':\n validationExpression = `fieldValue == null || fieldValue <= (${expression})`;\n break;\n case 'minLength':\n validationExpression = `fieldValue == null || (typeof fieldValue !== 'string' && !Array.isArray(fieldValue)) || fieldValue.length >= (${expression})`;\n break;\n case 'maxLength':\n validationExpression = `fieldValue == null || (typeof fieldValue !== 'string' && !Array.isArray(fieldValue)) || fieldValue.length <= (${expression})`;\n break;\n case 'pattern':\n validationExpression = `fieldValue == null || new RegExp(${expression}).test(fieldValue)`;\n break;\n default:\n throw new Error(`Cannot convert ${config.type} validator to custom validator`);\n }\n\n return {\n type: 'custom',\n expression: validationExpression,\n kind: config.type,\n when: config.when,\n errorParams: {\n [config.type]: expression,\n },\n };\n}\n","import { detectFormMode, FormModeDetectionResult, isPageField } from '../../models/types/form-mode';\nimport { RegisteredFieldTypes } from '../../models/registry';\nimport { validatePageNesting } from '../../definitions/default/page-field';\nimport { isRowField, validateRowNesting } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\n\n/**\n * Comprehensive form configuration validator that checks:\n * 1. Form mode consistency (paged vs non-paged)\n * 2. Page nesting rules\n * 3. Row nesting rules (no hidden fields in rows)\n * 4. Field placement constraints\n */\nexport class FormModeValidator {\n /**\n * Validates a form configuration and returns detailed validation results\n * @param fields The form field definitions to validate\n * @returns Validation result with mode detection and error details\n */\n static validateFormConfiguration<TFields extends RegisteredFieldTypes[]>(fields: TFields): FormConfigurationValidationResult {\n const modeDetection = detectFormMode(fields);\n const additionalErrors: string[] = [];\n\n // Additional validation for paged forms\n if (modeDetection.mode === 'paged' && modeDetection.isValid) {\n // Validate each page field individually\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n if (isPageField(field)) {\n if (!validatePageNesting(field)) {\n additionalErrors.push(\n `Page field at index ${i} (key: \"${field.key || 'unknown'}\") contains nested page fields, which is not allowed.`,\n );\n }\n }\n }\n }\n\n const allErrors = [...modeDetection.errors, ...additionalErrors];\n const isFullyValid = modeDetection.isValid && additionalErrors.length === 0;\n\n return {\n mode: modeDetection.mode,\n isValid: isFullyValid,\n errors: allErrors,\n warnings: this.generateWarnings(fields, modeDetection),\n };\n }\n\n /**\n * Validates form configuration and throws an error if invalid\n * @param fields The form field definitions to validate\n * @throws Error with detailed validation messages if form is invalid\n */\n static validateFormConfigurationOrThrow<TFields extends RegisteredFieldTypes[]>(fields: TFields): void {\n const result = this.validateFormConfiguration(fields);\n\n if (!result.isValid) {\n const errorMessage = [`Invalid form configuration (${result.mode} mode):`, ...result.errors.map((error) => ` - ${error}`)].join(\n '\\n',\n );\n\n throw new DynamicFormError(errorMessage);\n }\n }\n\n /**\n * Generates helpful warnings for form configurations\n * @param fields The form field definitions\n * @param modeDetection The mode detection result\n * @returns Array of warning messages\n */\n private static generateWarnings<TFields extends RegisteredFieldTypes[]>(\n fields: TFields,\n modeDetection: FormModeDetectionResult,\n ): string[] {\n const warnings: string[] = [];\n\n // Warn about single page forms\n if (modeDetection.mode === 'paged' && fields.length === 1) {\n warnings.push('Single page form detected. Consider using non-paged mode for better performance if page navigation is not needed.');\n }\n\n // Warn about empty pages\n if (modeDetection.mode === 'paged') {\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n if (isPageField(field)) {\n if (!field.fields || field.fields.length === 0) {\n warnings.push(`Page field at index ${i} (key: \"${field.key || 'unknown'}\") contains no fields and will render as empty.`);\n }\n }\n }\n }\n\n // Warn about hidden fields in rows (they work but don't render, which may be confusing)\n const rowWarnings = this.collectRowHiddenFieldWarnings(fields);\n warnings.push(...rowWarnings);\n\n return warnings;\n }\n\n /**\n * Recursively collects warnings for hidden fields inside rows\n * @param fields The form field definitions to check\n * @param path Current path for warning messages\n * @returns Array of warning messages\n */\n private static collectRowHiddenFieldWarnings(fields: readonly FieldDef<unknown>[] | undefined, path = ''): string[] {\n if (!fields) {\n return [];\n }\n\n const warnings: string[] = [];\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const fieldPath = path ? `${path}.fields[${i}]` : `fields[${i}]`;\n const fieldKey = field.key || 'unknown';\n\n if (isRowField(field)) {\n if (!validateRowNesting(field)) {\n warnings.push(\n `Row field at ${fieldPath} (key: \"${fieldKey}\") contains hidden fields. ` +\n `Hidden fields in rows don't render anything - consider placing them outside the row.`,\n );\n }\n // Continue checking nested rows within the row's children\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isPageField(field)) {\n // Check rows within pages\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isGroupField(field)) {\n // Check rows within groups\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isArrayField(field)) {\n // Check rows within array templates\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n }\n }\n\n return warnings;\n }\n}\n\n/**\n * Extended validation result including warnings\n */\nexport interface FormConfigurationValidationResult extends FormModeDetectionResult {\n /** Array of warning messages that don't prevent form operation */\n warnings: string[];\n}\n\n/**\n * Convenience function for quick form mode validation\n * @param fields The form field definitions to validate\n * @returns True if form configuration is valid, false otherwise\n */\nexport function isValidFormConfiguration<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n return FormModeValidator.validateFormConfiguration(fields).isValid;\n}\n","/**\n * Centralized constants for the derivation system.\n *\n * These constants configure the behavior of derivation processing,\n * caching, and path handling. Centralizing them enables:\n * - Easy configuration changes\n * - Consistent values across all derivation modules\n * - Clear documentation of magic numbers\n *\n * @module\n */\n\n/**\n * Maximum number of derivation iterations before stopping to prevent infinite loops.\n *\n * The value of 10 is chosen based on:\n * - Most derivation chains are 2-3 levels deep (A→B→C)\n * - Complex forms with conditional cascades rarely exceed 5-6 levels\n * - 10 provides headroom for bidirectional sync patterns (A↔B) which may need\n * 2 iterations per pair to stabilize\n * - Higher values delay detection of actual infinite loops\n * - Lower values risk false positives on legitimate deep chains\n *\n * If you hit this limit legitimately, consider:\n * 1. Restructuring derivations to reduce chain depth\n * 2. Using explicit `dependsOn` to control evaluation order\n * 3. Breaking complex derivations into computed signals outside the form\n */\nexport const MAX_DERIVATION_ITERATIONS = 10;\n\n/**\n * Placeholder string for array index in derivation paths.\n *\n * Used in paths like `items.$.quantity` to represent \"each item in the array\".\n * The `$` is resolved to actual indices at runtime during array derivation processing.\n */\nexport const ARRAY_PLACEHOLDER = '.$.';\n\n/**\n * Maximum size of the expression AST cache.\n *\n * Expressions are parsed into Abstract Syntax Trees (AST) once and cached\n * to avoid re-parsing on each evaluation. The cache uses LRU eviction.\n *\n * 1000 entries handles:\n * - Large forms with many derivation expressions\n * - Multiple form instances with different expressions\n * - Memory efficiency (AST nodes are relatively small)\n */\nexport const MAX_AST_CACHE_SIZE = 1000;\n\n/**\n * Delimiter used to create unique derivation keys from source and target field keys.\n *\n * Uses null character (\\x00) which is extremely unlikely to appear in field names,\n * avoiding collision issues that could occur with common delimiters like ':'.\n */\nexport const DERIVATION_KEY_DELIMITER = '\\x00';\n","import { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { DerivationLogicConfig, LogicTrigger } from '../../models/logic/logic-config';\nimport { DERIVATION_KEY_DELIMITER } from './derivation-constants';\n\n/**\n * Entry representing a collected derivation from field definitions.\n *\n * Created during form initialization when traversing field definitions\n * to collect all derivation rules (both shorthand and full logic configs).\n *\n * @public\n */\nexport interface DerivationEntry {\n /**\n * The key of the field where this derivation is defined.\n *\n * For shorthand derivations, this is the same as `targetFieldKey`.\n * For full logic derivations, this is the field containing the logic array.\n */\n sourceFieldKey: string;\n\n /**\n * The key of the field whose value will be set.\n *\n * Can be:\n * - Absolute path: 'fieldName' or 'nested.field.path'\n * - Relative path for arrays: '$.siblingField' (same index as source)\n */\n targetFieldKey: string;\n\n /**\n * Field keys that this derivation depends on.\n *\n * Extracted from conditions and expressions.\n * Used for:\n * - Cycle detection\n * - Reactive dependency tracking\n * - Determining evaluation order\n */\n dependsOn: string[];\n\n /**\n * Condition that determines when this derivation applies.\n *\n * Defaults to `true` (always apply) if not specified.\n */\n condition: ConditionalExpression | boolean;\n\n /**\n * Static value to set on the target field.\n *\n * Mutually exclusive with `expression` and `functionName`.\n */\n value?: unknown;\n\n /**\n * JavaScript expression to evaluate for the derived value.\n *\n * Mutually exclusive with `value` and `functionName`.\n */\n expression?: string;\n\n /**\n * Name of a registered custom derivation function.\n *\n * Mutually exclusive with `value` and `expression`.\n */\n functionName?: string;\n\n /**\n * When to evaluate the derivation.\n *\n * - `onChange`: Evaluate immediately when dependencies change (default)\n * - `debounced`: Evaluate after value has stabilized for debounceMs\n *\n * @default 'onChange'\n */\n trigger: LogicTrigger;\n\n /**\n * Debounce duration in milliseconds.\n *\n * Only used when `trigger` is 'debounced'.\n * @default 500\n */\n debounceMs?: number;\n\n /**\n * Whether this derivation was created from the shorthand `derivation` property.\n *\n * Shorthand derivations always target the same field they're defined on.\n */\n isShorthand: boolean;\n\n /**\n * The original logic config if this entry was created from a full logic config.\n */\n originalConfig?: DerivationLogicConfig;\n\n /**\n * Optional debug name for easier identification in logs.\n *\n * Copied from the originalConfig if provided. When set, this name\n * appears in verbose derivation logs instead of the source→target path.\n */\n debugName?: string;\n}\n\n/**\n * Collection of all derivation entries from a form's field definitions.\n *\n * This interface is intentionally minimal - it contains only the core data.\n * Lookup maps are provided via {@link DerivationLookup} which computes\n * them lazily on demand.\n *\n * @public\n */\nexport interface DerivationCollection {\n /**\n * All derivation entries collected from field definitions,\n * sorted in topological order for efficient processing.\n */\n entries: DerivationEntry[];\n}\n\n/**\n * Result of cycle detection in the derivation graph.\n *\n * @public\n */\nexport interface CycleDetectionResult {\n /**\n * Whether a cycle was detected.\n */\n hasCycle: boolean;\n\n /**\n * Field paths involved in the cycle, if one was detected.\n *\n * Example: ['country', 'currency', 'country'] for a country -> currency -> country cycle.\n */\n cyclePath?: string[];\n\n /**\n * Bidirectional derivation pairs detected (A↔B patterns).\n *\n * These are allowed and stabilize via equality checks, but may oscillate\n * with floating-point precision issues (e.g., currency conversions).\n *\n * Format: ['fieldA↔fieldB', 'fieldC↔fieldD']\n */\n bidirectionalPairs?: string[];\n\n /**\n * Human-readable error message describing the cycle.\n */\n errorMessage?: string;\n}\n\n/**\n * Context for tracking derivation chain during runtime.\n *\n * Prevents infinite loops by tracking which derivations have already\n * been applied in the current update cycle.\n *\n * @internal\n */\nexport interface DerivationChainContext {\n /**\n * Set of derivation keys that have already been applied.\n *\n * Key format: \"sourceFieldKey:targetFieldKey\"\n */\n appliedDerivations: Set<string>;\n\n /**\n * Current iteration count in the derivation processing loop.\n */\n iteration: number;\n}\n\n/**\n * Creates an empty derivation collection.\n *\n * @returns Empty collection ready for population\n *\n * @internal\n */\nexport function createEmptyDerivationCollection(): DerivationCollection {\n return { entries: [] };\n}\n\n/**\n * Creates a new derivation chain context for tracking applied derivations.\n *\n * @returns Fresh context for a new derivation cycle\n *\n * @internal\n */\nexport function createDerivationChainContext(): DerivationChainContext {\n return {\n appliedDerivations: new Set(),\n iteration: 0,\n };\n}\n\n/**\n * Creates a unique key for a derivation entry.\n *\n * Uses a null character delimiter to avoid collision with field names\n * that might contain common delimiters like ':'.\n *\n * @param sourceKey - The source field key\n * @param targetKey - The target field key\n * @returns Unique key for the derivation\n *\n * @internal\n */\nexport function createDerivationKey(sourceKey: string, targetKey: string): string {\n return `${sourceKey}${DERIVATION_KEY_DELIMITER}${targetKey}`;\n}\n\n/**\n * Parses a derivation key back into source and target field keys.\n *\n * @param key - The derivation key to parse\n * @returns Object containing source and target field keys\n *\n * @internal\n */\nexport function parseDerivationKey(key: string): { sourceKey: string; targetKey: string } {\n const delimiterIndex = key.indexOf(DERIVATION_KEY_DELIMITER);\n return {\n sourceKey: key.substring(0, delimiterIndex),\n targetKey: key.substring(delimiterIndex + DERIVATION_KEY_DELIMITER.length),\n };\n}\n\n/**\n * Result of processing all pending derivations.\n *\n * @public\n */\nexport interface DerivationProcessingResult {\n /** Number of derivations successfully applied */\n appliedCount: number;\n\n /** Number of derivations skipped (condition not met or value unchanged) */\n skippedCount: number;\n\n /** Number of derivations that failed with errors */\n errorCount: number;\n\n /**\n * Number of derivations that encountered warnings (e.g., missing target field).\n *\n * These are not counted as errors because they may be intentional (conditional fields)\n * but indicate potential configuration issues if unexpected.\n */\n warnCount: number;\n\n /** Total iterations performed */\n iterations: number;\n\n /** Whether max iterations was reached (potential loop) */\n maxIterationsReached: boolean;\n}\n","import { InjectionToken, Signal } from '@angular/core';\nimport { DerivationEntry } from './derivation-types';\n\n/**\n * Injection token for the collected derivation entries.\n *\n * Provided at form level, contains the topologically sorted entries\n * after validation. This is the \"core data\" that other derivation\n * components consume.\n *\n * @example\n * ```typescript\n * // In a component or service\n * private readonly entries = inject(DERIVATION_ENTRIES);\n *\n * // Access the current entries\n * const currentEntries = this.entries();\n * ```\n */\nexport const DERIVATION_ENTRIES = new InjectionToken<Signal<DerivationEntry[]>>('DerivationEntries');\n","/**\n * Utilities for parsing and manipulating field paths in dynamic forms.\n *\n * Field paths follow these formats:\n * - Simple: \"fieldName\"\n * - Nested: \"parent.child.grandchild\"\n * - Array indexed: \"items.0.quantity\" or \"items[0].quantity\"\n * - Array placeholder: \"items.$.quantity\" ($ = any index)\n *\n * @module path-utils\n */\n\n/**\n * Result of parsing an array derivation path.\n *\n * @public\n */\nexport interface ArrayPathInfo {\n /** The array field path (e.g., \"items\" or \"orders.lineItems\") */\n arrayPath: string;\n\n /** The relative field path within the array item (e.g., \"quantity\" or \"lineTotal\") */\n relativePath: string;\n\n /** Whether this is a valid array path (contains .$. separator) */\n isArrayPath: boolean;\n}\n\n/**\n * Parses an array derivation path into its components.\n *\n * Array paths use the `$` placeholder to represent \"any index\".\n * Format: \"arrayPath.$.relativePath\"\n *\n * @param path - The path to parse (e.g., \"items.$.quantity\")\n * @returns Parsed path info with arrayPath and relativePath\n *\n * @example\n * ```typescript\n * parseArrayPath('items.$.quantity')\n * // { arrayPath: 'items', relativePath: 'quantity', isArrayPath: true }\n *\n * parseArrayPath('orders.lineItems.$.total')\n * // { arrayPath: 'orders.lineItems', relativePath: 'total', isArrayPath: true }\n *\n * parseArrayPath('simpleField')\n * // { arrayPath: '', relativePath: '', isArrayPath: false }\n * ```\n *\n * @public\n */\nexport function parseArrayPath(path: string): ArrayPathInfo {\n const ARRAY_PLACEHOLDER = '.$.';\n const placeholderIndex = path.indexOf(ARRAY_PLACEHOLDER);\n\n if (placeholderIndex === -1) {\n return {\n arrayPath: '',\n relativePath: '',\n isArrayPath: false,\n };\n }\n\n return {\n arrayPath: path.substring(0, placeholderIndex),\n relativePath: path.substring(placeholderIndex + ARRAY_PLACEHOLDER.length),\n isArrayPath: true,\n };\n}\n\n/**\n * Resolves an array placeholder path to a concrete indexed path.\n *\n * @param path - The path with $ placeholder (e.g., \"items.$.quantity\")\n * @param index - The array index to substitute\n * @returns Resolved path with index (e.g., \"items.0.quantity\")\n *\n * @example\n * ```typescript\n * resolveArrayPath('items.$.quantity', 2)\n * // 'items.2.quantity'\n *\n * resolveArrayPath('orders.lineItems.$.total', 0)\n * // 'orders.lineItems.0.total'\n * ```\n *\n * @public\n */\nexport function resolveArrayPath(path: string, index: number): string {\n const info = parseArrayPath(path);\n if (!info.isArrayPath) {\n return path;\n }\n return `${info.arrayPath}.${index}.${info.relativePath}`;\n}\n\n/**\n * Checks if a path contains an array placeholder.\n *\n * @param path - The path to check\n * @returns True if the path contains .$.\n *\n * @public\n */\nexport function isArrayPlaceholderPath(path: string): boolean {\n return path.includes('.$.');\n}\n\n/**\n * Extracts the array path from a path that may contain an array placeholder.\n *\n * @param path - The path to extract from\n * @returns The array path, or empty string if not an array path\n *\n * @example\n * ```typescript\n * extractArrayPath('items.$.quantity')\n * // 'items'\n *\n * extractArrayPath('orders.lineItems.$.total')\n * // 'orders.lineItems'\n *\n * extractArrayPath('simpleField')\n * // ''\n * ```\n *\n * @public\n */\nexport function extractArrayPath(path: string): string {\n return parseArrayPath(path).arrayPath;\n}\n\n/**\n * Splits a dot-separated path into segments.\n *\n * Handles both dot notation and bracket notation for array indices.\n *\n * @param path - The path to split\n * @returns Array of path segments\n *\n * @example\n * ```typescript\n * splitPath('parent.child.grandchild')\n * // ['parent', 'child', 'grandchild']\n *\n * splitPath('items.0.quantity')\n * // ['items', '0', 'quantity']\n * ```\n *\n * @public\n */\nexport function splitPath(path: string): string[] {\n if (!path) return [];\n return path.split('.');\n}\n\n/**\n * Joins path segments into a dot-separated path.\n *\n * @param segments - The path segments to join\n * @returns Joined path string\n *\n * @public\n */\nexport function joinPath(segments: string[]): string {\n return segments.join('.');\n}\n\n/**\n * Gets the parent path from a nested path.\n *\n * @param path - The path to get parent from\n * @returns The parent path, or empty string if no parent\n *\n * @example\n * ```typescript\n * getParentPath('parent.child.grandchild')\n * // 'parent.child'\n *\n * getParentPath('topLevel')\n * // ''\n * ```\n *\n * @public\n */\nexport function getParentPath(path: string): string {\n const segments = splitPath(path);\n if (segments.length <= 1) return '';\n return joinPath(segments.slice(0, -1));\n}\n\n/**\n * Gets the last segment (leaf) from a path.\n *\n * @param path - The path to get leaf from\n * @returns The last segment\n *\n * @example\n * ```typescript\n * getLeafPath('parent.child.grandchild')\n * // 'grandchild'\n *\n * getLeafPath('topLevel')\n * // 'topLevel'\n * ```\n *\n * @public\n */\nexport function getLeafPath(path: string): string {\n const segments = splitPath(path);\n return segments[segments.length - 1] ?? '';\n}\n\n// ============================================================================\n// Multi-Array Path Utilities\n// ============================================================================\n\n/**\n * Result of parsing a path with multiple array placeholders.\n *\n * @public\n */\nexport interface MultiArrayPathInfo {\n /** Whether this path contains array placeholders */\n isArrayPath: boolean;\n\n /** Number of array placeholders in the path */\n placeholderCount: number;\n\n /** Path segments (excluding $ placeholders) */\n segments: string[];\n\n /** The positions of '$' in the split path (by part index) */\n placeholderPositions: number[];\n}\n\n/**\n * Parses a path that may contain multiple array placeholders.\n *\n * This supports deeply nested array structures like `orders.$.items.$.quantity`\n * where multiple levels of arrays need to be traversed.\n *\n * @param path - Path with zero or more $ placeholders\n * @returns Parsed path information\n *\n * @example\n * ```typescript\n * parseMultiArrayPath('orders.$.items.$.quantity')\n * // {\n * // isArrayPath: true,\n * // placeholderCount: 2,\n * // segments: ['orders', 'items', 'quantity'],\n * // placeholderPositions: [1, 3]\n * // }\n *\n * parseMultiArrayPath('items.$.name')\n * // {\n * // isArrayPath: true,\n * // placeholderCount: 1,\n * // segments: ['items', 'name'],\n * // placeholderPositions: [1]\n * // }\n *\n * parseMultiArrayPath('simpleField')\n * // {\n * // isArrayPath: false,\n * // placeholderCount: 0,\n * // segments: ['simpleField'],\n * // placeholderPositions: []\n * // }\n * ```\n *\n * @public\n */\nexport function parseMultiArrayPath(path: string): MultiArrayPathInfo {\n const parts = path.split('.');\n const segments: string[] = [];\n const placeholderPositions: number[] = [];\n\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] === '$') {\n placeholderPositions.push(i);\n } else {\n segments.push(parts[i]);\n }\n }\n\n return {\n isArrayPath: placeholderPositions.length > 0,\n placeholderCount: placeholderPositions.length,\n segments,\n placeholderPositions,\n };\n}\n\n/**\n * Resolves a path with multiple array placeholders using provided indices.\n *\n * Each `$` placeholder is replaced with the corresponding index from the\n * indices array, in order.\n *\n * @param path - Path with $ placeholders (e.g., 'orders.$.items.$.quantity')\n * @param indices - Array of indices to substitute (e.g., [0, 2])\n * @returns Resolved path (e.g., 'orders.0.items.2.quantity')\n *\n * @throws Error if number of indices doesn't match number of placeholders\n *\n * @example\n * ```typescript\n * resolveMultiArrayPath('orders.$.items.$.quantity', [0, 2])\n * // 'orders.0.items.2.quantity'\n *\n * resolveMultiArrayPath('items.$.name', [5])\n * // 'items.5.name'\n * ```\n *\n * @public\n */\nexport function resolveMultiArrayPath(path: string, indices: number[]): string {\n const parts = path.split('.');\n let indexPointer = 0;\n\n const resolved = parts.map((part) => {\n if (part === '$') {\n if (indexPointer >= indices.length) {\n throw new Error(\n `Not enough indices provided for path '${path}'. ` +\n `Expected ${parts.filter((p) => p === '$').length} indices, got ${indices.length}.`,\n );\n }\n return String(indices[indexPointer++]);\n }\n return part;\n });\n\n if (indexPointer < indices.length) {\n throw new Error(`Too many indices provided for path '${path}'. ` + `Expected ${indexPointer} indices, got ${indices.length}.`);\n }\n\n return resolved.join('.');\n}\n\n/**\n * Counts the number of array placeholders in a path.\n *\n * @param path - The path to analyze\n * @returns Number of $ placeholders in the path\n *\n * @example\n * ```typescript\n * countArrayPlaceholders('orders.$.items.$.quantity')\n * // 2\n *\n * countArrayPlaceholders('items.$.name')\n * // 1\n *\n * countArrayPlaceholders('simpleField')\n * // 0\n * ```\n *\n * @public\n */\nexport function countArrayPlaceholders(path: string): number {\n return path.split('.').filter((part) => part === '$').length;\n}\n","import { inject, Injectable } from '@angular/core';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\nimport { isArrayPlaceholderPath, extractArrayPath } from '../../utils/path-utils/path-utils';\nimport { DERIVATION_ENTRIES } from './derivation-tokens';\nimport { DerivationEntry } from './derivation-types';\n\n/**\n * Provides lazy-computed lookup maps for derivation entries.\n *\n * Instead of pre-computing all lookup maps at collection time (which caused\n * hidden mutation and bloated the DerivationCollection god object), this class\n * computes maps lazily on first access and caches them.\n *\n * @example\n * ```typescript\n * const lookup = inject(DerivationLookup);\n *\n * // Lazy-computed on first access\n * const entriesForQuantity = lookup.byDependency.get('quantity');\n * const onChangeEntries = lookup.getOnChangeEntries();\n * ```\n */\n@Injectable()\nexport class DerivationLookup {\n private readonly entriesSignal = inject(DERIVATION_ENTRIES);\n\n // Track the entries array reference to auto-invalidate on change\n private _cachedEntriesRef?: DerivationEntry[];\n\n // Cached lookup maps (built lazily on first access)\n private _byTarget?: Map<string, DerivationEntry[]>;\n private _bySource?: Map<string, DerivationEntry[]>;\n private _byDependency?: Map<string, DerivationEntry[]>;\n private _byArrayPath?: Map<string, DerivationEntry[]>;\n private _wildcardEntries?: DerivationEntry[];\n private _onChangeEntries?: DerivationEntry[];\n private _debouncedEntriesByMs?: Map<number, DerivationEntry[]>;\n\n /**\n * Current derivation entries (from signal).\n * Auto-invalidates cache if entries reference changed.\n */\n get entries(): DerivationEntry[] {\n const currentEntries = this.entriesSignal();\n\n // Auto-invalidate if entries reference changed (schema was updated)\n if (this._cachedEntriesRef !== currentEntries) {\n this.invalidateCache();\n this._cachedEntriesRef = currentEntries;\n }\n\n return currentEntries;\n }\n\n /**\n * Map of target field key to entries that modify it.\n * Used for quick lookup when processing derivations.\n */\n get byTarget(): Map<string, DerivationEntry[]> {\n return (this._byTarget ??= this.buildByTargetMap());\n }\n\n /**\n * Map of source field key to entries defined on it.\n * Used for finding derivations when a field's value changes.\n */\n get bySource(): Map<string, DerivationEntry[]> {\n return (this._bySource ??= this.buildBySourceMap());\n }\n\n /**\n * Map of dependency field key to entries that depend on it.\n * Used for efficient O(1) lookup when filtering by changed fields.\n */\n get byDependency(): Map<string, DerivationEntry[]> {\n return (this._byDependency ??= this.buildByDependencyMap());\n }\n\n /**\n * Map of array path to entries that derive array item values.\n * Used for O(1) lookup when an array field changes.\n */\n get byArrayPath(): Map<string, DerivationEntry[]> {\n return (this._byArrayPath ??= this.buildByArrayPathMap());\n }\n\n /**\n * Entries that have wildcard (*) dependency.\n * These entries depend on all form values and must always be considered.\n */\n get wildcardEntries(): DerivationEntry[] {\n return (this._wildcardEntries ??= this.buildWildcardEntries());\n }\n\n /**\n * Gets entries that should be processed based on changed fields.\n *\n * Handles nested path matching: if 'address' changed, entries depending on\n * 'address.city' will also be included (parent change implies child changed).\n *\n * Uses O(k) lookup via indexed maps for exact matches, plus O(d) scan for\n * nested dependencies, where k = changed fields, d = unique dependencies.\n */\n getEntriesForChangedFields(changedFields: Set<string>): DerivationEntry[] {\n const entrySet = new Set<DerivationEntry>();\n\n // Add entries triggered by each changed field via byDependency map\n for (const fieldKey of changedFields) {\n const entries = this.byDependency.get(fieldKey);\n if (entries) {\n for (const entry of entries) {\n entrySet.add(entry);\n }\n }\n\n // Check if this changed field is an array path - O(1) lookup\n const arrayEntries = this.byArrayPath.get(fieldKey);\n if (arrayEntries) {\n for (const entry of arrayEntries) {\n entrySet.add(entry);\n }\n }\n\n // Handle nested dependencies: if 'address' changed, include entries\n // that depend on 'address.city', 'address.street', etc.\n // This is O(d) where d = number of unique dependency keys in the map.\n const fieldKeyPrefix = fieldKey + '.';\n for (const [depKey, depEntries] of this.byDependency) {\n if (depKey.startsWith(fieldKeyPrefix)) {\n for (const entry of depEntries) {\n entrySet.add(entry);\n }\n }\n }\n }\n\n // Add all wildcard entries - O(w) where w = number of wildcard entries\n for (const entry of this.wildcardEntries) {\n entrySet.add(entry);\n }\n\n return Array.from(entrySet);\n }\n\n /**\n * Gets entries with trigger 'onChange' (or no trigger, which defaults to onChange).\n */\n getOnChangeEntries(): DerivationEntry[] {\n return (this._onChangeEntries ??= this.entries.filter((e) => e.trigger !== 'debounced'));\n }\n\n /**\n * Gets entries with trigger 'debounced' for a specific debounce period.\n */\n getDebouncedEntries(debounceMs: number): DerivationEntry[] {\n if (!this._debouncedEntriesByMs) {\n this._debouncedEntriesByMs = this.buildDebouncedEntriesMap();\n }\n return this._debouncedEntriesByMs.get(debounceMs) ?? [];\n }\n\n /**\n * Gets all unique debounce periods that have entries.\n */\n getDebouncePeriods(): number[] {\n if (!this._debouncedEntriesByMs) {\n this._debouncedEntriesByMs = this.buildDebouncedEntriesMap();\n }\n return Array.from(this._debouncedEntriesByMs.keys());\n }\n\n /**\n * Invalidates cached maps. Call this when entries change.\n */\n invalidateCache(): void {\n this._byTarget = undefined;\n this._bySource = undefined;\n this._byDependency = undefined;\n this._byArrayPath = undefined;\n this._wildcardEntries = undefined;\n this._onChangeEntries = undefined;\n this._debouncedEntriesByMs = undefined;\n }\n\n // ─────────────────────────────────────────────────────────────────\n // Private builders\n // ─────────────────────────────────────────────────────────────────\n\n private buildByTargetMap(): Map<string, DerivationEntry[]> {\n const map = new Map<string, DerivationEntry[]>();\n for (const entry of this.entries) {\n const targetEntries = map.get(entry.targetFieldKey) ?? [];\n targetEntries.push(entry);\n map.set(entry.targetFieldKey, targetEntries);\n }\n return map;\n }\n\n private buildBySourceMap(): Map<string, DerivationEntry[]> {\n const map = new Map<string, DerivationEntry[]>();\n for (const entry of this.entries) {\n const sourceEntries = map.get(entry.sourceFieldKey) ?? [];\n sourceEntries.push(entry);\n map.set(entry.sourceFieldKey, sourceEntries);\n }\n return map;\n }\n\n private buildByDependencyMap(): Map<string, DerivationEntry[]> {\n const map = new Map<string, DerivationEntry[]>();\n for (const entry of this.entries) {\n for (const dep of entry.dependsOn) {\n if (dep !== '*') {\n const depEntries = map.get(dep) ?? [];\n depEntries.push(entry);\n map.set(dep, depEntries);\n }\n }\n }\n return map;\n }\n\n private buildByArrayPathMap(): Map<string, DerivationEntry[]> {\n const map = new Map<string, DerivationEntry[]>();\n for (const entry of this.entries) {\n if (isArrayPlaceholderPath(entry.targetFieldKey)) {\n const arrayPath = extractArrayPath(entry.targetFieldKey);\n if (arrayPath) {\n const arrayEntries = map.get(arrayPath) ?? [];\n arrayEntries.push(entry);\n map.set(arrayPath, arrayEntries);\n }\n }\n }\n return map;\n }\n\n private buildWildcardEntries(): DerivationEntry[] {\n return this.entries.filter((entry) => entry.dependsOn.includes('*'));\n }\n\n private buildDebouncedEntriesMap(): Map<number, DerivationEntry[]> {\n const map = new Map<number, DerivationEntry[]>();\n for (const entry of this.entries) {\n if (entry.trigger === 'debounced') {\n const ms = entry.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n const group = map.get(ms) ?? [];\n group.push(entry);\n map.set(ms, group);\n }\n }\n return map;\n }\n}\n","import { DerivationEntry } from './derivation-types';\n\n/**\n * Sorts derivation entries in topological order based on their dependencies.\n *\n * This ensures that derivations are processed in the correct order:\n * if derivation B depends on field A, and derivation A->A' modifies A,\n * then A->A' is processed before B.\n *\n * Uses Kahn's algorithm for topological sorting, which also provides\n * natural handling of entries with no dependencies (they come first).\n *\n * @param entries - The derivation entries to sort\n * @returns A new array of entries in topological order\n *\n * @example\n * ```typescript\n * // Given derivations:\n * // 1. quantity -> lineTotal (depends on quantity, unitPrice)\n * // 2. unitPrice -> lineTotal (depends on quantity, unitPrice)\n * // 3. lineTotal -> grandTotal (depends on lineTotal)\n * //\n * // Topological sort ensures lineTotal is computed before grandTotal\n * const sorted = topologicalSort(entries);\n * // Result: [1, 2, 3] - derivations that produce lineTotal come before\n * // those that consume it\n * ```\n *\n * @public\n */\nexport function topologicalSort(entries: DerivationEntry[]): DerivationEntry[] {\n if (entries.length <= 1) {\n return [...entries];\n }\n\n // Build adjacency list and in-degree count\n // An edge A -> B exists if B depends on the target of A\n const graph = new Map<DerivationEntry, Set<DerivationEntry>>();\n const inDegree = new Map<DerivationEntry, number>();\n\n // Initialize\n for (const entry of entries) {\n graph.set(entry, new Set());\n inDegree.set(entry, 0);\n }\n\n // Pre-build index: target field -> entries that produce it\n // This enables O(1) lookup instead of O(n) scanning\n const producersByTarget = new Map<string, DerivationEntry[]>();\n for (const entry of entries) {\n // Index by exact target field\n const producers = producersByTarget.get(entry.targetFieldKey) ?? [];\n producers.push(entry);\n producersByTarget.set(entry.targetFieldKey, producers);\n\n // Also index array field relative paths for array derivations\n // If entry targets 'items.$.lineTotal', index under 'lineTotal' too\n if (entry.targetFieldKey.includes('.$.')) {\n const relativePath = entry.targetFieldKey.split('.$.')[1];\n if (relativePath) {\n const relativeProducers = producersByTarget.get(relativePath) ?? [];\n relativeProducers.push(entry);\n producersByTarget.set(relativePath, relativeProducers);\n }\n }\n }\n\n // Collect entries with wildcard dependencies (need special handling)\n const wildcardDependents: DerivationEntry[] = [];\n for (const entry of entries) {\n if (entry.dependsOn.includes('*')) {\n wildcardDependents.push(entry);\n }\n }\n\n // Build edges using pre-computed index\n // For each entry B, find all entries A whose target is in B's dependencies\n for (const entryB of entries) {\n for (const dep of entryB.dependsOn) {\n // Skip wildcards here - handled separately below\n if (dep === '*') continue;\n\n // O(1) lookup: find all producers of this dependency\n const producers = producersByTarget.get(dep);\n if (producers) {\n for (const entryA of producers) {\n const entryAEdges = graph.get(entryA);\n if (entryA !== entryB && entryAEdges && !entryAEdges.has(entryB)) {\n entryAEdges.add(entryB);\n inDegree.set(entryB, (inDegree.get(entryB) ?? 0) + 1);\n }\n }\n }\n }\n }\n\n // Handle wildcard dependencies: they depend on ALL producers\n for (const entryB of wildcardDependents) {\n for (const entryA of entries) {\n const entryAEdges = graph.get(entryA);\n if (entryA !== entryB && entryAEdges && !entryAEdges.has(entryB)) {\n entryAEdges.add(entryB);\n inDegree.set(entryB, (inDegree.get(entryB) ?? 0) + 1);\n }\n }\n }\n\n // Kahn's algorithm: process nodes with in-degree 0\n const queue: DerivationEntry[] = [];\n const sorted: DerivationEntry[] = [];\n\n // Start with entries that have no dependencies on other derivation outputs\n for (const entry of entries) {\n if (inDegree.get(entry) === 0) {\n queue.push(entry);\n }\n }\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break; // TypeScript guard (shouldn't happen due to while condition)\n sorted.push(current);\n\n // Reduce in-degree for all neighbors\n const neighbors = graph.get(current) ?? new Set<DerivationEntry>();\n for (const neighbor of neighbors) {\n const newDegree = (inDegree.get(neighbor) ?? 0) - 1;\n inDegree.set(neighbor, newDegree);\n\n if (newDegree === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n // If we couldn't sort all entries, there's a cycle\n // (but cycles should be caught by cycle-detector, so this is defensive)\n if (sorted.length !== entries.length) {\n // Return original order for entries in cycles\n const sortedSet = new Set(sorted);\n for (const entry of entries) {\n if (!sortedSet.has(entry)) {\n sorted.push(entry);\n }\n }\n }\n\n return sorted;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { DerivationLogicConfig, isDerivationLogicConfig } from '../../models/logic/logic-config';\nimport { hasChildFields } from '../../models/types/type-guards';\nimport { normalizeFieldsArray } from '../../utils/object-utils';\nimport { extractExpressionDependencies, extractStringDependencies } from '../cross-field/cross-field-detector';\nimport { topologicalSort } from './derivation-sorter';\nimport { DerivationCollection, DerivationEntry } from './derivation-types';\n\n/**\n * Context for collecting derivations, tracking the current array path for relative references.\n *\n * @internal\n */\ninterface CollectionContext {\n /**\n * Current array path for resolving relative field references.\n *\n * When inside an array field, this contains the path to the array item\n * (e.g., 'items[0]' or 'orders[1].lineItems[2]').\n */\n arrayPath?: string;\n}\n\n/**\n * Collects all derivation entries from field definitions.\n *\n * This function traverses the field definition tree and extracts:\n * - Shorthand `derivation` properties on fields\n * - Full `logic` array entries with `type: 'derivation'`\n *\n * The collected entries include dependency information for cycle detection\n * and reactive evaluation. Entries are sorted topologically so derivations\n * are processed in dependency order.\n *\n * Lookup maps (byTarget, byDependency, etc.) are NOT built here - they are\n * computed lazily via {@link DerivationLookup} to avoid hidden mutation\n * and reduce the size of the returned collection.\n *\n * @param fields - Array of field definitions to traverse\n * @returns Collection containing sorted derivation entries\n *\n * @example\n * ```typescript\n * const fields = [\n * { key: 'quantity', type: 'number' },\n * { key: 'unitPrice', type: 'number' },\n * {\n * key: 'total',\n * type: 'number',\n * derivation: 'formValue.quantity * formValue.unitPrice',\n * },\n * ];\n *\n * const collection = collectDerivations(fields);\n * // collection.entries has 1 entry for the 'total' field derivation\n * ```\n *\n * @public\n */\nexport function collectDerivations(fields: FieldDef<unknown>[]): DerivationCollection {\n const entries: DerivationEntry[] = [];\n const context: CollectionContext = {};\n\n traverseFields(fields, entries, context);\n\n // Sort entries in topological order for efficient processing.\n // This ensures derivations are processed in dependency order,\n // reducing the number of iterations needed in the applicator.\n const sortedEntries = topologicalSort(entries);\n\n return { entries: sortedEntries };\n}\n\n/**\n * Recursively traverses field definitions to collect derivations.\n *\n * @internal\n */\nfunction traverseFields(fields: FieldDef<unknown>[], entries: DerivationEntry[], context: CollectionContext): void {\n for (const field of fields) {\n collectFromField(field, entries, context);\n\n // Recursively process container fields (page, row, group, array)\n if (hasChildFields(field)) {\n const childContext = { ...context };\n\n // Update array path context if this is an array field\n if (field.type === 'array') {\n childContext.arrayPath = field.key;\n }\n\n traverseFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], entries, childContext);\n }\n }\n}\n\n/**\n * Collects derivation entries from a single field.\n *\n * @internal\n */\nfunction collectFromField(field: FieldDef<unknown>, entries: DerivationEntry[], context: CollectionContext): void {\n const fieldKey = field.key;\n if (!fieldKey) return;\n\n const validationField = field as FieldDef<unknown> & FieldWithValidation;\n\n // Collect shorthand derivation property\n if (validationField.derivation) {\n const entry = createShorthandEntry(fieldKey, validationField.derivation);\n entries.push(entry);\n }\n\n // Collect logic array derivations\n if (validationField.logic) {\n for (const logicConfig of validationField.logic) {\n if (isDerivationLogicConfig(logicConfig)) {\n const entry = createLogicEntry(fieldKey, logicConfig, context);\n entries.push(entry);\n }\n }\n }\n}\n\n/**\n * Creates a derivation entry from the shorthand `derivation` property.\n *\n * Shorthand derivations:\n * - Always target the same field they're defined on\n * - Always apply (condition defaults to true)\n * - Always trigger on change\n *\n * @internal\n */\nfunction createShorthandEntry(fieldKey: string, expression: string): DerivationEntry {\n return {\n sourceFieldKey: fieldKey,\n targetFieldKey: fieldKey,\n dependsOn: extractStringDependencies(expression),\n condition: true,\n expression,\n trigger: 'onChange',\n isShorthand: true,\n };\n}\n\n/**\n * Creates a derivation entry from a full `DerivationLogicConfig`.\n *\n * Handles:\n * - Condition extraction and dependency analysis\n * - Relative path resolution for array fields\n * - Multiple value source types (static, expression, function)\n * - Trigger and debounce configuration\n *\n * @internal\n */\nfunction createLogicEntry(fieldKey: string, config: DerivationLogicConfig, context: CollectionContext): DerivationEntry {\n const targetFieldKey = resolveTargetFieldKey(config.targetField, fieldKey, context);\n const dependsOn = extractDependencies(config);\n const condition = config.condition ?? true;\n const trigger = config.trigger ?? 'onChange';\n\n // Extract debounceMs from debounced configs\n // The type system ensures debounceMs is only present when trigger is 'debounced'\n const debounceMs = trigger === 'debounced' ? (config as { debounceMs?: number }).debounceMs : undefined;\n\n return {\n sourceFieldKey: fieldKey,\n targetFieldKey,\n dependsOn,\n condition,\n value: config.value,\n expression: config.expression,\n functionName: config.functionName,\n trigger,\n debounceMs,\n isShorthand: false,\n originalConfig: config,\n debugName: config.debugName,\n };\n}\n\n/**\n * Resolves a target field key, handling relative paths for array fields.\n *\n * Relative paths start with '$.' and reference siblings at the same array index.\n *\n * @param targetField - The target field specification from config\n * @param sourceFieldKey - The source field key\n * @param context - Current collection context with array path info\n * @returns Resolved target field key\n *\n * @example\n * ```typescript\n * // Absolute path - returned as-is\n * resolveTargetFieldKey('phonePrefix', 'country', {})\n * // Returns: 'phonePrefix'\n *\n * // Relative path in array context\n * resolveTargetFieldKey('$.lineTotal', 'items[0].quantity', { arrayPath: 'items' })\n * // Returns: 'items.$.lineTotal'\n * ```\n *\n * @internal\n */\nfunction resolveTargetFieldKey(targetField: string, _sourceFieldKey: string, context: CollectionContext): string {\n // Check for relative path indicator\n if (targetField.startsWith('$.')) {\n // Extract the relative field name (after '$.')\n const relativePath = targetField.substring(2);\n\n if (context.arrayPath) {\n // Replace '$' with the array path for pattern matching\n return `${context.arrayPath}.$.${relativePath}`;\n }\n\n // Not in array context - keep relative path as-is.\n // This indicates a configuration error (relative path used outside array).\n // The runtime applicator will handle this gracefully.\n return targetField;\n }\n\n // Absolute path - return as-is\n return targetField;\n}\n\n/**\n * Extracts all field dependencies from a derivation config.\n *\n * Combines dependencies from:\n * - Explicit `dependsOn` array (if provided, takes precedence)\n * - Condition expression\n * - Value expression\n * - Function name (defaults to '*' if no explicit dependsOn)\n *\n * @internal\n */\nfunction extractDependencies(config: DerivationLogicConfig): string[] {\n const deps = new Set<string>();\n\n // If explicit dependsOn is provided, use it as the primary source\n // This allows users to override automatic detection and control\n // when derivations are triggered\n if (config.dependsOn && config.dependsOn.length > 0) {\n config.dependsOn.forEach((dep) => deps.add(dep));\n } else {\n // Extract from expression (automatic dependency detection)\n if (config.expression) {\n const exprDeps = extractStringDependencies(config.expression);\n exprDeps.forEach((dep) => deps.add(dep));\n }\n\n // Custom functions assume full form access if no explicit dependsOn\n if (config.functionName) {\n deps.add('*');\n }\n }\n\n // Always extract from condition (these are additional runtime guards)\n if (config.condition && config.condition !== true) {\n const conditionDeps = extractExpressionDependencies(config.condition);\n conditionDeps.forEach((dep) => deps.add(dep));\n }\n\n return Array.from(deps);\n}\n","import { isDevMode } from '@angular/core';\nimport { CycleDetectionResult, DerivationCollection } from './derivation-types';\nimport { Logger } from '../../providers/features/logger/logger.interface';\n\n/**\n * Node in the derivation dependency graph.\n *\n * @internal\n */\ninterface GraphNode {\n /** Field key this node represents */\n fieldKey: string;\n\n /** Set of field keys this node depends on (edges to other nodes) */\n dependsOn: Set<string>;\n\n /** Set of field keys that depend on this node (reverse edges) */\n dependedOnBy: Set<string>;\n}\n\n/**\n * State for topological sort cycle detection.\n *\n * @internal\n */\nconst enum VisitState {\n /** Node has not been visited */\n Unvisited = 0,\n /** Node is currently being processed (in the stack) */\n InProgress = 1,\n /** Node has been fully processed */\n Completed = 2,\n}\n\n/**\n * Detects cycles in the derivation dependency graph.\n *\n * Uses Kahn's algorithm variant with DFS to detect cycles.\n * Bidirectional sync patterns (A→B→A) are allowed because they stabilize\n * via the equality check at runtime.\n *\n * @param collection - The collected derivation entries\n * @returns Result indicating whether a cycle exists and details if found\n *\n * @example\n * ```typescript\n * const collection = collectDerivations(fields);\n * const result = detectCycles(collection);\n *\n * if (result.hasCycle) {\n * console.error(`Cycle detected: ${result.cyclePath?.join(' -> ')}`);\n * throw new Error(result.errorMessage);\n * }\n * ```\n *\n * @public\n */\nexport function detectCycles(collection: DerivationCollection): CycleDetectionResult {\n // Build directed graph from derivation entries\n const graph = buildDependencyGraph(collection);\n\n // No entries means no cycles\n if (graph.size === 0) {\n return { hasCycle: false };\n }\n\n // Build bidirectional pairs set for cycle exemption\n const bidirectionalPairs = detectBidirectionalPairs(collection);\n\n // Run DFS to detect cycles\n const result = detectCyclesWithDFS(graph, bidirectionalPairs);\n\n // Include bidirectional pairs in result for warnings\n if (bidirectionalPairs.size > 0) {\n result.bidirectionalPairs = Array.from(bidirectionalPairs);\n }\n\n return result;\n}\n\n/**\n * Detects bidirectional derivation pairs (A→B and B→A).\n *\n * These patterns are allowed because they stabilize via equality checks.\n * Example: USD/EUR conversion where both fields derive from each other.\n *\n * ## Floating-Point Precision Note\n *\n * Bidirectional derivations stabilize via equality checks using exact IEEE 754\n * comparison with no tolerance. This means:\n *\n * - **Integer math**: Safe (e.g., `A = B * 2`, `B = A / 2` where A is even)\n * - **Floating-point math**: May oscillate due to rounding errors\n *\n * For currency conversions or other floating-point operations, consider:\n * 1. Rounding values in your expression (e.g., `Math.round(value * 100) / 100`)\n * 2. Using integer cents instead of decimal dollars\n * 3. Using one-way derivation instead of bidirectional\n *\n * @example\n * ```typescript\n * // Safe - uses rounding to avoid oscillation\n * logic: [\n * {\n * type: 'derivation',\n * targetField: 'eur',\n * expression: 'Math.round(formValue.usd * 0.92 * 100) / 100'\n * }\n * ]\n * ```\n *\n * @internal\n */\nfunction detectBidirectionalPairs(collection: DerivationCollection): Set<string> {\n const pairs = new Set<string>();\n const edgeSet = new Set<string>();\n\n // Build set of all source→target edges\n for (const entry of collection.entries) {\n if (entry.sourceFieldKey !== entry.targetFieldKey) {\n edgeSet.add(`${entry.sourceFieldKey}→${entry.targetFieldKey}`);\n }\n }\n\n // Find bidirectional pairs (A→B exists AND B→A exists)\n for (const entry of collection.entries) {\n const reverseEdge = `${entry.targetFieldKey}→${entry.sourceFieldKey}`;\n if (edgeSet.has(reverseEdge)) {\n // Normalize pair key (alphabetically sorted)\n const pairKey =\n entry.sourceFieldKey < entry.targetFieldKey\n ? `${entry.sourceFieldKey}↔${entry.targetFieldKey}`\n : `${entry.targetFieldKey}↔${entry.sourceFieldKey}`;\n pairs.add(pairKey);\n }\n }\n\n return pairs;\n}\n\n/**\n * Checks if a cycle path represents a bidirectional pair.\n *\n * @internal\n */\nfunction isBidirectionalCycle(cyclePath: string[], bidirectionalPairs: Set<string>): boolean {\n // Bidirectional cycles are exactly: [A, B, A] (length 3 with first=last)\n if (cyclePath.length !== 3) {\n return false;\n }\n\n const [first, second, third] = cyclePath;\n if (first !== third) {\n return false;\n }\n\n // Check if this pair is in our bidirectional set\n const pairKey = first < second ? `${first}↔${second}` : `${second}↔${first}`;\n return bidirectionalPairs.has(pairKey);\n}\n\n/**\n * Builds a dependency graph from derivation entries.\n *\n * Creates nodes for each field involved in derivations and\n * edges representing the derivation dependencies.\n *\n * Edge direction: sourceField -> targetField\n * (source triggers derivation that modifies target)\n *\n * @internal\n */\nfunction buildDependencyGraph(collection: DerivationCollection): Map<string, GraphNode> {\n const graph = new Map<string, GraphNode>();\n\n // Helper to ensure a node exists\n const ensureNode = (fieldKey: string): GraphNode => {\n let node = graph.get(fieldKey);\n if (!node) {\n node = {\n fieldKey,\n dependsOn: new Set(),\n dependedOnBy: new Set(),\n };\n graph.set(fieldKey, node);\n }\n return node;\n };\n\n for (const entry of collection.entries) {\n const sourceNode = ensureNode(entry.sourceFieldKey);\n const targetNode = ensureNode(entry.targetFieldKey);\n\n // For cycle detection, we care about the data flow:\n // When sourceField changes -> targetField gets updated\n // So the edge is: sourceField -> targetField\n //\n // A cycle exists if: A -> B -> A\n // (A triggers B, B triggers A)\n\n // For self-referential derivations (where source === target), don't add source->target edge.\n // This includes:\n // 1. Shorthand derivations (field.derivation = 'expression')\n // 2. Self-transform derivations (logic: [{ targetField: 'self', ... }])\n // These are legitimate patterns for computed fields and value transformations,\n // not actual cycles. The real dependencies come from the expression (tracked in dependsOn).\n const isSelfReferential = entry.sourceFieldKey === entry.targetFieldKey;\n if (!isSelfReferential) {\n // The target depends on the source for its value\n targetNode.dependsOn.add(entry.sourceFieldKey);\n sourceNode.dependedOnBy.add(entry.targetFieldKey);\n }\n\n // Also track dependencies from the derivation expression/condition\n for (const dep of entry.dependsOn) {\n if (dep !== '*' && dep !== entry.targetFieldKey) {\n const depNode = ensureNode(dep);\n targetNode.dependsOn.add(dep);\n depNode.dependedOnBy.add(entry.targetFieldKey);\n }\n }\n }\n\n return graph;\n}\n\n/**\n * Detects cycles using depth-first search.\n *\n * Uses three-color marking:\n * - Unvisited (white): Not yet processed\n * - InProgress (gray): Currently in the DFS stack\n * - Completed (black): Fully processed\n *\n * A cycle is detected when we visit a node that's InProgress,\n * unless it's a bidirectional sync pattern (allowed).\n *\n * @internal\n */\nfunction detectCyclesWithDFS(graph: Map<string, GraphNode>, bidirectionalPairs: Set<string>): CycleDetectionResult {\n const visitState = new Map<string, VisitState>();\n const parent = new Map<string, string | null>();\n\n // Initialize all nodes as unvisited\n for (const fieldKey of graph.keys()) {\n visitState.set(fieldKey, VisitState.Unvisited);\n }\n\n // Process each unvisited node\n for (const fieldKey of graph.keys()) {\n if (visitState.get(fieldKey) === VisitState.Unvisited) {\n const cycleResult = dfsVisit(fieldKey, graph, visitState, parent, [], bidirectionalPairs);\n if (cycleResult) {\n return cycleResult;\n }\n }\n }\n\n return { hasCycle: false };\n}\n\n/**\n * DFS visit function that detects back edges (cycles).\n *\n * @internal\n */\nfunction dfsVisit(\n fieldKey: string,\n graph: Map<string, GraphNode>,\n visitState: Map<string, VisitState>,\n parent: Map<string, string | null>,\n path: string[],\n bidirectionalPairs: Set<string>,\n): CycleDetectionResult | null {\n visitState.set(fieldKey, VisitState.InProgress);\n path.push(fieldKey);\n\n const node = graph.get(fieldKey);\n if (!node) {\n visitState.set(fieldKey, VisitState.Completed);\n path.pop();\n return null;\n }\n\n // Check all nodes that this field's changes would trigger\n for (const targetFieldKey of node.dependedOnBy) {\n const targetState = visitState.get(targetFieldKey);\n\n if (targetState === VisitState.InProgress) {\n // Back edge found - potential cycle\n const cyclePath = extractCyclePath(path, targetFieldKey);\n\n // Allow bidirectional sync patterns (A→B→A)\n // These stabilize via equality checks at runtime\n if (isBidirectionalCycle(cyclePath, bidirectionalPairs)) {\n // Continue DFS without reporting this as a cycle\n continue;\n }\n\n return {\n hasCycle: true,\n cyclePath,\n errorMessage: formatCycleError(cyclePath),\n };\n }\n\n if (targetState === VisitState.Unvisited) {\n parent.set(targetFieldKey, fieldKey);\n const result = dfsVisit(targetFieldKey, graph, visitState, parent, path, bidirectionalPairs);\n if (result) {\n return result;\n }\n }\n }\n\n visitState.set(fieldKey, VisitState.Completed);\n path.pop();\n return null;\n}\n\n/**\n * Extracts the cycle path from the DFS path.\n *\n * @internal\n */\nfunction extractCyclePath(path: string[], cycleStart: string): string[] {\n const cycleStartIndex = path.indexOf(cycleStart);\n if (cycleStartIndex === -1) {\n // Shouldn't happen, but handle gracefully\n return [...path, cycleStart];\n }\n\n // Extract from cycle start to current position, then back to start\n const cyclePath = path.slice(cycleStartIndex);\n cyclePath.push(cycleStart); // Close the cycle\n return cyclePath;\n}\n\n/**\n * Formats a human-readable error message for a detected cycle.\n *\n * @internal\n */\nfunction formatCycleError(cyclePath: string[]): string {\n const pathStr = cyclePath.join(' -> ');\n return (\n `Derivation cycle detected: ${pathStr}\\n` +\n `This would cause an infinite loop at runtime. ` +\n `Remove one of the derivations to break the cycle.`\n );\n}\n\n/**\n * Validates a derivation collection and throws if cycles are detected.\n *\n * This is the main entry point for cycle validation during form initialization.\n * Should be called after collecting derivations and before setting up effects.\n *\n * In dev mode, logs a warning when bidirectional derivation pairs are detected.\n * These patterns are allowed but may oscillate with floating-point values.\n *\n * @param collection - The collected derivation entries to validate\n * @param logger - Optional logger for dev-mode warnings\n * @throws Error if a cycle is detected, with details about the cycle\n *\n * @example\n * ```typescript\n * const collection = collectDerivations(fields);\n *\n * // This will throw if cycles exist\n * validateNoCycles(collection, logger);\n *\n * // Safe to set up derivation effects now\n * setupDerivationEffects(collection);\n * ```\n *\n * @public\n */\nexport function validateNoCycles(collection: DerivationCollection, logger?: Logger): void {\n const result = detectCycles(collection);\n\n if (result.hasCycle) {\n throw new Error(result.errorMessage);\n }\n\n // Warn about bidirectional patterns in dev mode\n if (isDevMode() && result.bidirectionalPairs && result.bidirectionalPairs.length > 0 && logger) {\n logger.warn(\n '[Derivation] Bidirectional derivation patterns detected. ' +\n 'These patterns stabilize via equality checks, but may oscillate with floating-point values ' +\n '(e.g., currency conversions with rounding). ' +\n 'Consider adding tolerance-based comparisons for numeric values.',\n result.bidirectionalPairs,\n );\n }\n}\n","import { isWritableSignal, Signal, untracked } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { isEqual } from '../../utils/object-utils';\nimport { parseArrayPath, resolveArrayPath, isArrayPlaceholderPath } from '../../utils/path-utils/path-utils';\nimport { CustomFunction } from '../expressions/custom-function-types';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport {\n createDerivationChainContext,\n createDerivationKey,\n DerivationChainContext,\n DerivationCollection,\n DerivationEntry,\n DerivationProcessingResult,\n} from './derivation-types';\nimport { DerivationWarningTracker } from './derivation-warning-tracker';\nimport { MAX_DERIVATION_ITERATIONS } from './derivation-constants';\nimport { DerivationLogger } from './derivation-logger.service';\n\n// Re-export for backwards compatibility\nexport type { DerivationProcessingResult } from './derivation-types';\n\n/**\n * Context required for applying derivations.\n *\n * @public\n */\nexport interface DerivationApplicatorContext {\n /** The current form value (signal) */\n formValue: Signal<Record<string, unknown>>;\n\n /** Root form field tree for value updates */\n rootForm: FieldTree<unknown>;\n\n /** Registered custom derivation functions */\n derivationFunctions?: Record<string, CustomFunction>;\n\n /** Custom functions for expression evaluation */\n customFunctions?: Record<string, CustomFunction>;\n\n /** Logger for diagnostic output */\n logger: Logger;\n\n /**\n * Instance-scoped warning tracker to prevent log spam.\n * If not provided, warnings will be logged every time.\n */\n warningTracker?: DerivationWarningTracker;\n\n /**\n * Derivation logger for debug output.\n * Created via `createDerivationLogger()` factory.\n */\n derivationLogger: DerivationLogger;\n\n /**\n * Maximum number of iterations for derivation chain processing.\n * Falls back to MAX_DERIVATION_ITERATIONS constant if not provided.\n */\n maxIterations?: number;\n}\n\n/**\n * Result of a single derivation application.\n *\n * @internal\n */\ninterface DerivationResult {\n /** Whether the derivation was applied */\n applied: boolean;\n\n /** The target field key */\n targetFieldKey: string;\n\n /** The computed value */\n newValue?: unknown;\n\n /** Error message if application failed */\n error?: string;\n\n /** Warning message (e.g., missing target field) - not a failure, but noteworthy */\n warning?: string;\n}\n\n/**\n * Applies all pending derivations from a collection.\n *\n * This function processes derivations in order, evaluating conditions\n * and computing values. It handles loop prevention through:\n * 1. Chain tracking (prevents same derivation from running twice in one cycle)\n * 2. Value equality checks (skips if target already has computed value)\n * 3. Max iteration limit (safety fallback)\n *\n * @param collection - The collected derivation entries\n * @param context - Context for applying derivations\n * @param changedFields - Set of field keys that changed (for filtering)\n * @returns Result of the derivation processing\n *\n * @example\n * ```typescript\n * const result = applyDerivations(collection, {\n * formValue: formValueSignal,\n * rootForm: form(),\n * derivationFunctions: customFnConfig?.derivations,\n * logger: inject(DynamicFormLogger),\n * });\n *\n * if (result.maxIterationsReached) {\n * console.warn('Possible derivation loop detected');\n * }\n * ```\n *\n * @public\n */\nexport function applyDerivations(\n collection: DerivationCollection,\n context: DerivationApplicatorContext,\n changedFields?: Set<string>,\n): DerivationProcessingResult {\n const chainContext = createDerivationChainContext();\n const { derivationLogger } = context;\n const maxIterations = context.maxIterations ?? MAX_DERIVATION_ITERATIONS;\n let appliedCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n let warnCount = 0;\n\n // Filter entries based on changed fields\n const entriesToProcess = changedFields ? getEntriesForChangedFields(collection.entries, changedFields) : collection.entries;\n\n // Log cycle start in verbose mode\n derivationLogger.cycleStart('onChange', entriesToProcess.length);\n\n // Process derivations iteratively until no more changes\n let hasChanges = true;\n\n while (hasChanges && chainContext.iteration < maxIterations) {\n chainContext.iteration++;\n hasChanges = false;\n\n // Log iteration in verbose mode\n derivationLogger.iteration(chainContext.iteration);\n\n for (const entry of entriesToProcess) {\n const result = tryApplyDerivation(entry, context, chainContext);\n\n if (result.applied) {\n appliedCount++;\n hasChanges = true;\n } else if (result.error) {\n errorCount++;\n } else if (result.warning) {\n warnCount++;\n skippedCount++;\n } else {\n skippedCount++;\n }\n }\n }\n\n // Build result\n const processingResult: DerivationProcessingResult = {\n appliedCount,\n skippedCount,\n errorCount,\n warnCount,\n iterations: chainContext.iteration,\n maxIterationsReached: chainContext.iteration >= maxIterations,\n };\n\n if (processingResult.maxIterationsReached) {\n derivationLogger.maxIterationsReached(processingResult, 'onChange');\n }\n\n // Log summary\n derivationLogger.summary(processingResult, 'onChange');\n\n return processingResult;\n}\n\n/**\n * Gets entries that should be processed based on changed fields.\n *\n * Filters entries by checking if any of their dependencies are in the changed fields set.\n * Also includes all wildcard (*) entries since they depend on any form change.\n *\n * Note: For optimal O(k) performance where k = changed fields count, use\n * DerivationLookup.getEntriesForChangedFields() which uses pre-built indexes.\n *\n * @internal\n */\nfunction getEntriesForChangedFields(entries: DerivationEntry[], changedFields: Set<string>): DerivationEntry[] {\n return entries.filter((entry) => {\n // Wildcard entries are always included\n if (entry.dependsOn.includes('*')) {\n return true;\n }\n\n // Check if any dependency is in changed fields\n return entry.dependsOn.some((dep) => changedFields.has(dep));\n });\n}\n\n/**\n * Attempts to apply a single derivation.\n *\n * **Important:** When a derivation's condition evaluates to `false`, the previously\n * derived value is NOT automatically cleared. If you need to reset a field when a\n * condition becomes false, use a separate derivation with an inverted condition\n * that sets the desired fallback value.\n *\n * @example\n * ```typescript\n * // Two derivations for conditional value with cleanup:\n * // When country is USA, set phonePrefix to '+1'\n * { condition: { field: 'country', operator: '==', value: 'USA' }, targetField: 'phonePrefix', value: '+1' }\n * // When country is NOT USA, clear phonePrefix\n * { condition: { field: 'country', operator: '!=', value: 'USA' }, targetField: 'phonePrefix', value: '' }\n * ```\n *\n * @internal\n */\nfunction tryApplyDerivation(\n entry: DerivationEntry,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): DerivationResult {\n const { derivationLogger } = context;\n\n // Check if this is an array field derivation (has '$' placeholder)\n if (isArrayPlaceholderPath(entry.targetFieldKey)) {\n return tryApplyArrayDerivation(entry, context, chainContext);\n }\n\n const derivationKey = createDerivationKey(entry.sourceFieldKey, entry.targetFieldKey);\n\n // Check if already applied in this cycle\n if (chainContext.appliedDerivations.has(derivationKey)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'skipped',\n skipReason: 'already-applied',\n });\n return { applied: false, targetFieldKey: entry.targetFieldKey };\n }\n\n // Create evaluation context\n const formValue = untracked(() => context.formValue());\n const evalContext = createEvaluationContext(entry, formValue, context);\n\n // Evaluate condition\n if (!evaluateDerivationCondition(entry.condition, evalContext)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'skipped',\n skipReason: 'condition-false',\n });\n return { applied: false, targetFieldKey: entry.targetFieldKey };\n }\n\n // Compute derived value\n let newValue: unknown;\n try {\n newValue = computeDerivedValue(entry, evalContext, context);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'compute', errorMessage));\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'error',\n error: errorMessage,\n });\n return {\n applied: false,\n targetFieldKey: entry.targetFieldKey,\n error: errorMessage,\n };\n }\n\n // Check if value actually changed using exact equality.\n // Note: This uses isEqual which performs deep comparison with exact IEEE 754\n // equality for numbers. Bidirectional derivations with floating-point math\n // may oscillate due to rounding errors. Use explicit rounding in expressions\n // or integer arithmetic to avoid this issue.\n const currentValue = getNestedValue(formValue, entry.targetFieldKey);\n if (isEqual(currentValue, newValue)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'skipped',\n skipReason: 'value-unchanged',\n });\n return { applied: false, targetFieldKey: entry.targetFieldKey };\n }\n\n // Apply the value\n try {\n const wasApplied = applyValueToForm(entry.targetFieldKey, newValue, context.rootForm, context.logger, context.warningTracker);\n\n if (wasApplied) {\n chainContext.appliedDerivations.add(derivationKey);\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'applied',\n previousValue: currentValue,\n newValue,\n });\n return { applied: true, targetFieldKey: entry.targetFieldKey, newValue };\n } else {\n // Field not found - this is a warning, not an error\n // The warning was already logged by warnMissingField\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'skipped',\n skipReason: 'target-not-found',\n });\n return {\n applied: false,\n targetFieldKey: entry.targetFieldKey,\n warning: `Target field '${entry.targetFieldKey}' not found`,\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'apply', errorMessage));\n derivationLogger.evaluation({\n debugName: entry.debugName,\n sourceFieldKey: entry.sourceFieldKey,\n targetFieldKey: entry.targetFieldKey,\n result: 'error',\n error: errorMessage,\n });\n return {\n applied: false,\n targetFieldKey: entry.targetFieldKey,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Handles array field derivations with '$' placeholder.\n *\n * Iterates over all array items and applies the derivation for each,\n * resolving '$' to the actual index and creating scoped evaluation contexts.\n *\n * @internal\n */\nfunction tryApplyArrayDerivation(\n entry: DerivationEntry,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): DerivationResult {\n const formValue = untracked(() => context.formValue());\n\n // Parse the target path using path utilities\n const pathInfo = parseArrayPath(entry.targetFieldKey);\n if (!pathInfo.isArrayPath) {\n return { applied: false, targetFieldKey: entry.targetFieldKey, error: 'Invalid array derivation path' };\n }\n\n const { arrayPath } = pathInfo;\n\n // Get the array from form values\n const arrayValue = getNestedValue(formValue, arrayPath);\n if (!Array.isArray(arrayValue)) {\n return { applied: false, targetFieldKey: entry.targetFieldKey };\n }\n\n let appliedAny = false;\n\n // Process each array item\n for (let i = 0; i < arrayValue.length; i++) {\n const resolvedTargetPath = resolveArrayPath(entry.targetFieldKey, i);\n const derivationKey = createDerivationKey(entry.sourceFieldKey, resolvedTargetPath);\n\n // Skip if already applied in this cycle\n if (chainContext.appliedDerivations.has(derivationKey)) {\n continue;\n }\n\n // Create evaluation context scoped to this array item\n const arrayItem = arrayValue[i] as Record<string, unknown>;\n const evalContext = createArrayItemEvaluationContext(entry, arrayItem, formValue, i, arrayPath, context);\n\n // Evaluate condition\n if (!evaluateDerivationCondition(entry.condition, evalContext)) {\n continue;\n }\n\n // Compute derived value\n let newValue: unknown;\n try {\n newValue = computeDerivedValue(entry, evalContext, context);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'compute', `[index ${i}] ${errorMessage}`));\n continue;\n }\n\n // Check if value actually changed\n const currentValue = getNestedValue(formValue, resolvedTargetPath);\n if (isEqual(currentValue, newValue)) {\n continue;\n }\n\n // Apply the value\n try {\n applyValueToForm(resolvedTargetPath, newValue, context.rootForm, context.logger, context.warningTracker);\n chainContext.appliedDerivations.add(derivationKey);\n appliedAny = true;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'apply', `[index ${i}] ${errorMessage}`));\n }\n }\n\n return { applied: appliedAny, targetFieldKey: entry.targetFieldKey };\n}\n\n/**\n * Creates an evaluation context for derivation processing.\n *\n * @internal\n */\nfunction createEvaluationContext(\n entry: DerivationEntry,\n formValue: Record<string, unknown>,\n context: DerivationApplicatorContext,\n): EvaluationContext {\n const fieldValue = getNestedValue(formValue, entry.sourceFieldKey);\n\n return {\n fieldValue,\n formValue,\n fieldPath: entry.sourceFieldKey,\n customFunctions: context.customFunctions,\n logger: context.logger,\n };\n}\n\n/**\n * Creates an evaluation context scoped to a specific array item.\n *\n * For array derivations, `formValue` in the expression should reference\n * the current array item's values, not the root form values.\n *\n * @internal\n */\nfunction createArrayItemEvaluationContext(\n entry: DerivationEntry,\n arrayItem: Record<string, unknown>,\n rootFormValue: Record<string, unknown>,\n itemIndex: number,\n arrayPath: string,\n context: DerivationApplicatorContext,\n): EvaluationContext {\n // For array item expressions, formValue should be the array item\n // This allows expressions like 'formValue.quantity * formValue.unitPrice'\n // to work within the context of each array item\n return {\n fieldValue: arrayItem,\n formValue: arrayItem,\n fieldPath: `${arrayPath}.${itemIndex}`,\n customFunctions: context.customFunctions,\n logger: context.logger,\n // Provide access to root form value for cross-scope references\n rootFormValue,\n arrayIndex: itemIndex,\n arrayPath,\n };\n}\n\n/**\n * Evaluates the derivation condition.\n *\n * @internal\n */\nfunction evaluateDerivationCondition(condition: ConditionalExpression | boolean, context: EvaluationContext): boolean {\n if (typeof condition === 'boolean') {\n return condition;\n }\n\n return evaluateCondition(condition, context);\n}\n\n/**\n * Computes the derived value based on the entry configuration.\n *\n * @internal\n */\nfunction computeDerivedValue(\n entry: DerivationEntry,\n evalContext: EvaluationContext,\n applicatorContext: DerivationApplicatorContext,\n): unknown {\n // Static value\n if (entry.value !== undefined) {\n return entry.value;\n }\n\n // Expression\n if (entry.expression) {\n return ExpressionParser.evaluate(entry.expression, evalContext);\n }\n\n // Custom function\n if (entry.functionName) {\n const fn = applicatorContext.derivationFunctions?.[entry.functionName];\n if (!fn) {\n throw new Error(`Derivation function '${entry.functionName}' not found in customFnConfig.derivations`);\n }\n return fn(evalContext);\n }\n\n // No value source specified\n throw new Error(`Derivation for ${entry.targetFieldKey} has no value source. ` + `Specify 'value', 'expression', or 'functionName'.`);\n}\n\n/**\n * Applies a value to the form at the specified path.\n *\n * Uses bracket notation to access child FieldTrees, following the same pattern\n * as group-field and array-field components. Fields are accessed as signals\n * and their value is set via the `.value.set()` method.\n *\n * Handles nested paths and array paths with '$' placeholder.\n *\n * @internal\n */\nfunction applyValueToForm(\n targetPath: string,\n value: unknown,\n rootForm: FieldTree<unknown>,\n logger?: Logger,\n warningTracker?: DerivationWarningTracker,\n): boolean {\n // Handle simple top-level fields\n if (!targetPath.includes('.')) {\n return setFieldValue(rootForm, targetPath, value, logger, warningTracker);\n }\n\n // Handle nested paths (e.g., 'address.city' or 'items.$.quantity')\n const parts = targetPath.split('.');\n let current: unknown = rootForm;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n\n // Handle array index placeholder '$'\n if (part === '$') {\n // This case should be resolved at collection time\n // If we still have '$', we need to skip for now\n return false;\n }\n\n // Navigate to the next level using bracket notation\n const next = (current as Record<string, unknown>)[part];\n if (next === undefined || next === null) {\n warnMissingField(targetPath, logger, warningTracker);\n return false; // Path doesn't exist\n }\n current = next;\n }\n\n // Set the final value\n const finalPart = parts[parts.length - 1];\n return setFieldValue(current, finalPart, value, logger, warningTracker);\n}\n\n/**\n * Error message prefix for derivation-related errors.\n * @internal\n */\nconst ERROR_PREFIX = '[Derivation]';\n\n/**\n * Creates a standardized error message for derivation errors.\n * @internal\n */\nfunction formatDerivationError(entry: DerivationEntry, phase: 'compute' | 'apply' | 'condition', message: string): string {\n const source = entry.expression\n ? `expression: \"${entry.expression.substring(0, 50)}${entry.expression.length > 50 ? '...' : ''}\"`\n : entry.functionName\n ? `function: \"${entry.functionName}\"`\n : entry.value !== undefined\n ? 'static value'\n : 'unknown source';\n\n return `${ERROR_PREFIX} Failed to ${phase} derivation (${entry.sourceFieldKey} → ${entry.targetFieldKey}, ${source}): ${message}`;\n}\n\n/**\n * Sets a field value using the Angular Signal Forms pattern.\n *\n * Accesses the child field via bracket notation, drills down to find\n * the WritableSignal, and uses isWritableSignal for type-safe signal detection.\n *\n * Angular Signal Forms structure:\n * - form[key] is a callable function (field accessor)\n * - form[key]() returns the field instance with { value: WritableSignal<T> }\n * - form[key]().value.set(newValue) sets the value\n *\n * @returns true if the value was successfully set, false if field not found\n *\n * @internal\n */\nfunction setFieldValue(\n parent: unknown,\n fieldKey: string,\n value: unknown,\n logger?: Logger,\n warningTracker?: DerivationWarningTracker,\n): boolean {\n // Access child field via bracket notation (same pattern as group-field/array-field)\n const fieldAccessor = (parent as Record<string, unknown>)[fieldKey];\n\n if (fieldAccessor === undefined || fieldAccessor === null) {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n\n // Angular Signal Forms: field accessor is a callable function\n if (typeof fieldAccessor !== 'function') {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n\n // Call the accessor to get the field instance\n const fieldInstance = fieldAccessor();\n\n if (!fieldInstance || typeof fieldInstance !== 'object' || !('value' in fieldInstance)) {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n\n // Get the value signal and verify it's a WritableSignal\n const valueSignal = fieldInstance.value;\n\n if (isWritableSignal(valueSignal)) {\n valueSignal.set(value);\n return true;\n } else {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n}\n\n/**\n * Logs a warning for a missing target field (once per field per form instance).\n *\n * Uses the provided warning tracker to avoid log spam. If no tracker is provided,\n * the warning will be logged every time.\n *\n * @internal\n */\nfunction warnMissingField(fieldKey: string, logger?: Logger, warningTracker?: DerivationWarningTracker): void {\n // If tracker is provided, check if we've already warned about this field\n if (warningTracker) {\n if (warningTracker.warnedFields.has(fieldKey)) {\n return;\n }\n warningTracker.warnedFields.add(fieldKey);\n }\n\n logger?.warn(\n `${ERROR_PREFIX} Target field '${fieldKey}' not found in form. ` +\n `Ensure the field is defined in your form configuration. ` +\n `This warning is shown once per field.`,\n );\n}\n\n/**\n * Processes derivations for a specific trigger type.\n *\n * Filters entries by trigger type and applies them.\n *\n * @param collection - The collected derivation entries\n * @param trigger - The trigger type to filter by\n * @param context - Context for applying derivations\n * @param changedFields - Set of field keys that changed (for filtering)\n * @returns Result of the derivation processing\n *\n * @public\n */\nexport function applyDerivationsForTrigger(\n collection: DerivationCollection,\n trigger: 'onChange' | 'debounced',\n context: DerivationApplicatorContext,\n changedFields?: Set<string>,\n): DerivationProcessingResult {\n // Filter entries by trigger type\n const filteredEntries = collection.entries.filter((entry) => {\n if (trigger === 'onChange') {\n return !entry.trigger || entry.trigger === 'onChange';\n }\n return entry.trigger === trigger;\n });\n\n // Create a minimal collection with filtered entries\n const filteredCollection: DerivationCollection = {\n entries: filteredEntries,\n };\n\n return applyDerivations(filteredCollection, context, changedFields);\n}\n\n/**\n * Gets all debounced derivation entries from a collection.\n *\n * Use this to extract debounced entries for separate processing with debounce timers.\n *\n * @param collection - The collected derivation entries\n * @returns Array of debounced derivation entries\n *\n * @public\n */\nexport function getDebouncedDerivationEntries(collection: DerivationCollection): DerivationEntry[] {\n return collection.entries.filter((entry) => entry.trigger === 'debounced');\n}\n","import { InjectionToken } from '@angular/core';\n\n/**\n * Tracks fields that have already been warned about to prevent log spam.\n * Scoped to a single form instance via DI.\n *\n * This replaces the module-level Set to avoid SSR/testing issues where\n * warnings from one form instance would suppress warnings for all others.\n *\n * @public\n */\nexport interface DerivationWarningTracker {\n /** Set of field keys we've already warned about */\n warnedFields: Set<string>;\n}\n\n/**\n * Injection token for the derivation warning tracker.\n * Provided at form component level for instance-scoped tracking.\n *\n * @public\n */\nexport const DERIVATION_WARNING_TRACKER = new InjectionToken<DerivationWarningTracker>('DerivationWarningTracker', {\n providedIn: null,\n factory: () => ({ warnedFields: new Set<string>() }),\n});\n\n/**\n * Creates a fresh warning tracker instance.\n *\n * @returns A new DerivationWarningTracker with an empty warnedFields Set\n *\n * @public\n */\nexport function createDerivationWarningTracker(): DerivationWarningTracker {\n return { warnedFields: new Set<string>() };\n}\n","import { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationLogConfig, shouldLog } from '../../models/logic/logic-config';\nimport { DerivationProcessingResult } from './derivation-types';\n\n// Re-export types from models for backwards compatibility\nexport type { DerivationLogLevel, DerivationLogConfig } from '../../models/logic/logic-config';\nexport { createDefaultDerivationLogConfig, shouldLog } from '../../models/logic/logic-config';\n\n/**\n * Information about a single derivation evaluation for logging.\n *\n * @public\n */\nexport interface DerivationLogEntry {\n /** Debug name if provided in the derivation config */\n debugName?: string;\n /** Source field key where the derivation is defined */\n sourceFieldKey: string;\n /** Target field key that will be modified */\n targetFieldKey: string;\n /** Result of the derivation evaluation */\n result: 'applied' | 'skipped' | 'error';\n /** Reason for skipping (if result is 'skipped') */\n skipReason?: 'condition-false' | 'value-unchanged' | 'already-applied' | 'target-not-found';\n /** The new value that was set (if result is 'applied') */\n newValue?: unknown;\n /** The previous value before the derivation (if result is 'applied') */\n previousValue?: unknown;\n /** Error message (if result is 'error') */\n error?: string;\n /** Duration in milliseconds (optional, for performance tracking) */\n durationMs?: number;\n}\n\n/**\n * Prefix for derivation debug log messages.\n * @internal\n */\nconst LOG_PREFIX = '[Derivation]';\n\n/**\n * Logs a summary of derivation processing results.\n *\n * Only logs when:\n * - Config level is 'summary' or 'verbose'\n * - At least one derivation was applied or an error occurred\n *\n * @param result - The derivation processing result\n * @param trigger - The trigger type ('onChange' or 'debounced')\n * @param logger - Logger instance\n * @param config - Debug logging configuration\n *\n * @public\n */\nexport function logDerivationSummary(\n result: DerivationProcessingResult,\n trigger: 'onChange' | 'debounced',\n logger: Logger,\n config: DerivationLogConfig,\n): void {\n if (!shouldLog(config, 'summary')) return;\n\n // Only log if something interesting happened\n if (result.appliedCount === 0 && result.errorCount === 0) return;\n\n logger.debug(`${LOG_PREFIX} Cycle complete (${trigger})`, {\n applied: result.appliedCount,\n skipped: result.skippedCount,\n errors: result.errorCount,\n iterations: result.iterations,\n });\n}\n\n/**\n * Logs when max iterations are reached (always logged as warning).\n *\n * @param result - The derivation processing result\n * @param trigger - The trigger type\n * @param logger - Logger instance\n *\n * @public\n */\nexport function logMaxIterationsReached(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced', logger: Logger): void {\n logger.warn(\n `${LOG_PREFIX} Processing reached max iterations (${trigger}). ` +\n `This may indicate a loop in derivation logic. ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n}\n\n/**\n * Logs a verbose entry for a single derivation evaluation.\n *\n * Only logs when config level is 'verbose'.\n *\n * @param entry - The derivation log entry with evaluation details\n * @param logger - Logger instance\n * @param config - Debug logging configuration\n *\n * @internal\n */\nexport function logDerivationEvaluation(entry: DerivationLogEntry, logger: Logger, config: DerivationLogConfig): void {\n if (!shouldLog(config, 'verbose')) return;\n\n const name = entry.debugName ? `\"${entry.debugName}\"` : `${entry.sourceFieldKey} -> ${entry.targetFieldKey}`;\n\n switch (entry.result) {\n case 'applied':\n logger.debug(`${LOG_PREFIX} -> Applied: ${name}`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n previousValue: entry.previousValue,\n newValue: entry.newValue,\n ...(entry.durationMs !== undefined && { durationMs: entry.durationMs }),\n });\n break;\n\n case 'skipped':\n logger.debug(`${LOG_PREFIX} -> Skipped: ${name} (${formatSkipReason(entry.skipReason)})`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n reason: entry.skipReason,\n });\n break;\n\n case 'error':\n logger.debug(`${LOG_PREFIX} -> Error: ${name}`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n error: entry.error,\n });\n break;\n }\n}\n\n/**\n * Formats the skip reason for human-readable output.\n *\n * @internal\n */\nfunction formatSkipReason(reason?: string): string {\n switch (reason) {\n case 'condition-false':\n return 'condition not met';\n case 'value-unchanged':\n return 'value unchanged';\n case 'already-applied':\n return 'already applied this cycle';\n default:\n return 'unknown';\n }\n}\n\n/**\n * Logs the start of a derivation processing cycle.\n *\n * Only logs when config level is 'verbose'.\n *\n * @param trigger - The trigger type ('onChange' or 'debounced')\n * @param entryCount - Number of derivations to process in this cycle\n * @param logger - Logger instance\n * @param config - Debug logging configuration\n *\n * @internal\n */\nexport function logDerivationCycleStart(\n trigger: 'onChange' | 'debounced',\n entryCount: number,\n logger: Logger,\n config: DerivationLogConfig,\n): void {\n if (!shouldLog(config, 'verbose')) return;\n\n logger.debug(`${LOG_PREFIX} Starting cycle (${trigger}) with ${entryCount} derivation(s)`);\n}\n\n/**\n * Logs the start of a derivation iteration within a cycle.\n *\n * Only logs when config level is 'verbose'.\n *\n * @param iteration - Current iteration number (1-based)\n * @param logger - Logger instance\n * @param config - Debug logging configuration\n *\n * @internal\n */\nexport function logDerivationIteration(iteration: number, logger: Logger, config: DerivationLogConfig): void {\n if (!shouldLog(config, 'verbose')) return;\n\n logger.debug(`${LOG_PREFIX} Iteration ${iteration}`);\n}\n","import { InjectionToken } from '@angular/core';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationLogConfig, createDefaultDerivationLogConfig, shouldLog } from '../../models/logic/logic-config';\nimport { DerivationProcessingResult } from './derivation-types';\nimport { DerivationLogEntry } from './derivation-logger';\n\n/**\n * Service interface for derivation logging.\n *\n * Provides methods to log derivation processing events at different verbosity levels.\n * Use `DERIVATION_LOGGER` injection token to get an instance.\n *\n * @public\n */\nexport interface DerivationLogger {\n /**\n * Logs the start of a derivation processing cycle.\n * Only logs when config level is 'verbose'.\n */\n cycleStart(trigger: 'onChange' | 'debounced', entryCount: number): void;\n\n /**\n * Logs the start of a derivation iteration within a cycle.\n * Only logs when config level is 'verbose'.\n */\n iteration(iterationNumber: number): void;\n\n /**\n * Logs a single derivation evaluation result.\n * Only logs when config level is 'verbose'.\n */\n evaluation(entry: DerivationLogEntry): void;\n\n /**\n * Logs a summary of derivation processing results.\n * Logs when config level is 'summary' or 'verbose' and something interesting happened.\n */\n summary(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void;\n\n /**\n * Logs when max iterations are reached (always logged as warning).\n */\n maxIterationsReached(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void;\n}\n\n/**\n * Active implementation of DerivationLogger that performs actual logging.\n *\n * @internal\n */\nclass ActiveDerivationLogger implements DerivationLogger {\n logger!: Logger;\n private config: DerivationLogConfig = createDefaultDerivationLogConfig();\n\n /**\n * Updates the log configuration.\n */\n setConfig(config: DerivationLogConfig): void {\n this.config = config;\n }\n\n cycleStart(trigger: 'onChange' | 'debounced', entryCount: number): void {\n if (!shouldLog(this.config, 'verbose')) return;\n this.logger.debug(`Derivation - Starting cycle (${trigger}) with ${entryCount} derivation(s)`);\n }\n\n iteration(iterationNumber: number): void {\n if (!shouldLog(this.config, 'verbose')) return;\n this.logger.debug(`Derivation - Iteration ${iterationNumber}`);\n }\n\n evaluation(entry: DerivationLogEntry): void {\n if (!shouldLog(this.config, 'verbose')) return;\n\n const name = entry.debugName ? `\"${entry.debugName}\"` : `${entry.sourceFieldKey} -> ${entry.targetFieldKey}`;\n\n switch (entry.result) {\n case 'applied':\n this.logger.debug(`Derivation - Applied ${name}`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n previousValue: entry.previousValue,\n newValue: entry.newValue,\n ...(entry.durationMs !== undefined && { durationMs: entry.durationMs }),\n });\n break;\n\n case 'skipped':\n this.logger.debug(`Derivation - Skipped ${name} (${this.formatSkipReason(entry.skipReason)})`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n reason: entry.skipReason,\n });\n break;\n\n case 'error':\n this.logger.debug(`Derivation - Error ${name}`, {\n source: entry.sourceFieldKey,\n target: entry.targetFieldKey,\n error: entry.error,\n });\n break;\n }\n }\n\n summary(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void {\n if (!shouldLog(this.config, 'summary')) return;\n\n // Only log if something interesting happened\n if (result.appliedCount === 0 && result.errorCount === 0) return;\n\n this.logger.debug(`Derivation - Cycle complete (${trigger})`, {\n applied: result.appliedCount,\n skipped: result.skippedCount,\n errors: result.errorCount,\n iterations: result.iterations,\n });\n }\n\n maxIterationsReached(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void {\n this.logger.warn(\n `Derivation - Max iterations reached (${trigger}). ` +\n `This may indicate a loop in derivation logic. ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n\n private formatSkipReason(reason?: string): string {\n switch (reason) {\n case 'condition-false':\n return 'condition not met';\n case 'value-unchanged':\n return 'value unchanged';\n case 'already-applied':\n return 'already applied this cycle';\n default:\n return 'unknown';\n }\n }\n}\n\n/**\n * No-op implementation of DerivationLogger.\n * All methods are empty - no logging overhead when disabled.\n *\n * @internal\n */\nclass NoopDerivationLogger implements DerivationLogger {\n cycleStart(): void {\n /* no-op */\n }\n iteration(): void {\n /* no-op */\n }\n evaluation(): void {\n /* no-op */\n }\n summary(): void {\n /* no-op */\n }\n maxIterationsReached(): void {\n /* no-op */\n }\n}\n\n/** Singleton no-op instance to avoid creating new objects */\nconst NOOP_INSTANCE = new NoopDerivationLogger();\n\n/**\n * Injection token for the derivation logger service.\n *\n * @public\n */\nexport const DERIVATION_LOGGER = new InjectionToken<DerivationLogger>('DerivationLogger');\n\n/**\n * Factory function to create a DerivationLogger.\n *\n * Returns a no-op implementation if config level is 'none',\n * otherwise returns an active logger with the given config.\n *\n * @param config - The derivation log configuration\n * @param logger - The underlying logger instance\n * @returns A DerivationLogger instance\n *\n * @public\n */\nexport function createDerivationLogger(config: DerivationLogConfig | undefined, logger: Logger): DerivationLogger {\n const effectiveConfig = config ?? createDefaultDerivationLogConfig();\n\n // Return no-op if logging is completely disabled\n if (effectiveConfig.level === 'none') {\n return NOOP_INSTANCE;\n }\n\n // Create active logger with config\n const service = new ActiveDerivationLogger();\n service.logger = logger;\n service.setConfig(effectiveConfig);\n\n return service;\n}\n","import { computed, DestroyRef, inject, InjectionToken, Injector, isDevMode, Signal, untracked } from '@angular/core';\nimport { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { FieldTree } from '@angular/forms/signals';\nimport {\n auditTime,\n combineLatestWith,\n debounceTime,\n exhaustMap,\n filter,\n map,\n merge,\n of,\n pairwise,\n queueScheduler,\n scheduled,\n startWith,\n switchMap,\n timer,\n} from 'rxjs';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FORM_OPTIONS } from '../../models/field-signal-context.token';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\nimport { getChangedKeys } from '../../utils/object-utils';\nimport { FunctionRegistryService } from '../registry';\nimport { applyDerivationsForTrigger } from './derivation-applicator';\nimport { collectDerivations } from './derivation-collector';\nimport { validateNoCycles } from './cycle-detector';\nimport { DerivationCollection, DerivationEntry } from './derivation-types';\nimport { DerivationLogger } from './derivation-logger.service';\nimport { DERIVATION_WARNING_TRACKER } from './derivation-warning-tracker';\n\n/**\n * Minimal configuration for creating a DerivationOrchestrator.\n * Only includes form-specific signals that cannot be injected.\n *\n * @internal\n */\nexport interface DerivationOrchestratorConfig {\n /** Signal containing the flattened schema fields */\n schemaFields: Signal<FieldDef<unknown>[] | undefined>;\n\n /** Signal containing the current form value */\n formValue: Signal<Record<string, unknown>>;\n\n /** Signal containing the form accessor */\n form: Signal<FieldTree<unknown>>;\n\n /** Signal containing the derivation logger */\n derivationLogger: Signal<DerivationLogger>;\n}\n\n/**\n * Orchestrates derivation processing for a dynamic form.\n *\n * Uses RxJS streams for reactive derivation processing:\n * - `exhaustMap` prevents re-entry during onChange derivation application\n * - `pairwise` tracks value changes without mutable state\n * - `takeUntilDestroyed` handles automatic cleanup\n *\n * Injects common services directly, requiring only form-specific signals in config.\n *\n * @public\n */\nexport class DerivationOrchestrator {\n private readonly config: DerivationOrchestratorConfig;\n private readonly injector = inject(Injector);\n private readonly destroyRef = inject(DestroyRef);\n private readonly logger = inject(DynamicFormLogger);\n private readonly warningTracker = inject(DERIVATION_WARNING_TRACKER);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly formOptions = inject(FORM_OPTIONS);\n\n /**\n * Computed signal containing the collected and validated derivations.\n * Returns null if no derivations are defined.\n */\n readonly derivationCollection: Signal<DerivationCollection | null>;\n\n constructor(config: DerivationOrchestratorConfig) {\n this.config = config;\n\n this.derivationCollection = computed<DerivationCollection | null>(() => {\n const fields = config.schemaFields();\n\n if (!fields || fields.length === 0) {\n return null;\n }\n\n const collection = collectDerivations(fields);\n\n if (collection.entries.length === 0) {\n return null;\n }\n\n validateNoCycles(collection, this.logger);\n this.warnAboutWildcardDependencies(collection.entries, fields.length);\n\n return collection;\n });\n\n this.setupOnChangeStream();\n this.setupDebouncedStream();\n }\n\n private setupOnChangeStream(): void {\n const collection$ = toObservable(this.derivationCollection, { injector: this.injector });\n const formValue$ = toObservable(this.config.formValue, { injector: this.injector });\n const form$ = toObservable(this.config.form, { injector: this.injector });\n\n collection$\n .pipe(\n filter((collection): collection is DerivationCollection => collection !== null),\n combineLatestWith(formValue$, form$),\n\n // auditTime(0): Batch synchronous emissions from Angular's change detection.\n // When a single user action triggers multiple signal updates, this ensures\n // we only process derivations once after all updates complete (microtask timing).\n auditTime(0),\n\n // exhaustMap: Prevents re-entry while processing derivations.\n // If form value changes DURING derivation processing (from our own setValue calls),\n // we ignore those emissions and complete the current cycle first.\n // switchMap would cancel mid-processing, causing incomplete derivation chains.\n exhaustMap(([collection, , formAccessor]) => {\n this.applyOnChangeDerivations(collection, formAccessor);\n\n // scheduled with queueScheduler: Ensures the observable completes\n // in the next microtask, allowing exhaustMap to accept new emissions.\n // Without this, exhaustMap would block indefinitely.\n return scheduled([null], queueScheduler);\n }),\n\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe();\n }\n\n private setupDebouncedStream(): void {\n toObservable(this.config.formValue, { injector: this.injector })\n .pipe(\n // debounceTime: Wait for value to stabilize before detecting changes.\n // Uses DEFAULT_DEBOUNCE_MS as the minimum debounce period.\n debounceTime(DEFAULT_DEBOUNCE_MS),\n\n // startWith + pairwise: Track previous and current values to detect changes.\n // startWith(null) ensures pairwise has an initial value to pair with.\n startWith(null as Record<string, unknown> | null),\n pairwise(),\n filter((pair): pair is [Record<string, unknown> | null, Record<string, unknown>] => pair[1] !== null),\n map(([previous, current]) => ({\n current,\n changedFields: getChangedKeys(previous, current),\n })),\n filter(({ changedFields }) => changedFields.size > 0),\n\n // switchMap: For debounced derivations, it's OK to cancel pending work\n // if new changes come in - we want the latest debounced values.\n // (Unlike onChange which uses exhaustMap to prevent cancellation)\n switchMap(({ changedFields }) => {\n const collection = untracked(() => this.derivationCollection());\n const formAccessor = untracked(() => this.config.form());\n\n if (!collection || !formAccessor) return of(null);\n\n // Get unique debounce periods from entries with trigger 'debounced'\n const debouncePeriods = this.getDebouncePeriods(collection.entries);\n if (debouncePeriods.length === 0) return of(null);\n\n // merge: Process multiple debounce periods concurrently.\n // Each period stream handles its own timing independently.\n const periodStreams = debouncePeriods.map((debounceMs) =>\n this.createPeriodStream(debounceMs, collection, formAccessor, changedFields),\n );\n\n return merge(...periodStreams);\n }),\n\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe();\n }\n\n private createPeriodStream(\n debounceMs: number,\n collection: DerivationCollection,\n formAccessor: FieldTree<unknown>,\n changedFields: Set<string>,\n ) {\n const additionalWait = Math.max(0, debounceMs - DEFAULT_DEBOUNCE_MS);\n\n if (additionalWait === 0) {\n return of(null).pipe(\n map(() => {\n this.applyDebouncedEntriesForPeriod(debounceMs, collection, formAccessor, changedFields);\n }),\n );\n }\n\n return timer(additionalWait).pipe(\n map(() => {\n const currentCollection = untracked(() => this.derivationCollection());\n const currentFormAccessor = untracked(() => this.config.form());\n if (currentCollection && currentFormAccessor) {\n this.applyDebouncedEntriesForPeriod(debounceMs, currentCollection, currentFormAccessor, changedFields);\n }\n }),\n );\n }\n\n private applyOnChangeDerivations(collection: DerivationCollection, formAccessor: FieldTree<unknown>): void {\n const applicatorContext = {\n formValue: this.config.formValue,\n rootForm: formAccessor,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n derivationLogger: untracked(() => this.config.derivationLogger()),\n maxIterations: untracked(() => this.formOptions()?.maxDerivationIterations),\n };\n\n const result = applyDerivationsForTrigger(collection, 'onChange', applicatorContext);\n\n if (result.maxIterationsReached) {\n this.logger.warn(\n `Derivation processing reached max iterations. ` +\n `This may indicate a loop in derivation logic that wasn't caught at build time. ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n }\n\n private applyDebouncedEntriesForPeriod(\n debounceMs: number,\n collection: DerivationCollection,\n formAccessor: FieldTree<unknown>,\n changedFields?: Set<string>,\n ): void {\n // Filter entries to just those with the specific debounce period\n const debouncedEntries = collection.entries.filter(\n (entry) => entry.trigger === 'debounced' && (entry.debounceMs ?? DEFAULT_DEBOUNCE_MS) === debounceMs,\n );\n\n if (debouncedEntries.length === 0) {\n return;\n }\n\n // Create a minimal collection with filtered entries\n const filteredCollection: DerivationCollection = {\n entries: debouncedEntries,\n };\n\n const applicatorContext = {\n formValue: this.config.formValue,\n rootForm: formAccessor,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n derivationLogger: untracked(() => this.config.derivationLogger()),\n maxIterations: untracked(() => this.formOptions()?.maxDerivationIterations),\n };\n\n const result = applyDerivationsForTrigger(filteredCollection, 'debounced', applicatorContext, changedFields);\n\n if (result.maxIterationsReached) {\n this.logger.warn(\n `Debounced derivation processing reached max iterations (${debounceMs}ms). ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n }\n\n /**\n * Gets all unique debounce periods from entries with trigger 'debounced'.\n */\n private getDebouncePeriods(entries: DerivationEntry[]): number[] {\n const periods = new Set<number>();\n for (const entry of entries) {\n if (entry.trigger === 'debounced') {\n periods.add(entry.debounceMs ?? DEFAULT_DEBOUNCE_MS);\n }\n }\n return Array.from(periods);\n }\n\n private warnAboutWildcardDependencies(entries: DerivationEntry[], fieldCount: number): void {\n if (!isDevMode()) return;\n\n // Find entries with wildcard dependency\n const wildcardEntries = entries.filter((entry) => entry.dependsOn.includes('*'));\n if (wildcardEntries.length === 0) return;\n\n // Find implicit wildcards (custom functions without explicit dependsOn)\n const implicitWildcards = wildcardEntries.filter(\n (entry) => entry.functionName && (!entry.originalConfig?.dependsOn || entry.originalConfig.dependsOn.length === 0),\n );\n\n if (implicitWildcards.length > 0) {\n const derivationDescs = implicitWildcards.map((e) => `${e.sourceFieldKey} -> ${e.targetFieldKey} (${e.functionName})`);\n\n this.logger.warn(\n '[Derivation] Derivations using custom functions without explicit dependsOn detected. ' +\n `These run on EVERY form change, which may impact performance (form has ${fieldCount} fields). ` +\n 'Consider specifying explicit dependsOn arrays for better performance.',\n derivationDescs,\n );\n }\n }\n}\n\n/**\n * Creates a DerivationOrchestrator for a dynamic form.\n * Must be called within an injection context.\n *\n * @param config - Form-specific signals configuration\n * @returns The created DerivationOrchestrator\n *\n * @public\n */\nexport function createDerivationOrchestrator(config: DerivationOrchestratorConfig): DerivationOrchestrator {\n return new DerivationOrchestrator(config);\n}\n\n/**\n * Injection token for the DerivationOrchestrator.\n *\n * @public\n */\nexport const DERIVATION_ORCHESTRATOR = new InjectionToken<DerivationOrchestrator>('DERIVATION_ORCHESTRATOR');\n\n/**\n * Injects the DerivationOrchestrator from the current injection context.\n *\n * @returns The DerivationOrchestrator instance\n * @throws Error if called outside of an injection context or if orchestrator is not provided\n *\n * @public\n */\nexport function injectDerivationOrchestrator(): DerivationOrchestrator {\n return inject(DERIVATION_ORCHESTRATOR);\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class NextPageEvent implements FormEvent {\n readonly type = 'next-page' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class PageChangeEvent implements FormEvent {\n readonly type = 'page-change' as const;\n\n constructor(\n /** The current page index (0-based) */\n public readonly currentPageIndex: number,\n /** Total number of pages */\n public readonly totalPages: number,\n /** Previous page index (0-based), undefined if first navigation */\n public readonly previousPageIndex?: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class PreviousPageEvent implements FormEvent {\n readonly type = 'previous-page' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { ArrayAllowedChildren } from '../../models/types/nesting-constraints';\n\n/**\n * Event dispatched to add a new item to an array field.\n *\n * This event is used to dynamically add items to array fields at runtime.\n * The array field component listens for this event and adds a new item\n * based on the provided field template, or uses the array's own template if not provided.\n *\n * @example\n * ```typescript\n * // Add item using array's own template\n * eventBus.dispatch(AddArrayItemEvent, 'contacts');\n *\n * // Add item with explicit field template\n * const fieldTemplate = { key: 'email', type: 'input' };\n * eventBus.dispatch(AddArrayItemEvent, 'contacts', fieldTemplate);\n *\n * // Add item at specific index\n * eventBus.dispatch(AddArrayItemEvent, 'contacts', fieldTemplate, 2);\n * ```\n */\nexport class AddArrayItemEvent implements FormEvent {\n readonly type = 'add-array-item' as const;\n\n constructor(\n /** The key of the array field to add an item to */\n public readonly arrayKey: string,\n /**\n * Optional field template definition to render for the new array item.\n * If not provided, the array field component will use its own template.\n */\n public readonly field?: ArrayAllowedChildren,\n /** Optional index where to insert the item (defaults to end of array) */\n public readonly index?: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched to remove an item from an array field.\n *\n * This event is used to dynamically remove items from array fields at runtime.\n * The array field component listens for this event and removes the item\n * at the specified index.\n *\n * @example\n * ```typescript\n * // Remove item at index 1 from 'contacts' array\n * eventBus.dispatch(RemoveArrayItemEvent, 'contacts', 1);\n *\n * // Remove last item\n * eventBus.dispatch(RemoveArrayItemEvent, 'contacts');\n * ```\n */\nexport class RemoveArrayItemEvent implements FormEvent {\n readonly type = 'remove-array-item' as const;\n\n constructor(\n /** The key of the array field to remove an item from */\n public readonly arrayKey: string,\n /** Index of the item to remove (defaults to last item) */\n public readonly index?: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched when the form should be reset to its default values.\n *\n * This event instructs the dynamic form component to restore all field values\n * to their initial default values as defined in the form configuration.\n *\n * @example\n * ```typescript\n * // Dispatch from a button component\n * eventBus.dispatch(FormResetEvent);\n * ```\n *\n * @example\n * ```typescript\n * // Listen for reset events\n * eventBus.on<FormResetEvent>('form-reset').subscribe(() => {\n * console.log('Form was reset to defaults');\n * });\n * ```\n */\nexport class FormResetEvent implements FormEvent {\n readonly type = 'form-reset' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched when the form should be cleared.\n *\n * This event instructs the dynamic form component to clear all field values,\n * resetting them to empty/undefined state regardless of their default values.\n *\n * @example\n * ```typescript\n * // Dispatch from a button component\n * eventBus.dispatch(FormClearEvent);\n * ```\n *\n * @example\n * ```typescript\n * // Listen for clear events\n * eventBus.on<FormClearEvent>('form-clear').subscribe(() => {\n * console.log('Form was cleared');\n * });\n * ```\n */\nexport class FormClearEvent implements FormEvent {\n readonly type = 'form-clear' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { PageOrchestratorState } from '../../core/page-orchestrator/page-orchestrator.interfaces';\n\nexport class PageNavigationStateChangeEvent implements FormEvent {\n type = 'page-navigation-state-change' as const;\n\n constructor(public state: PageOrchestratorState) {}\n}\n","import { ChangeDetectionStrategy, Component, computed, inject, input, linkedSignal } from '@angular/core';\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\nimport { EventBus } from '../../events/event.bus';\nimport { NextPageEvent, PageChangeEvent, PreviousPageEvent } from '../../events/constants';\nimport { NavigationResult, PageOrchestratorState } from './page-orchestrator.interfaces';\nimport { PageField, PageLogicConfig } from '../../definitions/default/page-field';\nimport { FieldSignalContext } from '../../mappers/types';\nimport PageFieldComponent from '../../fields/page/page-field.component';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { PageNavigationStateChangeEvent } from '../../events/constants/page-navigation-state-change.event';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\n\n/**\n * PageOrchestrator manages page navigation and visibility for paged forms.\n * It acts as an intermediary between the DynamicForm component and PageField components,\n * handling page state management and navigation events without interfering with form data.\n *\n * This component uses declarative rendering with @defer blocks for optimal performance,\n * ensuring that non-visible pages are lazily loaded only when needed.\n *\n * Key responsibilities:\n * - Manage current page index state\n * - Handle navigation events (next/previous)\n * - Declaratively render pages with deferred loading\n * - Emit page change events\n * - Validate navigation boundaries\n *\n * @example\n * ```html\n * <div page-orchestrator\n * [pageFields]=\"pageFields\"\n * [form]=\"form\"\n * [fieldSignalContext]=\"fieldSignalContext\"\n * [config]=\"orchestratorConfig\"\n * (pageChanged)=\"onPageChanged($event)\"\n * (navigationStateChanged)=\"onNavigationStateChanged($event)\">\n * </div>\n * ```\n */\n@Component({\n selector: 'div[page-orchestrator]',\n imports: [PageFieldComponent],\n template: `\n @for (pageField of pageFields(); track pageField.key; let i = $index) {\n @if (i === state().currentPageIndex || i === state().currentPageIndex + 1 || i === state().currentPageIndex - 1) {\n <!-- Current and adjacent pages (±1): render immediately for flicker-free navigation -->\n @defer (on immediate) {\n <section\n page-field\n [field]=\"pageField\"\n [key]=\"pageField.key\"\n [pageIndex]=\"i\"\n [isVisible]=\"i === state().currentPageIndex\"\n ></section>\n } @placeholder {\n <div class=\"df-page-placeholder\" [attr.data-page-index]=\"i\" [attr.data-page-key]=\"pageField.key\"></div>\n }\n } @else {\n <!-- Distant pages: defer until browser is idle for memory savings -->\n @defer (on idle) {\n <section page-field [field]=\"pageField\" [key]=\"pageField.key\" [pageIndex]=\"i\" [isVisible]=\"false\"></section>\n } @placeholder {\n <div class=\"df-page-placeholder\" [attr.data-page-index]=\"i\" [attr.data-page-key]=\"pageField.key\"></div>\n }\n }\n }\n `,\n styleUrl: './page-orchestrator.component.scss',\n host: {\n class: 'df-page-orchestrator',\n '[attr.data-current-page]': 'state().currentPageIndex',\n '[attr.data-total-pages]': 'state().totalPages',\n },\n providers: [\n {\n provide: FIELD_SIGNAL_CONTEXT,\n useFactory: (orchestrator: PageOrchestratorComponent) => orchestrator.extendedFieldSignalContext(),\n deps: [PageOrchestratorComponent],\n },\n ],\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class PageOrchestratorComponent {\n private readonly eventBus = inject(EventBus);\n private readonly fieldContextRegistry = inject(FieldContextRegistryService);\n private readonly functionRegistry = inject(FunctionRegistryService);\n\n /**\n * Array of page field definitions to render\n */\n pageFields = input.required<PageField[]>();\n\n /**\n * Root form instance from parent DynamicForm.\n * Uses FieldTree<unknown> to accept any form type.\n */\n form = input.required<FieldTree<unknown>>();\n\n /**\n * Field signal context for child fields\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FieldSignalContext is contravariant in TModel, using any allows accepting any form type\n fieldSignalContext = input.required<FieldSignalContext<any>>();\n\n /**\n * Computed signal that tracks which pages are hidden.\n * Returns an array of booleans where true means the page is hidden.\n * This signal is reactive and will re-evaluate when form values change.\n */\n readonly pageHiddenStates = computed(() => {\n const pages = this.pageFields();\n\n return pages.map((page) => this.evaluatePageHidden(page));\n });\n\n /**\n * Computed signal that returns indices of visible (non-hidden) pages.\n * This is used for navigation to skip hidden pages.\n */\n readonly visiblePageIndices = computed(() => {\n const hiddenStates = this.pageHiddenStates();\n return hiddenStates\n .map((hidden, index) => ({ index, hidden }))\n .filter((item) => !item.hidden)\n .map((item) => item.index);\n });\n\n /**\n * Internal signal for current page index that tracks with page fields.\n * This tracks the actual page index, not the visible page index.\n *\n * Note: We only track pageFields().length to handle page additions/removals.\n * The hidden state changes should NOT reset the current page index -\n * that would cause unwanted navigation when form values change.\n */\n private readonly currentPageIndex = linkedSignal(() => {\n const totalPages = this.pageFields().length;\n\n if (totalPages === 0) return 0;\n\n // Start on page 0 (will be adjusted if page 0 is hidden by initial navigation)\n return 0;\n });\n\n /**\n * Computed state for the orchestrator\n */\n readonly state = computed<PageOrchestratorState>(() => {\n const currentIndex = this.currentPageIndex();\n const totalPages = this.pageFields().length;\n const visibleIndices = this.visiblePageIndices();\n\n // Find where the current index is in the visible pages list\n const currentVisiblePosition = visibleIndices.indexOf(currentIndex);\n const isFirstVisiblePage = currentVisiblePosition === 0 || currentVisiblePosition === -1;\n const isLastVisiblePage = currentVisiblePosition >= visibleIndices.length - 1;\n\n return {\n currentPageIndex: currentIndex,\n totalPages,\n isFirstPage: isFirstVisiblePage,\n isLastPage: isLastVisiblePage,\n navigationDisabled: false,\n };\n });\n\n /**\n * Signal indicating whether all fields on the current page are valid.\n *\n * This is used by next page buttons to determine their disabled state.\n * Returns `true` if all fields on the current page pass validation,\n * `false` otherwise.\n *\n * @returns `true` if current page is valid, `false` otherwise\n */\n readonly currentPageValid = computed(() => {\n const currentIndex = this.currentPageIndex();\n const pages = this.pageFields();\n const form = this.form();\n\n // No pages or invalid index\n if (pages.length === 0 || currentIndex >= pages.length) {\n return true;\n }\n\n const currentPage = pages[currentIndex];\n const pageFields = currentPage.fields || [];\n\n // Check validity of each field on the current page\n // Fields are stored at root level in the form (pages don't add nesting)\n for (const fieldDef of pageFields) {\n const fieldKey = fieldDef.key;\n if (!fieldKey) continue;\n\n // Access the field from the form using bracket notation\n const field = (form as Record<string, unknown>)[fieldKey];\n if (field && typeof field === 'function') {\n const fieldState = (field as () => { valid: () => boolean })();\n if (fieldState && typeof fieldState.valid === 'function' && !fieldState.valid()) {\n return false;\n }\n }\n }\n\n return true;\n });\n\n /**\n * Extended field signal context that includes currentPageValid.\n *\n * This extends the parent context from DynamicForm with page-specific\n * information needed by button mappers (e.g., next button needs to know\n * if the current page is valid).\n */\n readonly extendedFieldSignalContext = computed(() => ({\n ...this.fieldSignalContext(),\n currentPageValid: this.currentPageValid,\n }));\n\n constructor() {\n // Setup event listeners for navigation\n this.setupEventListeners();\n }\n\n /**\n * Navigate to the next visible page, skipping hidden pages.\n * @returns Navigation result\n */\n navigateToNextPage(): NavigationResult {\n const currentState = this.state();\n const visibleIndices = this.visiblePageIndices();\n\n if (currentState.isLastPage) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Already on the last visible page',\n };\n }\n\n if (currentState.navigationDisabled) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Navigation is currently disabled',\n };\n }\n\n // Find the next visible page after the current index\n const currentVisiblePosition = visibleIndices.indexOf(currentState.currentPageIndex);\n if (currentVisiblePosition === -1 || currentVisiblePosition >= visibleIndices.length - 1) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'No next visible page available',\n };\n }\n\n const nextVisiblePageIndex = visibleIndices[currentVisiblePosition + 1];\n return this.navigateToPage(nextVisiblePageIndex);\n }\n\n /**\n * Navigate to the previous visible page, skipping hidden pages.\n * @returns Navigation result\n */\n navigateToPreviousPage(): NavigationResult {\n const currentState = this.state();\n const visibleIndices = this.visiblePageIndices();\n\n if (currentState.isFirstPage) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Already on the first visible page',\n };\n }\n\n if (currentState.navigationDisabled) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Navigation is currently disabled',\n };\n }\n\n // Find the previous visible page before the current index\n const currentVisiblePosition = visibleIndices.indexOf(currentState.currentPageIndex);\n if (currentVisiblePosition <= 0) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'No previous visible page available',\n };\n }\n\n const prevVisiblePageIndex = visibleIndices[currentVisiblePosition - 1];\n return this.navigateToPage(prevVisiblePageIndex);\n }\n\n /**\n * Navigate to a specific page index\n * @param pageIndex The target page index (0-based)\n * @returns Navigation result\n */\n navigateToPage(pageIndex: number): NavigationResult {\n const currentState = this.state();\n const totalPages = currentState.totalPages;\n\n // Validate page index\n if (pageIndex < 0 || pageIndex >= totalPages) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: `Invalid page index: ${pageIndex}. Valid range is 0 to ${totalPages - 1}`,\n };\n }\n\n // Check if already on target page\n if (pageIndex === currentState.currentPageIndex) {\n return {\n success: true,\n newPageIndex: pageIndex,\n };\n }\n\n // Perform navigation\n const previousIndex = currentState.currentPageIndex;\n this.currentPageIndex.set(pageIndex);\n\n // Emit page change event\n this.eventBus.dispatch(PageChangeEvent, pageIndex, totalPages, previousIndex);\n\n return {\n success: true,\n newPageIndex: pageIndex,\n };\n }\n\n /**\n * Set up event listeners for navigation events\n */\n private setupEventListeners(): void {\n // Listen for next page events\n this.eventBus\n .on<NextPageEvent>('next-page')\n .pipe(takeUntilDestroyed())\n .subscribe(() => {\n this.navigateToNextPage();\n });\n\n // Listen for previous page events\n this.eventBus\n .on<PreviousPageEvent>('previous-page')\n .pipe(takeUntilDestroyed())\n .subscribe(() => {\n this.navigateToPreviousPage();\n });\n\n explicitEffect([this.state], ([state]) => this.eventBus.dispatch(PageNavigationStateChangeEvent, state));\n }\n\n /**\n * Evaluates whether a page should be hidden based on its logic configuration.\n * A page is hidden if ANY of its hidden logic conditions evaluate to true.\n *\n * @param page The page field to evaluate\n * @returns true if the page should be hidden, false otherwise\n */\n private evaluatePageHidden(page: PageField): boolean {\n // If no logic defined, page is visible\n if (!page.logic || page.logic.length === 0) {\n return false;\n }\n\n // Filter to only hidden logic (pages only support hidden type)\n const hiddenLogic = page.logic.filter((l): l is PageLogicConfig => l.type === 'hidden');\n\n // If no hidden logic, page is visible\n if (hiddenLogic.length === 0) {\n return false;\n }\n\n // Check each hidden logic - if ANY condition is true, the page is hidden\n for (const logic of hiddenLogic) {\n // Handle static boolean conditions (fast path)\n if (typeof logic.condition === 'boolean') {\n if (logic.condition) {\n return true;\n }\n continue;\n }\n\n // Evaluate conditional expression using centralized context creation\n const condition = logic.condition as ConditionalExpression;\n const context = this.fieldContextRegistry.createDisplayOnlyContext(page.key || '', this.functionRegistry.getCustomFunctions());\n\n if (evaluateCondition(condition, context)) {\n return true;\n }\n }\n\n return false;\n }\n}\n","import { Provider } from '@angular/core';\n\n/**\n * Base interface for dynamic form features.\n * Features are configuration options that can be passed to provideDynamicForm\n * alongside field type definitions.\n *\n * Uses Angular-style internal marker (ɵkind) to distinguish from field types.\n */\nexport interface DynamicFormFeature<TKind extends string = string> {\n /** Internal marker to identify this as a feature, not a field type */\n ɵkind: TKind;\n /** Providers to register for this feature */\n ɵproviders: Provider[];\n}\n\n/**\n * Known feature kinds for type safety\n */\nexport type DynamicFormFeatureKind = 'logger';\n\n/**\n * Type guard to check if a value is a DynamicFormFeature\n */\nexport function isDynamicFormFeature(value: unknown): value is DynamicFormFeature {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'ɵkind' in value &&\n typeof (value as DynamicFormFeature).ɵkind === 'string' &&\n 'ɵproviders' in value &&\n Array.isArray((value as DynamicFormFeature).ɵproviders)\n );\n}\n\n/**\n * Helper to create a feature with proper typing\n */\nexport function createFeature<TKind extends DynamicFormFeatureKind>(kind: TKind, providers: Provider[]): DynamicFormFeature<TKind> {\n return {\n ɵkind: kind,\n ɵproviders: providers,\n };\n}\n","import type { Logger } from './logger.interface';\n\n/**\n * Console-based logger implementation.\n */\nexport class ConsoleLogger implements Logger {\n private readonly prefix = '[Dynamic Forms]';\n\n debug(message: string, ...args: unknown[]): void {\n console.debug(this.prefix, message, ...args);\n }\n\n info(message: string, ...args: unknown[]): void {\n console.info(this.prefix, message, ...args);\n }\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(this.prefix, message, ...args);\n }\n\n error(message: string, ...args: unknown[]): void {\n console.error(this.prefix, message, ...args);\n }\n}\n","import type { Logger } from './logger.interface';\n\n/**\n * No-operation logger implementation.\n * All methods are no-ops - used in production by default.\n */\nexport class NoopLogger implements Logger {\n debug(): void {\n // Intentionally empty\n }\n\n info(): void {\n // Intentionally empty\n }\n\n warn(): void {\n // Intentionally empty\n }\n\n error(): void {\n // Intentionally empty\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport { createFeature, DynamicFormFeature } from '../dynamic-form-feature';\nimport { DynamicFormLogger } from './logger.token';\nimport { ConsoleLogger } from './console-logger';\nimport { NoopLogger } from './noop-logger';\nimport { DerivationLogConfig, DerivationLogLevel, createDefaultDerivationLogConfig } from '../../../models/logic/logic-config';\n\n/**\n * Injection token for derivation logging configuration.\n *\n * @internal\n */\nexport const DERIVATION_LOG_CONFIG = new InjectionToken<DerivationLogConfig>('DERIVATION_LOG_CONFIG', {\n providedIn: 'root',\n factory: createDefaultDerivationLogConfig,\n});\n\n/**\n * Configuration options for the logger feature.\n *\n * @public\n */\nexport interface LoggerConfigOptions {\n /**\n * Whether general logging is enabled.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Derivation logging level.\n *\n * - `'none'`: No derivation debug logging (default)\n * - `'summary'`: Log cycle completion with counts\n * - `'verbose'`: Log individual derivation evaluations with details\n *\n * @default 'none'\n */\n derivations?: DerivationLogLevel;\n}\n\n/**\n * Configure logging for dynamic forms.\n *\n * By default, general logging is enabled (ConsoleLogger) and derivation\n * logging is disabled ('none'). Use this feature to enable derivation debugging.\n *\n * @example\n * ```typescript\n * // Disable all logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(false)\n * )\n *\n * // Enable verbose derivation logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig({ derivations: 'verbose' })\n * )\n *\n * // Disable derivation logging but keep general logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig({ derivations: 'none' })\n * )\n *\n * // Conditional logging (e.g., only in dev mode)\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(() => isDevMode())\n * )\n * ```\n *\n * @param config - Boolean to enable/disable logging, a function returning boolean, or a config object\n * @returns A DynamicFormFeature that configures logging\n *\n * @public\n */\nexport function withLoggerConfig(config: boolean | (() => boolean) | LoggerConfigOptions = true): DynamicFormFeature<'logger'> {\n // Handle boolean or function\n if (typeof config === 'boolean' || typeof config === 'function') {\n const isEnabled = typeof config === 'function' ? config() : config;\n const logger = isEnabled ? new ConsoleLogger() : new NoopLogger();\n return createFeature('logger', [{ provide: DynamicFormLogger, useValue: logger }]);\n }\n\n // Handle config object\n const isEnabled = config.enabled !== false;\n const logger = isEnabled ? new ConsoleLogger() : new NoopLogger();\n\n const providers: { provide: InjectionToken<unknown>; useValue: unknown }[] = [{ provide: DynamicFormLogger, useValue: logger }];\n\n // Add derivation log config if specified\n if (config.derivations !== undefined) {\n providers.push({\n provide: DERIVATION_LOG_CONFIG,\n useValue: { level: config.derivations },\n });\n }\n\n return createFeature('logger', providers);\n}\n","import {\n afterNextRender,\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n inject,\n Injector,\n input,\n InputSignal,\n linkedSignal,\n model,\n OnDestroy,\n runInInjectionContext,\n signal,\n Signal,\n untracked,\n} from '@angular/core';\nimport { NgComponentOutlet } from '@angular/common';\nimport { form, FieldTree, Schema } from '@angular/forms/signals';\nimport { outputFromObservable, takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { EMPTY, forkJoin, map, of, pipe, scan, switchMap } from 'rxjs';\nimport { derivedFromDeferred } from './utils/derived-from-deferred/derived-from-deferred';\nimport { reconcileFields, ResolvedField, resolveField } from './utils/resolve-field/resolve-field';\nimport { createSubmissionHandler } from './utils/submission-handler/submission-handler';\nimport { keyBy, memoize, isEqual } from './utils/object-utils';\nimport { DEFAULT_PROPS, DEFAULT_VALIDATION_MESSAGES, FIELD_SIGNAL_CONTEXT, FORM_OPTIONS } from './models/field-signal-context.token';\nimport { FieldTypeDefinition } from './models/field-type';\nimport { FormConfig, FormOptions } from './models/form-config';\nimport { RegisteredFieldTypes } from './models/registry/field-registry';\nimport { injectFieldRegistry } from './utils/inject-field-registry/inject-field-registry';\nimport { createSchemaFromFields } from './core/schema-builder';\nimport { createFormLevelSchema } from './core/form-schema-merger';\nimport { EventBus } from './events/event.bus';\nimport { SubmitEvent } from './events/constants/submit.event';\nimport { ComponentInitializedEvent } from './events/constants/component-initialized.event';\nimport { setupInitializationTracking } from './utils/initialization-tracker/initialization-tracker';\nimport { FormMode, InferFormValue, isContainerField } from './models/types';\nimport { flattenFields } from './utils/flattener/field-flattener';\nimport { FieldDef } from './definitions/base/field-def';\nimport { isPageField, PageField } from './definitions/default/page-field';\nimport { getFieldDefaultValue } from './utils/default-value/default-value';\nimport { FieldSignalContext } from './mappers/types';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { FieldContextRegistryService, FunctionRegistryService, RootFormRegistryService, SchemaRegistryService } from './core/registry';\nimport { detectFormMode, FormModeDetectionResult } from './models/types/form-mode';\nimport { collectCrossFieldEntries } from './core/cross-field/cross-field-collector';\nimport { FormModeValidator } from './utils/form-validation/form-mode-validator';\nimport {\n DERIVATION_WARNING_TRACKER,\n DERIVATION_ORCHESTRATOR,\n createDerivationWarningTracker,\n createDerivationOrchestrator,\n createDerivationLogger,\n DerivationLogger,\n DerivationOrchestratorConfig,\n} from './core/derivation';\nimport { PageOrchestratorComponent } from './core/page-orchestrator';\nimport { FormClearEvent } from './events/constants/form-clear.event';\nimport { FormResetEvent } from './events/constants/form-reset.event';\nimport { PageChangeEvent } from './events/constants/page-change.event';\nimport { PageNavigationStateChangeEvent } from './events/constants/page-navigation-state-change.event';\nimport { DynamicFormLogger } from './providers/features/logger/logger.token';\nimport { DERIVATION_LOG_CONFIG } from './providers/features/logger/with-logger-config';\n\nfunction derivationOrchestratorFactoryWrapper(dynamicForm: DynamicForm) {\n return createDerivationOrchestrator(dynamicForm.derivationOrchestratorConfig);\n}\n\n/**\n * Dynamic form component that renders a complete form based on configuration.\n *\n * This is the main entry point for the dynamic form system. It handles form state management,\n * validation, field rendering, and event coordination using Angular's signal-based reactive forms.\n *\n * @typeParam TFields - Array of registered field types available for this form\n * @typeParam TModel - The strongly-typed interface for form values\n *\n * @example\n *```html\n * <form\n * [dynamic-form]=\"formConfig\"\n * [(value)]=\"formData\"\n * (submitted)=\"handleSubmit($event)\"\n * (validityChange)=\"handleValidityChange($event)\">\n * </form>\n * ```\n */\n@Component({\n selector: 'form[dynamic-form]',\n imports: [NgComponentOutlet, PageOrchestratorComponent],\n template: `\n @if (formModeDetection().mode === 'paged') {\n <div page-orchestrator [pageFields]=\"pageFieldDefinitions()\" [form]=\"form()\" [fieldSignalContext]=\"fieldSignalContext()\"></div>\n } @else {\n @for (field of resolvedFields(); track field.key) {\n <ng-container *ngComponentOutlet=\"field.component; injector: field.injector; inputs: field.inputs()\" />\n }\n }\n `,\n styleUrl: './dynamic-form.component.scss',\n providers: [\n EventBus,\n SchemaRegistryService,\n FunctionRegistryService,\n RootFormRegistryService,\n FieldContextRegistryService,\n // Form-level config tokens provided via useFactory to enable reactive updates\n {\n provide: DEFAULT_PROPS,\n useFactory: (form: DynamicForm) => computed(() => form.config().defaultProps),\n deps: [DynamicForm],\n },\n {\n provide: DEFAULT_VALIDATION_MESSAGES,\n useFactory: (form: DynamicForm) => computed(() => form.config().defaultValidationMessages),\n deps: [DynamicForm],\n },\n {\n provide: FORM_OPTIONS,\n useFactory: (form: DynamicForm) => form.effectiveFormOptions,\n deps: [DynamicForm],\n },\n { provide: DERIVATION_WARNING_TRACKER, useFactory: createDerivationWarningTracker },\n {\n provide: DERIVATION_ORCHESTRATOR,\n useFactory: derivationOrchestratorFactoryWrapper,\n deps: [DynamicForm],\n },\n ],\n host: {\n class: 'df-dynamic-form df-form',\n novalidate: '', // Disable browser validation - Angular Signal Forms handles validation\n '[class.disabled]': 'disabled()',\n '[class.df-form-paged]': 'formModeDetection().mode === \"paged\"',\n '[class.df-form-non-paged]': 'formModeDetection().mode === \"non-paged\"',\n '[attr.data-form-mode]': 'formModeDetection().mode',\n '(submit)': 'onNativeSubmit($event)',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class DynamicForm<\n TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[],\n TModel extends Record<string, unknown> = InferFormValue<TFields> & Record<string, unknown>,\n> implements OnDestroy {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly injector = inject(Injector);\n private readonly eventBus = inject(EventBus);\n private readonly rootFormRegistry = inject(RootFormRegistryService);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly schemaRegistry = inject(SchemaRegistryService);\n private readonly logger = inject(DynamicFormLogger);\n private readonly derivationLogConfig = inject(DERIVATION_LOG_CONFIG);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Form configuration defining the structure, validation, and behavior. */\n config: InputSignal<FormConfig<TFields>> = input.required<FormConfig<TFields>>({ alias: 'dynamic-form' });\n\n /** Runtime form options that override config options when provided. */\n formOptions = input<FormOptions | undefined>(undefined);\n\n /** Form values for two-way data binding. */\n value = model<Partial<TModel> | undefined>(undefined);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Memoized Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly memoizedFlattenFields = memoize(\n (fields: FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) => flattenFields(fields, registry),\n {\n resolver: (fields, registry) => {\n const fieldKeys = fields.map((f) => `${f.key || ''}:${f.type}`).join('|');\n const registryKeys = Array.from(registry.keys()).sort().join('|');\n return `${fieldKeys}__${registryKeys}`;\n },\n maxSize: 10,\n },\n );\n\n private readonly memoizedFlattenFieldsForRendering = memoize(\n (fields: FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) => flattenFields(fields, registry, { preserveRows: true }),\n {\n resolver: (fields, registry) => {\n const fieldKeys = fields.map((f) => `${f.key || ''}:${f.type}`).join('|');\n const registryKeys = Array.from(registry.keys()).sort().join('|');\n return `render_${fieldKeys}__${registryKeys}`;\n },\n maxSize: 10,\n },\n );\n\n private readonly memoizedKeyBy = memoize(<T extends { key: string }>(fields: T[]) => keyBy(fields, 'key'), {\n resolver: (fields) => fields.map((f) => f.key).join('|'),\n maxSize: 10,\n });\n\n private readonly memoizedDefaultValues = memoize(\n <T extends FieldDef<unknown>>(fieldsById: Record<string, T>, registry: Map<string, FieldTypeDefinition>) => {\n const result: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(fieldsById)) {\n const value = getFieldDefaultValue(field, registry);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result as TModel;\n },\n {\n resolver: (fieldsById, registry) => {\n const fieldKeys = Object.keys(fieldsById).sort().join('|');\n const registryKeys = Array.from(registry.keys()).sort().join('|');\n return `defaults_${fieldKeys}__${registryKeys}`;\n },\n maxSize: 10,\n },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n readonly formModeDetection = computed<FormModeDetectionResult>(() => {\n const config = this.config();\n const fields = config.fields || [];\n const detection = detectFormMode(fields);\n const validation = FormModeValidator.validateFormConfiguration(fields);\n\n if (!validation.isValid) {\n this.logger.error('Invalid form configuration:', validation.errors);\n }\n\n if (validation.warnings.length > 0) {\n this.logger.warn('Form configuration warnings:', validation.warnings);\n }\n\n return detection;\n });\n\n private readonly formSetup = computed(() => {\n const config = this.config();\n const modeDetection = this.formModeDetection();\n const registry = this.rawFieldRegistry();\n\n this.registerValidatorsFromConfig(config);\n\n if (config.fields && config.fields.length > 0) {\n return this.createFormSetupFromConfig(config.fields, modeDetection.mode, registry);\n }\n\n return this.createEmptyFormSetup(registry);\n });\n\n readonly pageFieldDefinitions = computed(() => {\n const config = this.config();\n const mode = this.formModeDetection().mode;\n\n if (mode === 'paged' && config.fields) {\n return config.fields.filter(isPageField);\n }\n\n return [] as PageField[];\n });\n\n readonly effectiveFormOptions = computed(() => {\n const config = this.config();\n const configOptions = config.options || {};\n const inputOptions = this.formOptions();\n return { ...configOptions, ...inputOptions };\n });\n\n /**\n * Computed derivation logger based on injected config.\n *\n * Uses factory pattern to return no-op logger when logging is disabled,\n * avoiding any logging overhead in production.\n */\n private readonly derivationLogger = computed<DerivationLogger>(() => {\n return createDerivationLogger(this.derivationLogConfig, this.logger);\n });\n\n readonly fieldSignalContext = computed<FieldSignalContext<TModel>>(() => ({\n injector: this.injector,\n value: this.value,\n defaultValues: this.defaultValues,\n form: this.form(),\n }));\n\n /**\n * Injector for field components with FIELD_SIGNAL_CONTEXT.\n * Other form-level tokens (DEFAULT_PROPS, etc.) are provided at component level.\n */\n private readonly fieldInjector = computed(() =>\n Injector.create({\n parent: this.injector,\n providers: [{ provide: FIELD_SIGNAL_CONTEXT, useValue: this.fieldSignalContext() }],\n }),\n );\n\n readonly defaultValues = linkedSignal(() => this.formSetup().defaultValues);\n\n private readonly entity = linkedSignal(() => {\n const inputValue = this.value();\n const defaults = this.defaultValues();\n const setup = this.formSetup();\n\n const combined = { ...defaults, ...inputValue };\n\n if (setup.schemaFields && setup.schemaFields.length > 0) {\n const validKeys = new Set(setup.schemaFields.map((field) => field.key).filter((key: string | undefined) => key !== undefined));\n const filtered: Record<string, unknown> = {};\n for (const key of Object.keys(combined)) {\n if (validKeys.has(key)) {\n filtered[key] = (combined as Record<string, unknown>)[key];\n }\n }\n return filtered as TModel;\n }\n\n return combined as TModel;\n });\n\n readonly form = computed<ReturnType<typeof form<TModel>>>(() => {\n return runInInjectionContext(this.injector, () => {\n const setup = this.formSetup();\n const config = this.config();\n let formInstance: ReturnType<typeof form<TModel>>;\n\n untracked(() => this.rootFormRegistry.registerFormValueSignal(this.entity as Signal<Record<string, unknown>>));\n\n const hasFields = setup.schemaFields && setup.schemaFields.length > 0;\n const hasFormSchema = config.schema !== undefined;\n\n if (hasFields) {\n const crossFieldCollection = collectCrossFieldEntries(setup.schemaFields as FieldDef<unknown>[]);\n\n // Create schema with both field-level and form-level validation\n // Type assertion needed due to complex generic type inference between TModel and InferFormValue\n const combinedSchema = createSchemaFromFields(setup.schemaFields, setup.registry, {\n crossFieldValidators: crossFieldCollection.validators,\n formLevelSchema: config.schema,\n }) as Schema<TModel>;\n\n formInstance = untracked(() => form(this.entity, combinedSchema));\n } else if (hasFormSchema) {\n // Only form-level schema (no fields with validation)\n // Non-null assertion safe: hasFormSchema guarantees config.schema is defined\n // Type assertion needed due to generic type inference\n const formSchema = createFormLevelSchema(config.schema!) as Schema<TModel>;\n formInstance = untracked(() => form(this.entity, formSchema));\n } else {\n formInstance = untracked(() => form(this.entity));\n }\n\n untracked(() => this.rootFormRegistry.registerRootForm(formInstance));\n\n return formInstance;\n });\n });\n\n private readonly componentId = 'dynamic-form';\n\n private readonly totalComponentsCount = computed(() => {\n const fields = this.formSetup().fields;\n if (!fields) {\n return 1;\n }\n\n const registry = this.rawFieldRegistry();\n const flatFields = flattenFields(fields, registry);\n const componentCount = flatFields.filter(isContainerField).length;\n\n return componentCount + 1;\n });\n\n private readonly fieldsSource = computed(() => this.formSetup().fields);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Collects errors from async field component loading for error boundary patterns. */\n readonly fieldLoadingErrors = signal<Array<{ fieldType: string; fieldKey: string; error: Error }>>([]);\n\n /** Current form values (reactive). */\n readonly formValue = computed(() => this.form()().value());\n\n /** Whether the form is currently valid. */\n readonly valid = computed(() => this.form()().valid());\n\n /** Whether the form is currently invalid. */\n readonly invalid = computed(() => this.form()().invalid());\n\n /** Whether any form field has been modified. */\n readonly dirty = computed(() => this.form()().dirty());\n\n /** Whether any form field has been touched (blurred). */\n readonly touched = computed(() => this.form()().touched());\n\n /** Current validation errors from all fields. */\n readonly errors = computed(() => this.form()().errors());\n\n /** Whether the form is disabled (from options or form state). */\n readonly disabled = computed(() => {\n const optionsDisabled = this.effectiveFormOptions().disabled;\n const formDisabled = this.form()().disabled();\n return optionsDisabled ?? formDisabled;\n });\n\n /** Whether the form is currently submitting. */\n readonly submitting = computed(() => this.form()().submitting());\n\n /**\n * Configuration for the derivation orchestrator.\n * Bundles the form-specific signals needed by the orchestrator.\n *\n * @internal Used by DERIVATION_ORCHESTRATOR provider.\n */\n readonly derivationOrchestratorConfig: DerivationOrchestratorConfig = {\n schemaFields: computed(() => this.formSetup().schemaFields as FieldDef<unknown>[] | undefined),\n formValue: this.formValue as Signal<Record<string, unknown>>,\n form: computed(() => this.form() as unknown as FieldTree<unknown>),\n derivationLogger: this.derivationLogger,\n };\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Initialization\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly initialized$ = setupInitializationTracking({\n eventBus: this.eventBus,\n totalComponentsCount: this.totalComponentsCount,\n injector: this.injector,\n componentId: this.componentId,\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Outputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Emits when form validity changes. */\n readonly validityChange = outputFromObservable(toObservable(this.valid));\n\n /** Emits when form dirty state changes. */\n readonly dirtyChange = outputFromObservable(toObservable(this.dirty));\n\n /**\n * Emits form values when submitted (via SubmitEvent).\n * Note: Does not emit when `submission.action` is configured - use one or the other.\n */\n readonly submitted = outputFromObservable(\n this.eventBus.on<SubmitEvent>('submit').pipe(\n switchMap(() => {\n const submissionConfig = this.config().submission;\n\n if (submissionConfig?.action) {\n this.logger.warn(\n 'Both `submission.action` and `(submitted)` output are configured. ' +\n 'When using `submission.action`, the `(submitted)` output will not emit. ' +\n 'Use either `submission.action` OR `(submitted)`, not both.',\n );\n return EMPTY;\n }\n\n return of(this.value());\n }),\n ),\n );\n\n /** Emits when form is reset to default values. */\n readonly reset = outputFromObservable(this.eventBus.on<FormResetEvent>('form-reset'));\n\n /** Emits when form is cleared to empty state. */\n readonly cleared = outputFromObservable(this.eventBus.on<FormClearEvent>('form-clear'));\n\n /** Emits all form events for custom event handling. */\n readonly events = outputFromObservable(this.eventBus.events$);\n\n /**\n * Emits when all form components are initialized and ready for interaction.\n * Useful for E2E testing to ensure the form is fully rendered before interaction.\n */\n readonly initialized = outputFromObservable(this.initialized$);\n\n /** Emits when the current page changes in paged forms. */\n readonly onPageChange = outputFromObservable(this.eventBus.on<PageChangeEvent>('page-change'));\n\n /** Emits when page navigation state changes (canGoNext, canGoPrevious, etc.). */\n readonly onPageNavigationStateChange = outputFromObservable(\n this.eventBus.on<PageNavigationStateChangeEvent>('page-navigation-state-change'),\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Field Resolution\n // ─────────────────────────────────────────────────────────────────────────────\n\n protected readonly resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n pipe(\n switchMap((fields) => {\n if (!fields || fields.length === 0) {\n return of([] as (ResolvedField | undefined)[]);\n }\n const context = {\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry: this.rawFieldRegistry(),\n injector: this.fieldInjector(),\n destroyRef: this.destroyRef,\n onError: (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n this.fieldLoadingErrors.update((errors) => [\n ...errors,\n {\n fieldType: fieldDef.type,\n fieldKey,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n ]);\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}). ` +\n `Ensure the field type is registered in your field registry.`,\n error,\n );\n },\n };\n return forkJoin(fields.map((f) => resolveField(f, context)));\n }),\n map((fields) => fields.filter((f): f is ResolvedField => f !== undefined)),\n scan(reconcileFields, [] as ResolvedField[]),\n ),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n this.setupEventHandlers();\n\n // Lazily inject the derivation orchestrator to avoid circular dependency.\n // The orchestrator's constructor sets up RxJS subscriptions that process derivations.\n afterNextRender(() => {\n this.injector.get(DERIVATION_ORCHESTRATOR);\n });\n }\n\n /**\n * Handles native form submission triggered by:\n * - Pressing Enter in an input field\n * - Clicking a button with type=\"submit\"\n * - Programmatic form.submit() calls\n *\n * This method prevents the default form submission behavior (page reload)\n * and dispatches a SubmitEvent through the EventBus for processing.\n *\n * @param event - The native submit event from the form element\n */\n protected onNativeSubmit(event: Event): void {\n event.preventDefault();\n this.eventBus.dispatch(SubmitEvent);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Sync entity changes to the value signal\n explicitEffect([this.entity], ([currentEntity]) => {\n const currentValue = this.value();\n if (!isEqual(currentEntity, currentValue)) {\n this.value.set(currentEntity);\n }\n });\n\n // Clear loading errors when config changes\n explicitEffect([this.config], () => {\n this.fieldLoadingErrors.set([]);\n });\n\n // Emit initialization event for paged forms\n explicitEffect([this.formModeDetection, this.pageFieldDefinitions], ([{ mode }, pages]) => {\n if (mode === 'paged' && pages.length > 0) {\n this.eventBus.dispatch(ComponentInitializedEvent, 'dynamic-form', this.componentId);\n }\n });\n\n // Emit initialization event for non-paged forms\n explicitEffect([this.resolvedFields, this.formModeDetection], ([fields, { mode }]) => {\n if (mode === 'non-paged' && fields.length > 0) {\n afterNextRender(\n () => {\n this.eventBus.dispatch(ComponentInitializedEvent, 'dynamic-form', this.componentId);\n },\n { injector: this.injector },\n );\n }\n });\n }\n\n private setupEventHandlers(): void {\n this.eventBus\n .on<FormResetEvent>('form-reset')\n .pipe(takeUntilDestroyed())\n .subscribe(() => this.onFormReset());\n\n this.eventBus\n .on<FormClearEvent>('form-clear')\n .pipe(takeUntilDestroyed())\n .subscribe(() => this.onFormClear());\n\n createSubmissionHandler({\n eventBus: this.eventBus,\n configSignal: this.config,\n formSignal: this.form,\n })\n .pipe(takeUntilDestroyed())\n .subscribe();\n }\n\n private registerValidatorsFromConfig({ customFnConfig, schemas }: FormConfig<TFields>): void {\n if (schemas) {\n schemas.forEach((schema) => {\n this.schemaRegistry.registerSchema(schema);\n });\n }\n\n if (!customFnConfig) {\n return;\n }\n\n if (customFnConfig.customFunctions) {\n Object.entries(customFnConfig.customFunctions).forEach(([name, fn]) => {\n this.functionRegistry.registerCustomFunction(name, fn);\n });\n }\n\n // Register derivation functions (stored separately for use by derivation applicator)\n if (customFnConfig.derivations) {\n this.functionRegistry.setDerivationFunctions(customFnConfig.derivations);\n }\n\n this.functionRegistry.setValidators(customFnConfig.validators);\n this.functionRegistry.setAsyncValidators(customFnConfig.asyncValidators);\n this.functionRegistry.setHttpValidators(customFnConfig.httpValidators);\n }\n\n private createFormSetupFromConfig(fields: FieldDef<unknown>[], mode: FormMode, registry: Map<string, FieldTypeDefinition>) {\n const flattenedFields = this.memoizedFlattenFields(fields, registry);\n const flattenedFieldsForRendering = this.memoizedFlattenFieldsForRendering(fields, registry);\n const fieldsById = this.memoizedKeyBy(flattenedFields);\n const defaultValues = this.memoizedDefaultValues(fieldsById, registry);\n const fieldsToRender = mode === 'paged' ? [] : flattenedFieldsForRendering;\n\n return {\n fields: fieldsToRender,\n schemaFields: flattenedFields,\n originalFields: fields,\n defaultValues,\n schema: undefined,\n mode,\n registry,\n };\n }\n\n private createEmptyFormSetup(registry: Map<string, FieldTypeDefinition>) {\n return {\n fields: [],\n schemaFields: [],\n defaultValues: {} as TModel,\n schema: undefined,\n mode: 'non-paged' as const,\n registry,\n };\n }\n\n private onFormReset(): void {\n const defaults = this.defaultValues();\n // Type assertion is necessary: Angular Signal Forms expects exact form value type\n (this.form()().value.set as (value: unknown) => void)(defaults);\n this.value.set(defaults as Partial<TModel>);\n }\n\n private onFormClear(): void {\n const emptyValue = {} as Partial<TModel>;\n // Type assertion is necessary: Angular Signal Forms expects exact form value type\n (this.form()().value.set as (value: unknown) => void)(emptyValue);\n this.value.set(emptyValue);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────────────────────────\n\n ngOnDestroy(): void {\n this.rootFormRegistry.unregisterForm();\n }\n}\n","import { computed, Signal } from '@angular/core';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Maps an array field definition to component inputs.\n *\n * Array components create nested form structures under the array's key.\n * The array component will inject the parent FIELD_SIGNAL_CONTEXT and create\n * a scoped child injector for its array item fields.\n *\n * @param fieldDef The array field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function arrayFieldMapper(fieldDef: ArrayField): Signal<Record<string, unknown>> {\n const className = buildClassName(fieldDef);\n\n // Array inputs are static (no reactive dependencies)\n return computed(() => ({\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n }));\n}\n","import { computed, Signal } from '@angular/core';\nimport { GroupField } from '../../definitions/default/group-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Maps a group field definition to component inputs.\n *\n * Group components create nested form structures under the group's key.\n * The group component will inject the parent FIELD_SIGNAL_CONTEXT and create\n * a scoped child injector for its nested fields.\n *\n * @param fieldDef The group field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function groupFieldMapper(fieldDef: GroupField): Signal<Record<string, unknown>> {\n const className = buildClassName(fieldDef);\n\n // Group inputs are static (no reactive dependencies)\n return computed(() => ({\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n }));\n}\n","import { computed, Signal } from '@angular/core';\nimport { RowField } from '../../definitions/default/row-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Maps a row field definition to component inputs.\n *\n * Row components are layout containers that don't change the form shape.\n * The row component will inject FIELD_SIGNAL_CONTEXT directly.\n *\n * @param fieldDef The row field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function rowFieldMapper(fieldDef: RowField): Signal<Record<string, unknown>> {\n const className = buildClassName(fieldDef);\n\n // Row inputs are static (no reactive dependencies)\n return computed(() => ({\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n }));\n}\n","import { computed, Signal } from '@angular/core';\nimport { PageField } from '../../definitions/default/page-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Maps a page field definition to component inputs.\n *\n * Page fields are layout containers that don't modify the form context.\n * The page component will inject FIELD_SIGNAL_CONTEXT directly.\n *\n * @param fieldDef The page field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function pageFieldMapper(fieldDef: PageField): Signal<Record<string, unknown>> {\n const className = buildClassName(fieldDef);\n\n // Page inputs are static (no reactive dependencies)\n return computed(() => ({\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n }));\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { TextField } from '../../definitions/default/text-field';\nimport { buildBaseInputs } from '../base/base-field-mapper';\nimport { FunctionRegistryService } from '../../core/registry/function-registry.service';\nimport { FieldContextRegistryService } from '../../core/registry/field-context-registry.service';\nimport { evaluateCondition } from '../../core/expressions/condition-evaluator';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { DEFAULT_PROPS } from '../../models/field-signal-context.token';\n\n/**\n * Maps a text field definition to component inputs.\n *\n * Text fields are display-only fields that don't participate in the form schema.\n * This mapper handles the `logic` configuration by creating reactive signals\n * that evaluate conditions using the form value from RootFormRegistryService.\n *\n * @param fieldDef The text field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function textFieldMapper(fieldDef: TextField): Signal<Record<string, unknown>> {\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n const defaultProps = inject(DEFAULT_PROPS);\n\n // Create computed signal for hidden state based on logic configuration\n const hiddenLogic = fieldDef.logic?.filter((l) => l.type === 'hidden') ?? [];\n\n // Return computed signal for reactive updates\n return computed(() => {\n const baseInputs = buildBaseInputs(fieldDef, defaultProps());\n const inputs: Record<string, unknown> = { ...baseInputs };\n\n // Evaluate hidden logic if present\n if (hiddenLogic.length > 0) {\n // Use centralized context creation for display-only components\n const evaluationContext = fieldContextRegistry.createDisplayOnlyContext(fieldDef.key, functionRegistry.getCustomFunctions());\n\n // Evaluate all hidden logic conditions - if ANY is true, the field is hidden\n inputs['hidden'] = hiddenLogic.some((logic) => {\n if (typeof logic.condition === 'boolean') {\n return logic.condition;\n }\n return evaluateCondition(logic.condition as ConditionalExpression, evaluationContext);\n });\n }\n\n return inputs;\n });\n}\n","import { FieldTypeDefinition } from '../models/field-type';\nimport { arrayFieldMapper } from '../mappers/array/array-field-mapper';\nimport { groupFieldMapper } from '../mappers/group/group-field-mapper';\nimport { rowFieldMapper } from '../mappers/row/row-field-mapper';\nimport { pageFieldMapper } from '../mappers/page/page-field-mapper';\nimport { textFieldMapper } from '../mappers/text/text-field-mapper';\nimport { RowField } from '../definitions/default/row-field';\nimport { GroupField } from '../definitions/default/group-field';\nimport { HiddenField } from '../definitions/default/hidden-field';\nimport { ArrayField } from '../definitions/default/array-field';\nimport { PageField } from '../definitions/default/page-field';\nimport { TextField } from '../definitions/default/text-field';\n\n/**\n * Built-in field types provided by the dynamic form library.\n *\n * These core field types handle form structure and layout. They are automatically\n * registered when using provideDynamicForm() and form the foundation for building\n * complex form layouts with nested fields and multi-step flows.\n *\n * @example\n * ```typescript\n * // Row field for horizontal layout\n * { type: 'row', fields: [\n * { type: 'input', key: 'firstName' },\n * { type: 'input', key: 'lastName' }\n * ]}\n *\n * // Group field for nested form sections\n * { type: 'group', key: 'address', fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city' }\n * ]}\n *\n * // Array field for array-based form sections\n * { type: 'array', key: 'items', fields: [\n * { type: 'input', key: 'name' },\n * { type: 'input', key: 'quantity' }\n * ]}\n *\n * // Page field for multi-step forms\n * { type: 'page', key: 'step1', fields: [...] }\n * ```\n */\n/**\n * Built-in field types provided by the dynamic form library.\n *\n * Each field type is validated at compile time using satisfies, ensuring\n * type safety of the mapper function while allowing the array to be typed\n * as FieldTypeDefinition[] for consumer flexibility.\n */\nexport const BUILT_IN_FIELDS: FieldTypeDefinition[] = [\n {\n name: 'row',\n loadComponent: () => import('../fields/row/row-field.component'),\n mapper: rowFieldMapper,\n valueHandling: 'flatten',\n } satisfies FieldTypeDefinition<RowField>,\n {\n name: 'group',\n loadComponent: () => import('../fields/group/group-field.component'),\n mapper: groupFieldMapper,\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<GroupField>,\n {\n name: 'array',\n loadComponent: () => import('../fields/array/array-field.component'),\n mapper: arrayFieldMapper,\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<ArrayField>,\n {\n name: 'page',\n loadComponent: () => import('../fields/page/page-field.component'),\n mapper: pageFieldMapper,\n valueHandling: 'flatten',\n } satisfies FieldTypeDefinition<PageField>,\n {\n name: 'text',\n loadComponent: () => import('../fields/text/text-field.component'),\n mapper: textFieldMapper,\n valueHandling: 'exclude',\n } satisfies FieldTypeDefinition<TextField>,\n {\n name: 'hidden',\n // Componentless field - no loadComponent or mapper needed\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<HiddenField>,\n];\n","import { EnvironmentProviders, inject, makeEnvironmentProviders, Provider } from '@angular/core';\nimport { provideSignalFormsConfig } from '@angular/forms/signals';\nimport { NG_STATUS_CLASSES } from '@angular/forms/signals/compat';\nimport { FIELD_REGISTRY, FieldTypeDefinition } from '../models/field-type';\nimport { BUILT_IN_FIELDS } from './built-in-fields';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { DynamicFormFeature, isDynamicFormFeature } from './features/dynamic-form-feature';\nimport { DynamicFormLogger } from './features/logger/logger.token';\nimport { ConsoleLogger } from './features/logger/console-logger';\n\n// Re-export global types for module augmentation\nexport type { DynamicFormFieldRegistry, AvailableFieldTypes } from '../models/registry';\nexport type { RegisteredFieldTypes } from '../models/types';\n\n/**\n * Field type definitions with optional config providers\n */\ntype FieldTypeDefinitionsWithConfig = FieldTypeDefinition[] & {\n __configProviders?: Provider[];\n};\n\n/**\n * Extract FieldDef type from FieldTypeDefinition\n */\ntype ExtractFieldDef<T> = T extends FieldTypeDefinition<infer F> ? F : never;\n\n/**\n * Union of all FieldDef types from provided field types\n */\ntype FieldDefUnion<T extends FieldTypeDefinition[]> = ExtractFieldDef<T[number]>;\n\n/**\n * Infer form value type from field definitions\n * Note: Full value type inference requires complex recursive type mapping.\n * Using unknown as placeholder until full inference is implemented.\n */\ntype InferFormValue<TFieldDefs extends FieldDef<unknown>[]> = {\n [K in TFieldDefs[number]['key']]: unknown;\n};\n\n/**\n * Provider result with type inference\n */\ntype ProvideDynamicFormResult<T extends FieldTypeDefinition[]> = EnvironmentProviders & {\n __fieldDefs?: FieldDefUnion<T>;\n __formValue?: InferFormValue<FieldDefUnion<T>[]>;\n};\n\n/**\n * Union type for items that can be passed to provideDynamicForm\n */\ntype FieldTypeOrFeature = FieldTypeDefinition | DynamicFormFeature;\n\n/**\n * Extract only FieldTypeDefinition items from a tuple type\n */\ntype ExtractFieldTypes<T extends FieldTypeOrFeature[]> = {\n [K in keyof T]: T[K] extends FieldTypeDefinition ? T[K] : never;\n}[number] extends infer U\n ? U extends FieldTypeDefinition\n ? U[]\n : never\n : never;\n\n/**\n * Provider function to configure the dynamic form system with field types and options.\n *\n * This function creates environment providers that can be used at application or route level\n * to register field types. It provides type-safe field registration with automatic type inference.\n *\n * @param items - Field type definitions and/or features (like withLoggerConfig)\n * @returns Environment providers for dependency injection with type inference\n *\n * @example\n * ```typescript\n * // Application-level setup\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideDynamicForm(...withMaterialFields())\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Disable logging\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(false)\n * )\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Custom field types with type inference\n * import { CustomFieldType, AnotherFieldType } from './custom-fields';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [\n * provideDynamicForm(CustomFieldType, AnotherFieldType)\n * ]\n * };\n * ```\n *\n * @typeParam T - Array of field type definitions for type inference\n *\n * @public\n */\nexport function provideDynamicForm<const T extends FieldTypeOrFeature[]>(\n ...items: T\n): ProvideDynamicFormResult<ExtractFieldTypes<T> extends FieldTypeDefinition[] ? ExtractFieldTypes<T> : FieldTypeDefinition[]> {\n // Separate field types from features\n const fieldTypes = items.filter((item): item is FieldTypeDefinition => !isDynamicFormFeature(item));\n const features = items.filter(isDynamicFormFeature);\n\n const fields = [...BUILT_IN_FIELDS, ...fieldTypes];\n\n // Extract config providers from field type arrays\n const configProviders: Provider[] = [];\n fieldTypes.forEach((fieldTypeArray) => {\n const fieldTypeWithConfig = fieldTypeArray as unknown as FieldTypeDefinitionsWithConfig;\n if (fieldTypeWithConfig.__configProviders) {\n configProviders.push(...fieldTypeWithConfig.__configProviders);\n }\n });\n\n // Extract providers from features\n const featureProviders: Provider[] = [];\n const hasLoggerFeature = features.some((feature) => feature.ɵkind === 'logger');\n features.forEach((feature) => {\n featureProviders.push(...feature.ɵproviders);\n });\n\n // Default logger provider (ConsoleLogger) if no logger feature was provided\n const defaultLoggerProvider: Provider[] = hasLoggerFeature ? [] : [{ provide: DynamicFormLogger, useValue: new ConsoleLogger() }];\n\n return makeEnvironmentProviders([\n ...defaultLoggerProvider,\n // Always provide default Signal Forms classes (ng-touched, ng-invalid, etc.)\n provideSignalFormsConfig({ classes: NG_STATUS_CLASSES }),\n {\n provide: FIELD_REGISTRY,\n useFactory: () => {\n const logger = inject(DynamicFormLogger);\n const registry = new Map();\n // Add custom field types\n fields.forEach((fieldType) => {\n if (registry.has(fieldType.name)) {\n logger.warn(`Field type \"${fieldType.name}\" is already registered. Overwriting.`);\n }\n registry.set(fieldType.name, fieldType);\n });\n return registry;\n },\n },\n ...configProviders,\n ...featureProviders,\n ]) as ProvideDynamicFormResult<ExtractFieldTypes<T> extends FieldTypeDefinition[] ? ExtractFieldTypes<T> : FieldTypeDefinition[]>;\n}\n\n/**\n * Extract FieldDef types from provider result\n */\nexport type ExtractFieldDefs<T> = T extends { __fieldDefs?: infer F } ? F : never;\n\n/**\n * Extract form value type from provider result\n */\nexport type ExtractFormValue<T> = T extends { __formValue?: infer V } ? V : never;\n","import { computed, Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FormOptions, NextButtonOptions, SubmitButtonOptions } from '../../models/form-config';\nimport { LogicConfig, FormStateCondition, isFormStateCondition } from '../../models/logic';\nimport { ConditionalExpression } from '../../models/expressions';\nimport { evaluateCondition } from '../expressions';\nimport type { Logger } from '../../providers/features/logger/logger.interface';\n\n/**\n * No-op logger for when no logger is provided.\n * Used as fallback in button logic evaluation to avoid breaking downstream packages.\n */\nconst noOpLogger: Logger = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n debug: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n info: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n warn: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n error: () => {},\n};\n\n/**\n * Context for resolving button disabled state.\n *\n * @public\n */\nexport interface ButtonLogicContext {\n /** The form's FieldTree instance (supports both string and number keys for array indices) */\n form: FieldTree<unknown, string | number>;\n\n /** Form-level options */\n formOptions?: FormOptions;\n\n /** Field-level logic array (if provided) */\n fieldLogic?: LogicConfig[];\n\n /** Explicit disabled state from field definition */\n explicitlyDisabled?: boolean;\n\n /** Current page validity signal (for paged forms) */\n currentPageValid?: Signal<boolean>;\n\n /** Current form value for evaluating conditional expressions */\n formValue?: unknown;\n\n /** Optional logger for diagnostic output. Falls back to no-op logger if not provided. */\n logger?: Logger;\n}\n\n/**\n * Default options for submit button disabled behavior.\n */\nconst DEFAULT_SUBMIT_BUTTON_OPTIONS: Required<SubmitButtonOptions> = {\n disableWhenInvalid: true,\n disableWhileSubmitting: true,\n};\n\n/**\n * Default options for next button disabled behavior.\n */\nconst DEFAULT_NEXT_BUTTON_OPTIONS: Required<NextButtonOptions> = {\n disableWhenPageInvalid: true,\n disableWhileSubmitting: true,\n};\n\n/**\n * Evaluates a FormStateCondition against the current form/page state.\n *\n * @param condition - The form state condition to evaluate\n * @param ctx - The button logic context\n * @returns true if the condition is met (button should be disabled)\n */\nfunction evaluateFormStateCondition(condition: FormStateCondition, ctx: ButtonLogicContext): boolean {\n const form = ctx.form();\n\n switch (condition) {\n case 'formInvalid':\n return !form.valid();\n\n case 'formSubmitting':\n return form.submitting();\n\n case 'pageInvalid':\n return ctx.currentPageValid ? !ctx.currentPageValid() : false;\n\n default:\n return false;\n }\n}\n\n/**\n * Evaluates a single logic condition (boolean, FormStateCondition, or ConditionalExpression).\n *\n * @param condition - The condition to evaluate\n * @param ctx - The button logic context\n * @returns true if the condition is met\n */\nfunction evaluateLogicCondition(condition: LogicConfig['condition'], ctx: ButtonLogicContext): boolean {\n // Boolean condition\n if (typeof condition === 'boolean') {\n return condition;\n }\n\n // FormStateCondition (string)\n if (isFormStateCondition(condition)) {\n return evaluateFormStateCondition(condition, ctx);\n }\n\n // ConditionalExpression\n const formValue = (ctx.formValue ?? ctx.form().value()) as Record<string, unknown>;\n const evaluationContext = {\n fieldValue: undefined,\n formValue,\n fieldPath: '',\n logger: ctx.logger ?? noOpLogger,\n };\n\n return evaluateCondition(condition as ConditionalExpression, evaluationContext);\n}\n\n/**\n * Checks if any disabled logic condition is met in the field's logic array.\n *\n * @param fieldLogic - Array of logic configurations\n * @param ctx - The button logic context\n * @returns true if any disabled condition is met\n */\nfunction hasFieldLevelDisabledCondition(fieldLogic: LogicConfig[] | undefined, ctx: ButtonLogicContext): boolean {\n if (!fieldLogic || fieldLogic.length === 0) {\n return false;\n }\n\n return fieldLogic.filter((logic) => logic.type === 'disabled').some((logic) => evaluateLogicCondition(logic.condition, ctx));\n}\n\n/**\n * Checks if the field has explicit logic that should override form-level defaults.\n *\n * When a field has its own disabled logic defined, it indicates the user wants\n * custom control over the disabled state, so form-level defaults should be ignored.\n *\n * @param fieldLogic - Array of logic configurations\n * @returns true if field has its own disabled logic\n */\nfunction hasCustomDisabledLogic(fieldLogic: LogicConfig[] | undefined): boolean {\n if (!fieldLogic || fieldLogic.length === 0) {\n return false;\n }\n\n return fieldLogic.some((logic) => logic.type === 'disabled');\n}\n\n/**\n * Resolves the disabled state for a submit button.\n *\n * The disabled state is determined by (in order of precedence):\n * 1. Explicit `disabled: true` on the field definition\n * 2. Field-level `logic` array (if present, overrides form-level defaults)\n * 3. Form-level `options.submitButton` defaults\n *\n * @param ctx - The button logic context\n * @returns A computed signal that returns true when the button should be disabled\n *\n * @example\n * ```typescript\n * const disabled = resolveSubmitButtonDisabled({\n * form: formInstance,\n * formOptions: config.options,\n * fieldLogic: buttonField.logic,\n * explicitlyDisabled: buttonField.disabled,\n * });\n *\n * // Use in template\n * <button [disabled]=\"disabled()\">Submit</button>\n * ```\n *\n * @public\n */\nexport function resolveSubmitButtonDisabled(ctx: ButtonLogicContext): Signal<boolean> {\n return computed(() => {\n // 1. Explicit disabled always wins\n if (ctx.explicitlyDisabled) {\n return true;\n }\n\n // 2. If field has custom disabled logic, use it exclusively\n if (hasCustomDisabledLogic(ctx.fieldLogic)) {\n return hasFieldLevelDisabledCondition(ctx.fieldLogic, ctx);\n }\n\n // 3. Apply form-level defaults\n const options = {\n ...DEFAULT_SUBMIT_BUTTON_OPTIONS,\n ...ctx.formOptions?.submitButton,\n };\n\n const form = ctx.form();\n\n if (options.disableWhenInvalid && !form.valid()) {\n return true;\n }\n\n if (options.disableWhileSubmitting && form.submitting()) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Resolves the disabled state for a next page button.\n *\n * The disabled state is determined by (in order of precedence):\n * 1. Explicit `disabled: true` on the field definition\n * 2. Field-level `logic` array (if present, overrides form-level defaults)\n * 3. Form-level `options.nextButton` defaults\n *\n * @param ctx - The button logic context\n * @returns A computed signal that returns true when the button should be disabled\n *\n * @example\n * ```typescript\n * const disabled = resolveNextButtonDisabled({\n * form: formInstance,\n * formOptions: config.options,\n * fieldLogic: buttonField.logic,\n * explicitlyDisabled: buttonField.disabled,\n * currentPageValid: pageOrchestrator.currentPageValid,\n * });\n * ```\n *\n * @public\n */\nexport function resolveNextButtonDisabled(ctx: ButtonLogicContext): Signal<boolean> {\n return computed(() => {\n // 1. Explicit disabled always wins\n if (ctx.explicitlyDisabled) {\n return true;\n }\n\n // 2. If field has custom disabled logic, use it exclusively\n if (hasCustomDisabledLogic(ctx.fieldLogic)) {\n return hasFieldLevelDisabledCondition(ctx.fieldLogic, ctx);\n }\n\n // 3. Apply form-level defaults\n const options = {\n ...DEFAULT_NEXT_BUTTON_OPTIONS,\n ...ctx.formOptions?.nextButton,\n };\n\n const form = ctx.form();\n\n if (options.disableWhenPageInvalid && ctx.currentPageValid && !ctx.currentPageValid()) {\n return true;\n }\n\n if (options.disableWhileSubmitting && form.submitting()) {\n return true;\n }\n\n return false;\n });\n}\n","import { FieldDef } from './field-def';\nimport { FieldMeta } from './field-meta';\nimport { FieldWithValidation } from './field-with-validation';\nimport { WithInputSignals } from '../../models/component-type';\nimport { Prettify } from '../../models/prettify';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\n/**\n * Supported primitive value types for form fields.\n * This type represents all possible value types that can be used in form fields.\n */\nexport type ValueType = string | number | boolean | Date | object | unknown[];\n\nexport interface BaseValueField<TProps, TValue, TMeta extends FieldMeta = FieldMeta> extends FieldDef<TProps, TMeta>, FieldWithValidation {\n value?: TValue;\n\n /**\n * Placeholder text displayed when the field is empty.\n * Supports static strings, Observables, and Signals for dynamic content.\n */\n placeholder?: DynamicText;\n\n required?: boolean;\n}\n\nexport function isValueField<TProps, TMeta extends FieldMeta = FieldMeta>(\n field: FieldDef<TProps, TMeta>,\n): field is BaseValueField<TProps, ValueType, TMeta> {\n return 'value' in field;\n}\n\ntype ExcludedKeys =\n | 'type'\n | 'conditionals'\n | 'value'\n | 'valueType'\n | 'disabled'\n | 'readonly'\n | 'hidden'\n | 'col'\n | 'minValue'\n | 'maxValue'\n | 'step'\n // Exclude validation config, but keep validationMessages for component use\n | 'required'\n | 'email'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern'\n | 'validators'\n | 'logic'\n | 'derivation'\n | 'schemas';\n// Note: 'meta' is NOT excluded - components must handle meta attributes\n\nexport type ValueFieldComponent<T extends BaseValueField<Record<string, unknown> | unknown, unknown>> = Prettify<\n WithInputSignals<Omit<T, ExcludedKeys>>\n>;\n","import { FieldDef } from './field-def';\nimport { FieldMeta } from './field-meta';\nimport { FieldWithValidation } from './field-with-validation';\nimport { WithInputSignals } from '../../models/component-type';\nimport { Prettify } from '../../models/prettify';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\nexport interface BaseCheckedField<TProps, TMeta extends FieldMeta = FieldMeta> extends FieldDef<TProps, TMeta>, FieldWithValidation {\n value?: boolean;\n\n /**\n * Placeholder text displayed when the field is empty.\n * Supports static strings, Observables, and Signals for dynamic content.\n */\n placeholder?: DynamicText;\n\n required?: boolean;\n}\n\nexport function isCheckedField<TProps, TMeta extends FieldMeta = FieldMeta>(\n field: FieldDef<TProps, TMeta>,\n): field is BaseCheckedField<TProps, TMeta> {\n return field.type === 'checkbox';\n}\n\n// Note: 'meta' is NOT excluded - components must handle meta attributes\ntype ExcludedKeys = 'type' | 'conditionals' | 'value' | 'disabled' | 'readonly' | 'hidden' | 'col' | keyof FieldWithValidation;\n\nexport type CheckedFieldComponent<T extends BaseCheckedField<Record<string, unknown> | unknown>> = Prettify<\n WithInputSignals<Omit<T, ExcludedKeys>>\n>;\n","/**\n * Context for token resolution in event args\n */\nexport interface TokenContext {\n /** Current field key */\n key?: string;\n /** Array index if field is inside an array */\n index?: number;\n /** Parent array field key if field is inside an array */\n arrayKey?: string;\n /** Current form value for complex indexing */\n formValue?: unknown;\n}\n\n/**\n * Resolves special tokens in event arguments to their actual values\n *\n * Supported tokens:\n * - $key: The current field key\n * - $index: The array index (if inside an array field)\n * - $arrayKey: The parent array field key (if inside an array field)\n * - formValue: Reference to the current form value for indexing\n *\n * @param args - Array of arguments that may contain tokens\n * @param context - Context object containing token values\n * @returns Array with resolved values\n *\n * @example\n * resolveTokens(['$arrayKey', '$index'], { arrayKey: 'contacts', index: 2 })\n * // Returns: ['contacts', 2]\n *\n * @example\n * resolveTokens(['$key', 'static'], { key: 'myField' })\n * // Returns: ['myField', 'static']\n */\nexport function resolveTokens(\n args: readonly (string | number | boolean | null | undefined)[],\n context: TokenContext,\n): (string | number | boolean | null | undefined | unknown)[] {\n return args.map((arg) => {\n // Only process string tokens\n if (typeof arg !== 'string') {\n return arg;\n }\n\n // Check for token patterns\n switch (arg) {\n case '$key':\n return context.key;\n case '$index':\n return context.index;\n case '$arrayKey':\n return context.arrayKey;\n case 'formValue':\n return context.formValue;\n default:\n // Return as-is if not a recognized token\n return arg;\n }\n });\n}\n","import type { FormConfig } from '../models/form-config';\nimport type { NarrowFields } from '../models/registry/field-registry';\nimport type { InferFormValue } from '../models/types/form-value-inference';\nimport type { FormSchema } from '@ng-forge/dynamic-forms/schema';\n\n/**\n * Type-safe form config builder that ensures schema matches field structure.\n *\n * This helper function provides type safety when using form-level schemas by\n * automatically inferring the form value type from fields and constraining\n * the schema type parameter accordingly.\n *\n * **When to use:**\n * - When you have a form-level `schema` and want type safety between fields and schema\n * - When you prefer function syntax over `as const satisfies FormConfig`\n *\n * **Note:** This is optional. Users who don't need schema type safety can\n * continue using `as const satisfies FormConfig` directly.\n *\n * @typeParam TFields - The field definitions array (narrowed via `as const`)\n * @typeParam TProps - Optional form-level default props type\n *\n * @param config - The form configuration object\n * @returns The same configuration with proper type inference\n *\n * @example Basic usage with Zod schema\n * ```typescript\n * import { z } from 'zod';\n * import { formConfig } from '@ng-forge/dynamic-forms';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const passwordSchema = z.object({\n * password: z.string().min(8),\n * confirmPassword: z.string(),\n * }).refine(\n * (data) => data.password === data.confirmPassword,\n * { message: 'Passwords must match', path: ['confirmPassword'] }\n * );\n *\n * const config = formConfig({\n * schema: standardSchema(passwordSchema),\n * fields: [\n * { key: 'password', type: 'input', label: 'Password', required: true, props: { type: 'password' } },\n * { key: 'confirmPassword', type: 'input', label: 'Confirm', required: true, props: { type: 'password' } },\n * { key: 'submit', type: 'submit', label: 'Register' },\n * ] as const,\n * });\n * ```\n *\n * @example Equivalent without helper\n * ```typescript\n * const config = {\n * schema: standardSchema(passwordSchema),\n * fields: [...],\n * } as const satisfies FormConfig;\n * ```\n */\nexport function formConfig<const TFields extends NarrowFields, TProps extends object = Record<string, unknown>>(\n config: Omit<FormConfig<TFields, InferFormValue<TFields>, TProps>, 'schema'> & {\n schema?: FormSchema<InferFormValue<TFields>>;\n },\n): FormConfig<TFields, InferFormValue<TFields>, TProps> {\n return config as FormConfig<TFields, InferFormValue<TFields>, TProps>;\n}\n","import { isSignal, Injector } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { isObservable, Observable, of } from 'rxjs';\nimport { DynamicText } from '../models/types/dynamic-text';\n\n/**\n * Converts DynamicText (string | Observable | Signal) to Observable<string>\n * Unifies all three types into a consistent Observable stream\n *\n * @param value - The dynamic text value to convert\n * @param injector - Optional injector for signal conversion\n * @returns Observable<string> - The value as an observable stream\n */\nexport function dynamicTextToObservable(value: DynamicText | undefined, injector?: Injector): Observable<string> {\n if (value === undefined) {\n return of('');\n }\n\n if (isObservable(value)) {\n return value;\n }\n\n if (isSignal(value)) {\n return toObservable(value, { injector });\n }\n\n return of(String(value));\n}\n","import { FieldMeta } from '../definitions/base/field-meta';\n\n/**\n * Applies meta attributes to a DOM element and tracks which attributes were applied.\n *\n * This utility handles:\n * - Removing previously applied attributes that are no longer in meta\n * - Setting new attributes from meta\n * - Converting all values to strings via String()\n *\n * @param element - The DOM element to apply attributes to\n * @param meta - The meta object containing attributes to apply\n * @param previouslyApplied - Set of attribute names that were previously applied\n * @returns A new Set containing the attribute names that were applied\n *\n * @example\n * ```typescript\n * private appliedAttrs = new Set<string>();\n *\n * explicitEffect([this.meta], ([meta]) => {\n * const input = this.el.nativeElement.querySelector('input');\n * if (input) {\n * this.appliedAttrs = applyMetaToElement(input, meta, this.appliedAttrs);\n * }\n * });\n * ```\n */\nexport function applyMetaToElement(element: Element, meta: FieldMeta | undefined, previouslyApplied: Set<string>): Set<string> {\n const newApplied = new Set<string>();\n\n // Remove old attributes no longer in meta\n for (const attr of previouslyApplied) {\n if (!meta || !(attr in meta) || meta[attr] === undefined) {\n element.removeAttribute(attr);\n }\n }\n\n if (!meta) return newApplied;\n\n // Apply new attributes\n for (const [key, value] of Object.entries(meta)) {\n if (value === undefined || value === null) continue;\n\n element.setAttribute(key, String(value));\n newApplied.add(key);\n }\n\n return newApplied;\n}\n","import { inject, Injector, isSignal, Pipe, PipeTransform } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { isObservable, Observable, of } from 'rxjs';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\n/**\n * Pipe that handles dynamic text resolution with support for static strings,\n * Observables, and Signals.\n *\n * Supports:\n * - Static strings (pass-through)\n * - Observables (subscribed internally)\n * - Signals (converted to Observable using toObservable for reactivity)\n *\n * @example\n * ```html\n * <!-- Static string -->\n * {{ 'Hello World' | dynamicText | async }}\n *\n * <!-- Observable -->\n * {{ transloco.selectTranslate('key') | dynamicText | async }}\n *\n * <!-- Signal -->\n * {{ myTextSignal | dynamicText | async }}\n * ```\n *\n * @public\n */\n@Pipe({\n name: 'dynamicText',\n standalone: true,\n})\nexport class DynamicTextPipe implements PipeTransform {\n private readonly injector = inject(Injector);\n\n /**\n * Transforms dynamic text input into a resolved string value\n *\n * @param value - The dynamic text value to resolve\n * @returns The resolved string value as an Observable\n */\n transform(value: DynamicText | undefined): Observable<string> {\n if (isObservable(value)) {\n return value;\n }\n\n if (isSignal(value)) {\n return toObservable(value, { injector: this.injector });\n }\n\n return of(value || '');\n }\n}\n","import { afterNextRender, Injector } from '@angular/core';\nimport { EventBus } from '../../events/event.bus';\nimport { ComponentInitializedEvent } from '../../events/constants/component-initialized.event';\n\n/**\n * Component type for initialization events.\n */\nexport type InitializationComponentType = 'dynamic-form' | 'group' | 'row' | 'page' | 'array';\n\n/**\n * Emits a component initialization event after the next render cycle.\n *\n * This utility is used by container components (group, row, page, array) to signal\n * that their child fields have been resolved and rendered. The event is dispatched\n * through the EventBus and is used by the initialization tracking system.\n *\n * @param eventBus - The EventBus instance to dispatch the event on\n * @param componentType - The type of component being initialized\n * @param componentKey - The unique key/id of the component\n * @param injector - The injector to use for afterNextRender scheduling\n */\nexport function emitComponentInitialized(\n eventBus: EventBus,\n componentType: InitializationComponentType,\n componentKey: string,\n injector: Injector,\n): void {\n afterNextRender(\n () => {\n try {\n eventBus.dispatch(ComponentInitializedEvent, componentType, componentKey);\n } catch {\n // Input not available - component may have been destroyed\n }\n },\n { injector },\n );\n}\n","import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, Injector, input } from '@angular/core';\nimport { NgComponentOutlet } from '@angular/common';\nimport { forkJoin, map, of, pipe, scan, switchMap } from 'rxjs';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\nimport { reconcileFields, ResolvedField, resolveField } from '../../utils/resolve-field/resolve-field';\nimport { emitComponentInitialized } from '../../utils/emit-initialization/emit-initialization';\nimport { RowField } from '../../definitions/default/row-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { EventBus } from '../../events/event.bus';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\n\n/**\n * Layout container for horizontal field arrangement.\n *\n * Does not create a new form context - fields share the parent's context.\n * Field values are flattened into the parent form (no nesting under row key).\n * Purely a visual/layout container with no impact on form structure.\n */\n@Component({\n selector: 'div[row-field]',\n imports: [NgComponentOutlet],\n template: `\n @for (field of resolvedFields(); track field.key) {\n <ng-container *ngComponentOutlet=\"field.component; injector: field.injector; inputs: field.inputs()\" />\n }\n `,\n styleUrl: './row-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n '[class.disabled]': 'disabled()',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class RowFieldComponent {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly injector = inject(Injector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n field = input.required<RowField>();\n key = input.required<string>();\n className = input<string>();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly hostClasses = computed(() => {\n const base = 'df-field df-row';\n const custom = this.className();\n return custom ? `${base} ${custom}` : base;\n });\n\n readonly disabled = computed(() => {\n try {\n return this.field().disabled || false;\n } catch {\n return false;\n }\n });\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Field Resolution\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly fieldsSource = computed(() => this.field().fields || []);\n\n protected readonly resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n pipe(\n switchMap((fields) => {\n if (!fields || fields.length === 0) {\n return of([] as (ResolvedField | undefined)[]);\n }\n const rowKey = this.field().key || '<no key>';\n const context = {\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry: this.rawFieldRegistry(),\n injector: this.injector,\n destroyRef: this.destroyRef,\n onError: (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}) ` +\n `within row '${rowKey}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n },\n };\n return forkJoin(fields.map((f) => resolveField(f as FieldDef<unknown>, context)));\n }),\n map((fields) => fields.filter((f): f is ResolvedField => f !== undefined)),\n scan(reconcileFields, [] as ResolvedField[]),\n ),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Emit initialization event when fields are resolved\n explicitEffect([this.resolvedFields], ([fields]) => {\n if (fields.length > 0) {\n emitComponentInitialized(this.eventBus, 'row', this.field().key, this.injector);\n }\n });\n }\n}\n\nexport { RowFieldComponent };\n","import {\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n inject,\n Injector,\n input,\n linkedSignal,\n runInInjectionContext,\n untracked,\n} from '@angular/core';\nimport { NgComponentOutlet } from '@angular/common';\nimport { outputFromObservable, toObservable } from '@angular/core/rxjs-interop';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\nimport { createFieldResolutionPipe, ResolvedField } from '../../utils/resolve-field/resolve-field';\nimport { emitComponentInitialized } from '../../utils/emit-initialization/emit-initialization';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { keyBy, mapValues, memoize } from '../../utils/object-utils';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { GroupField } from '../../definitions/default/group-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { FieldTree, form } from '@angular/forms/signals';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldSignalContext } from '../../mappers/types';\nimport { FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { getFieldDefaultValue } from '../../utils/default-value/default-value';\nimport { createSchemaFromFields } from '../../core/schema-builder';\nimport { EventBus } from '../../events/event.bus';\nimport { SubmitEvent } from '../../events/constants/submit.event';\nimport { flattenFields } from '../../utils/flattener/field-flattener';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\n\n/**\n * Container component for rendering nested form groups.\n *\n * Creates a scoped form context with its own validation state.\n * Child fields receive a FIELD_SIGNAL_CONTEXT scoped to this group's form instance.\n * Group values are nested under the group's key in the parent form.\n */\n@Component({\n selector: 'fieldset[group-field]',\n imports: [NgComponentOutlet],\n template: `\n @for (field of resolvedFields(); track field.key) {\n <ng-container *ngComponentOutlet=\"field.component; injector: field.injector; inputs: field.inputs()\" />\n }\n `,\n styleUrl: './group-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n role: 'group',\n '[class.disabled]': 'disabled()',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class GroupFieldComponent<TModel extends Record<string, unknown> = Record<string, unknown>> {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly parentFieldSignalContext = inject(FIELD_SIGNAL_CONTEXT) as FieldSignalContext<TModel>;\n private readonly injector = inject(Injector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Memoized Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly memoizedFlattenFields = memoize(\n (fields: readonly FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) => flattenFields([...fields], registry),\n {\n resolver: (fields, registry) =>\n JSON.stringify(fields.map((f) => ({ key: f.key, type: f.type }))) + '_' + Array.from(registry.keys()).sort().join(','),\n maxSize: 10,\n },\n );\n\n private readonly memoizedKeyBy = memoize(<T extends { key: string }>(fields: T[]) => keyBy(fields, 'key'), {\n resolver: (fields) => fields.map((f) => f.key).join(','),\n maxSize: 10,\n });\n\n private readonly memoizedDefaultValues = memoize(\n <T extends FieldDef<unknown>>(fieldsById: Record<string, T>, registry: Map<string, FieldTypeDefinition>) =>\n mapValues(fieldsById, (field) => getFieldDefaultValue(field, registry)),\n {\n resolver: (fieldsById, registry) => Object.keys(fieldsById).sort().join(',') + '_' + Array.from(registry.keys()).sort().join(','),\n maxSize: 10,\n },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n field = input.required<GroupField>();\n key = input.required<string>();\n className = input<string>();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly hostClasses = computed(() => {\n const base = 'df-field df-group';\n const custom = this.className();\n return custom ? `${base} ${custom}` : base;\n });\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n private readonly formSetup = computed(() => {\n const groupField = this.field();\n const registry = this.rawFieldRegistry();\n\n if (groupField.fields && groupField.fields.length > 0) {\n const flattenedFields = this.memoizedFlattenFields(groupField.fields, registry);\n const fieldsById = this.memoizedKeyBy(flattenedFields);\n const defaultValues = this.memoizedDefaultValues(fieldsById, registry);\n\n return {\n fields: flattenedFields,\n originalFields: groupField.fields,\n defaultValues,\n registry,\n };\n }\n\n return {\n fields: [],\n originalFields: [],\n defaultValues: {},\n registry,\n };\n });\n\n readonly defaultValues = linkedSignal(() => this.formSetup().defaultValues);\n\n private readonly entity = linkedSignal(() => {\n const parentValue = this.parentFieldSignalContext.value();\n const groupKey = this.field().key;\n const defaults = this.defaultValues();\n const groupValue = (parentValue as Record<string, unknown>)?.[groupKey] || {};\n return { ...defaults, ...groupValue };\n });\n\n private readonly form = computed(() => {\n return runInInjectionContext(this.injector, () => {\n const setup = this.formSetup();\n\n if (setup.fields.length > 0) {\n const schema = createSchemaFromFields(setup.fields, setup.registry);\n return untracked(() => form(this.entity, schema));\n }\n\n return untracked(() => form(this.entity));\n });\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly formValue = computed(() => this.entity());\n readonly valid = computed(() => this.form()().valid());\n readonly invalid = computed(() => this.form()().invalid());\n readonly dirty = computed(() => this.form()().dirty());\n readonly touched = computed(() => this.form()().touched());\n readonly errors = computed(() => this.form()().errors());\n readonly disabled = computed(() => this.form()().disabled());\n\n private readonly nestedFieldTree = computed((): FieldTree<Record<string, unknown>> => {\n const parentForm = this.parentFieldSignalContext.form as Record<string, FieldTree<Record<string, unknown>>>;\n const groupKey = this.field().key;\n const child = parentForm[groupKey];\n\n if (!child) {\n throw new DynamicFormError(\n `Group field \"${groupKey}\" not found in parent form. ` + `Ensure the parent form schema includes this group field.`,\n );\n }\n\n return child;\n });\n\n private readonly groupInjector = computed(() => {\n const groupFieldSignalContext: FieldSignalContext<Record<string, unknown>> = {\n injector: this.injector,\n value: this.parentFieldSignalContext.value,\n defaultValues: this.defaultValues,\n form: this.nestedFieldTree(),\n };\n\n return Injector.create({\n parent: this.injector,\n providers: [{ provide: FIELD_SIGNAL_CONTEXT, useValue: groupFieldSignalContext }],\n });\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Outputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly validityChange = outputFromObservable(toObservable(this.valid));\n readonly dirtyChange = outputFromObservable(toObservable(this.dirty));\n readonly submitted = outputFromObservable(this.eventBus.on<SubmitEvent>('submit'));\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Field Resolution\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly fieldsSource = computed(() => this.formSetup().fields);\n\n protected readonly resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n createFieldResolutionPipe(() => ({\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry: this.rawFieldRegistry(),\n injector: this.groupInjector(),\n destroyRef: this.destroyRef,\n onError: (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}) ` +\n `within group '${this.field().key}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n },\n })),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Emit initialization event when fields are resolved\n explicitEffect([this.resolvedFields], ([fields]) => {\n if (fields.length > 0) {\n emitComponentInitialized(this.eventBus, 'group', this.field().key, this.injector);\n }\n });\n }\n}\n\nexport { GroupFieldComponent };\n","import { Injector, Signal, type Type } from '@angular/core';\n\n/**\n * Generates a unique identifier for array items.\n * Uses crypto.randomUUID() for collision-free IDs that remain stable across position changes.\n */\nexport function generateArrayItemId(): string {\n return crypto.randomUUID();\n}\n\n/**\n * Resolved array item ready for declarative rendering with ngComponentOutlet.\n * Each item has a stable unique ID and a linkedSignal-based index that\n * automatically updates when items are added/removed.\n */\nexport interface ResolvedArrayItem {\n /** Unique identifier for this item (stable across position changes). */\n id: string;\n /** The loaded component type. */\n component: Type<unknown>;\n /** Injector providing ARRAY_CONTEXT and FIELD_SIGNAL_CONTEXT. */\n injector: Injector;\n /** Inputs signal for ngComponentOutlet - evaluated in template for reactivity. */\n inputs: Signal<Record<string, unknown>>;\n}\n\n/**\n * Safely extracts an array value from a model object.\n * Returns empty array if the key doesn't exist or value isn't an array.\n */\nexport function getArrayValue<TModel>(value: Partial<TModel> | undefined, key: string): unknown[] {\n const arrayValue = (value as Record<string, unknown>)?.[key];\n return Array.isArray(arrayValue) ? arrayValue : [];\n}\n\n/**\n * Discriminated union of possible differential update operations.\n * Enables optimized array updates without full recreation when possible.\n */\nexport type DifferentialUpdateOperation =\n | { type: 'clear' }\n | { type: 'initial'; fieldTreesLength: number }\n | { type: 'append'; startIndex: number; endIndex: number }\n | { type: 'pop'; newLength: number }\n | { type: 'recreate' }\n | { type: 'none' };\n\n/**\n * Determines the optimal differential update operation based on current and new state.\n *\n * Operations:\n * - Clear all (empty array)\n * - Initial render (no existing items)\n * - Append only (items added at end)\n * - Pop only (items removed from end)\n * - None (same length - items update via linkedSignal)\n */\nexport function determineDifferentialOperation(currentItems: ResolvedArrayItem[], newLength: number): DifferentialUpdateOperation {\n const currentLength = currentItems.length;\n\n if (newLength === 0) {\n return { type: 'clear' };\n }\n\n if (currentLength === 0) {\n return { type: 'initial', fieldTreesLength: newLength };\n }\n\n // For all length changes, we optimize by assuming existing items stay in place.\n // Items handle their own value updates via linkedSignal - no need to compare snapshots.\n // Snapshot comparison was causing false \"recreate\" when existing items had been edited.\n\n if (newLength > currentLength) {\n // Items added - append new ones, existing items stay\n return { type: 'append', startIndex: currentLength, endIndex: newLength };\n }\n\n if (newLength < currentLength) {\n // Items removed - pop from end, remaining items stay\n return { type: 'pop', newLength };\n }\n\n // Same length - no structural change, items update via linkedSignal\n return { type: 'none' };\n}\n","import { Injector, runInInjectionContext, Signal, untracked, linkedSignal } from '@angular/core';\nimport { FieldTree, form } from '@angular/forms/signals';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { ArrayContext, FieldSignalContext } from '../../mappers/types';\nimport { ARRAY_CONTEXT, FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { mapFieldToInputs } from '../field-mapper/field-mapper';\nimport { flattenFields } from '../flattener/field-flattener';\nimport { createSchemaFromFields } from '../../core/schema-builder';\nimport { getArrayValue } from './array-field.types';\n\n/**\n * Options for creating an array item injector.\n */\nexport interface CreateArrayItemInjectorOptions<TModel extends Record<string, unknown>> {\n /** The field tree for this item (null for object items without existing FieldTree). */\n fieldTree: FieldTree<unknown> | null;\n /** The field template defining the array item structure. */\n template: FieldDef<unknown>;\n /** Signal containing the current index (uses linkedSignal for auto-updates). */\n indexSignal: Signal<number>;\n /** Parent context for accessing form state and values. */\n parentFieldSignalContext: FieldSignalContext<TModel>;\n /** Parent injector for creating scoped child injector. */\n parentInjector: Injector;\n /** Field registry for looking up field type definitions. */\n registry: Map<string, FieldTypeDefinition>;\n /** The array field definition containing this item. */\n arrayField: ArrayField;\n}\n\n/**\n * Result of creating an array item injector.\n */\nexport interface ArrayItemInjectorResult {\n /** Scoped injector providing ARRAY_CONTEXT and FIELD_SIGNAL_CONTEXT. */\n injector: Injector;\n /** Inputs signal for ngComponentOutlet, mapped from the field template. Undefined for componentless fields. */\n inputs: Signal<Record<string, unknown>> | undefined;\n}\n\n/**\n * Syncs item form value changes back to the parent form's array.\n * This effect watches the item form value and updates the parent array when changes occur.\n */\nfunction syncItemToParent<TModel extends Record<string, unknown>>(\n itemFormInstance: ReturnType<typeof form<unknown>>,\n parentFieldSignalContext: FieldSignalContext<TModel>,\n arrayKey: string,\n indexSignal: Signal<number>,\n injector: Injector,\n): void {\n // Track if we're currently syncing to prevent loops\n let isSyncing = false;\n\n runInInjectionContext(injector, () => {\n // The form instance is callable - call it to get the form state with .value()\n explicitEffect([() => itemFormInstance().value()], ([itemValue]) => {\n if (isSyncing) return;\n\n const parentForm = parentFieldSignalContext.form;\n const parentValue = untracked(() => parentForm().value()) as TModel;\n const currentArray = getArrayValue(parentValue as Partial<TModel>, arrayKey);\n const idx = untracked(() => indexSignal());\n\n // Only sync if value actually changed\n if (idx >= 0 && idx < currentArray.length && currentArray[idx] !== itemValue) {\n isSyncing = true;\n const newArray = [...currentArray];\n newArray[idx] = itemValue;\n // Update the parent form with the new array value\n // The `as any` is required due to Angular Signal Forms' complex conditional types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...parentValue, [arrayKey]: newArray } as any);\n isSyncing = false;\n }\n });\n });\n}\n\n/**\n * Creates an injector and inputs for an array item.\n *\n * Handles different item types (flatten, group, regular) by creating appropriate\n * form references and scoped injectors with ARRAY_CONTEXT and FIELD_SIGNAL_CONTEXT.\n * Sets up two-way sync to propagate item form changes back to the parent form.\n */\nexport function createArrayItemInjectorAndInputs<TModel extends Record<string, unknown>>(\n options: CreateArrayItemInjectorOptions<TModel>,\n): ArrayItemInjectorResult {\n const { fieldTree, template, indexSignal, parentFieldSignalContext, parentInjector, registry, arrayField } = options;\n\n // Create item form - uses linkedSignal that derives from parent\n const formRef =\n fieldTree ??\n createObjectItemForm({\n template,\n indexSignal,\n parentFieldSignalContext,\n parentInjector,\n registry,\n arrayKey: arrayField.key,\n });\n\n const injector = createItemInjector({\n formRef,\n indexSignal,\n parentFieldSignalContext,\n parentInjector,\n arrayField,\n });\n\n // Set up two-way sync: item form changes -> parent form array\n // Only sync for locally created forms (not external FieldTrees)\n if (!fieldTree) {\n syncItemToParent(formRef as ReturnType<typeof form<unknown>>, parentFieldSignalContext, arrayField.key, indexSignal, injector);\n }\n\n const inputs = runInInjectionContext(injector, () => {\n return mapFieldToInputs(template, registry);\n });\n\n return { injector, inputs };\n}\n\ninterface CreateObjectItemFormOptions<TModel extends Record<string, unknown>> {\n template: FieldDef<unknown>;\n indexSignal: Signal<number>;\n parentFieldSignalContext: FieldSignalContext<TModel>;\n parentInjector: Injector;\n registry: Map<string, FieldTypeDefinition>;\n arrayKey: string;\n}\n\n/**\n * Creates a local form for an object array item using linkedSignal.\n * The linkedSignal derives from the parent array at the current index.\n *\n * For array items, we always create a form with a schema to ensure proper field structure.\n * This is needed for valueFieldMapper to find fields via bracket notation.\n */\nfunction createObjectItemForm<TModel extends Record<string, unknown>>(\n options: CreateObjectItemFormOptions<TModel>,\n): ReturnType<typeof form<unknown>> {\n const { template, indexSignal, parentFieldSignalContext, parentInjector, registry, arrayKey } = options;\n\n const itemEntity = linkedSignal(() => {\n const parentValue = parentFieldSignalContext.value();\n const arrayValue = getArrayValue(parentValue as Partial<TModel>, arrayKey);\n return arrayValue[indexSignal()] ?? {};\n });\n\n const nestedFields = 'fields' in template && Array.isArray(template.fields) ? template.fields : [];\n\n return runInInjectionContext(parentInjector, () => {\n // Determine which fields to include in the schema\n // - If template has nested fields (e.g., row with children), use those\n // - Otherwise use the template itself as a single-field schema\n const schemaFields = nestedFields.length > 0 ? nestedFields : [template];\n const flattenedFields = flattenFields(schemaFields, registry);\n const schema = createSchemaFromFields(flattenedFields, registry);\n return untracked(() => form(itemEntity, schema));\n });\n}\n\ninterface CreateItemInjectorOptions<TModel extends Record<string, unknown>> {\n formRef: FieldTree<unknown> | ReturnType<typeof form<unknown>>;\n indexSignal: Signal<number>;\n parentFieldSignalContext: FieldSignalContext<TModel>;\n parentInjector: Injector;\n arrayField: ArrayField;\n}\n\n/**\n * Creates a scoped injector for an array item.\n * Provides both FIELD_SIGNAL_CONTEXT (for form access) and ARRAY_CONTEXT (for position awareness).\n */\nfunction createItemInjector<TModel extends Record<string, unknown>>(options: CreateItemInjectorOptions<TModel>): Injector {\n const { formRef, indexSignal, parentFieldSignalContext, parentInjector, arrayField } = options;\n\n const arrayContext: ArrayContext = {\n arrayKey: arrayField.key,\n index: indexSignal,\n formValue: parentFieldSignalContext.value(),\n field: arrayField,\n };\n\n const itemFieldSignalContext: FieldSignalContext<Record<string, unknown>> = {\n injector: undefined as unknown as Injector,\n value: parentFieldSignalContext.value,\n defaultValues: () => ({}),\n form: formRef as FieldTree<Record<string, unknown>>,\n };\n\n const injector = Injector.create({\n parent: parentInjector,\n providers: [\n { provide: FIELD_SIGNAL_CONTEXT, useValue: itemFieldSignalContext },\n { provide: ARRAY_CONTEXT, useValue: arrayContext },\n ],\n });\n\n itemFieldSignalContext.injector = injector;\n\n return injector;\n}\n","import { DestroyRef, Injector, linkedSignal, Signal, Type } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { catchError, from, map, Observable, of } from 'rxjs';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldSignalContext } from '../../mappers/types';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { generateArrayItemId, ResolvedArrayItem } from './array-field.types';\nimport { createArrayItemInjectorAndInputs } from './create-array-item-injector';\n\n/**\n * Options for resolving an array item.\n */\nexport interface ResolveArrayItemOptions<TModel extends Record<string, unknown>> {\n /** The field tree for this item (null for object items). */\n fieldTree: FieldTree<unknown> | null;\n /** The initial index of this item in the array. */\n index: number;\n /** The field template defining the array item structure. */\n template: FieldDef<unknown>;\n /** The array field definition containing this item. */\n arrayField: ArrayField;\n /** Signal containing ordered item IDs for reactive index derivation. */\n itemOrderSignal: Signal<string[]>;\n /** Parent context for accessing form state and values. */\n parentFieldSignalContext: FieldSignalContext<TModel>;\n /** Parent injector for creating scoped child injector. */\n parentInjector: Injector;\n /** Field registry for looking up field type definitions. */\n registry: Map<string, FieldTypeDefinition>;\n /** DestroyRef to abort resolution if component is destroyed. */\n destroyRef: DestroyRef;\n /**\n * Function to async load the component for the field type.\n * Returns undefined for componentless fields (e.g., hidden fields).\n */\n loadTypeComponent: (type: string) => Promise<Type<unknown> | undefined>;\n}\n\n/**\n * Resolves a single array item for declarative rendering.\n *\n * Uses linkedSignal for the index, which automatically updates when itemOrderSignal changes.\n * This enables position-aware updates without recreating components when items are reordered.\n */\nexport function resolveArrayItem<TModel extends Record<string, unknown>>(\n options: ResolveArrayItemOptions<TModel>,\n): Observable<ResolvedArrayItem | undefined> {\n const {\n fieldTree,\n index,\n template,\n arrayField,\n itemOrderSignal,\n parentFieldSignalContext,\n parentInjector,\n registry,\n destroyRef,\n loadTypeComponent,\n } = options;\n\n return from(loadTypeComponent(template.type)).pipe(\n map((component) => {\n if (destroyRef.destroyed) {\n return undefined;\n }\n\n // Componentless fields (e.g., hidden) return undefined - nothing to render\n if (!component) {\n return undefined;\n }\n\n const itemId = generateArrayItemId();\n\n const indexSignal = linkedSignal(() => {\n const order = itemOrderSignal();\n const idx = order.indexOf(itemId);\n return idx >= 0 ? idx : index;\n });\n\n const { injector, inputs } = createArrayItemInjectorAndInputs({\n fieldTree,\n template,\n indexSignal,\n parentFieldSignalContext,\n parentInjector,\n registry,\n arrayField,\n });\n\n // Array item templates should always have inputs (componentless fields are handled above)\n if (!inputs) {\n return undefined;\n }\n\n return {\n id: itemId,\n component,\n injector,\n inputs,\n };\n }),\n catchError((error) => {\n if (!destroyRef.destroyed) {\n const logger = parentInjector.get(DynamicFormLogger);\n logger.error(\n `Failed to load component for field type '${template.type}' at index ${index} ` +\n `within array '${arrayField.key}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n }\n return of(undefined);\n }),\n );\n}\n","import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, Injector, input, linkedSignal, signal } from '@angular/core';\nimport { NgComponentOutlet } from '@angular/common';\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\nimport { filter, forkJoin, map, Observable, of } from 'rxjs';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { getFieldDefaultValue } from '../../utils/default-value/default-value';\nimport { getFieldValueHandling } from '../../models/field-type';\nimport { emitComponentInitialized } from '../../utils/emit-initialization/emit-initialization';\nimport { AddArrayItemEvent } from '../../events/constants/add-array-item.event';\nimport { RemoveArrayItemEvent } from '../../events/constants/remove-array-item.event';\nimport { EventBus } from '../../events/event.bus';\nimport { FieldSignalContext } from '../../mappers/types';\nimport { FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { determineDifferentialOperation, getArrayValue, ResolvedArrayItem } from '../../utils/array-field/array-field.types';\nimport { resolveArrayItem } from '../../utils/array-field/resolve-array-item';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { ArrayFieldTree } from '../../core/field-tree-utils';\n\n/**\n * Container component for rendering dynamic arrays of fields.\n *\n * Supports add/remove operations via AddArrayItemEvent and RemoveArrayItemEvent.\n * Uses differential updates to optimize rendering - only recreates items when necessary.\n * Each item gets a scoped injector with ARRAY_CONTEXT for position-aware operations.\n */\n@Component({\n selector: 'array-field',\n imports: [NgComponentOutlet],\n template: `\n @for (item of resolvedItems(); track item.id) {\n <ng-container *ngComponentOutlet=\"item.component; injector: item.injector; inputs: item.inputs()\" />\n }\n `,\n styleUrl: './array-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class ArrayFieldComponent<TModel extends Record<string, unknown> = Record<string, unknown>> {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly parentFieldSignalContext = inject(FIELD_SIGNAL_CONTEXT) as FieldSignalContext<TModel>;\n private readonly parentInjector = inject(Injector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n field = input.required<ArrayField>();\n key = input.required<string>();\n className = input<string>();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly hostClasses = computed(() => {\n const base = 'df-field df-array';\n const custom = this.className();\n return custom ? `${base} ${custom}` : base;\n });\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n private readonly fieldTemplate = computed<FieldDef<unknown> | null>(() => {\n const arrayField = this.field();\n return arrayField.fields && arrayField.fields.length > 0 ? arrayField.fields[0] : null;\n });\n\n private readonly arrayFieldTrees = computed<readonly (FieldTree<unknown> | null)[]>(() => {\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const arrayValue = getArrayValue(this.parentFieldSignalContext.value(), arrayKey);\n\n if (arrayValue.length === 0) return [];\n\n const arrayFieldTree = (parentForm as Record<string, ArrayFieldTree<unknown>>)[arrayKey];\n if (!arrayFieldTree) return arrayValue.map(() => null);\n\n // Access array items via bracket notation - Angular Signal Forms arrays support this\n const items: (FieldTree<unknown> | null)[] = [];\n for (let i = 0; i < arrayValue.length; i++) {\n // Access item FieldTree directly via numeric indexing (ArrayFieldTree supports this)\n const itemFieldTree = arrayFieldTree[i];\n items.push(itemFieldTree ?? null);\n }\n\n return items;\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly resolvedItemsSignal = signal<ResolvedArrayItem[]>([]);\n private readonly updateVersion = signal(0);\n private readonly itemOrderSignal = linkedSignal(() => this.resolvedItemsSignal().map((item) => item.id));\n\n readonly resolvedItems = linkedSignal(() => this.resolvedItemsSignal());\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n this.setupEventHandlers();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Sync field components when array data changes\n explicitEffect([this.arrayFieldTrees], ([fieldTrees]) => {\n this.updateVersion.update((v) => v + 1);\n const currentVersion = this.updateVersion();\n this.performDifferentialUpdate(fieldTrees, currentVersion);\n });\n }\n\n private setupEventHandlers(): void {\n // Handle add item events\n this.eventBus\n .on<AddArrayItemEvent>('add-array-item')\n .pipe(\n takeUntilDestroyed(),\n filter((event) => event.arrayKey === this.key()),\n )\n .subscribe((event) => this.addItem(event.field ?? this.fieldTemplate(), event.index));\n\n // Handle remove item events\n this.eventBus\n .on<RemoveArrayItemEvent>('remove-array-item')\n .pipe(\n takeUntilDestroyed(),\n filter((event) => event.arrayKey === this.key()),\n )\n .subscribe((event) => this.removeItem(event.index));\n }\n\n private performDifferentialUpdate(fieldTrees: readonly (FieldTree<unknown> | null)[], updateId: number): void {\n const resolvedItems = this.resolvedItemsSignal();\n const operation = determineDifferentialOperation(resolvedItems, fieldTrees.length);\n\n switch (operation.type) {\n case 'clear':\n this.resolvedItemsSignal.set([]);\n break;\n case 'initial':\n this.resolveAllItems(fieldTrees, updateId);\n break;\n case 'append':\n this.appendItems(fieldTrees, operation.startIndex, operation.endIndex, updateId);\n break;\n case 'pop':\n this.resolvedItemsSignal.set(resolvedItems.slice(0, operation.newLength));\n break;\n case 'recreate':\n this.resolvedItemsSignal.set([]);\n this.resolveAllItems(fieldTrees, updateId);\n break;\n case 'none':\n break;\n }\n }\n\n private resolveAllItems(fieldTrees: readonly (FieldTree<unknown> | null)[], updateId: number): void {\n if (fieldTrees.length === 0) {\n this.resolvedItemsSignal.set([]);\n return;\n }\n\n const itemObservables = fieldTrees.map((fieldTree, i) => this.createResolveItemObservable(fieldTree, i));\n\n forkJoin(itemObservables)\n .pipe(\n takeUntilDestroyed(this.destroyRef),\n map((items) => items.filter((item): item is ResolvedArrayItem => item !== undefined)),\n )\n .subscribe((newItems) => {\n if (updateId === this.updateVersion()) {\n this.resolvedItemsSignal.set(newItems);\n emitComponentInitialized(this.eventBus, 'array', this.field().key, this.parentInjector);\n }\n });\n }\n\n private appendItems(fieldTrees: readonly (FieldTree<unknown> | null)[], startIndex: number, endIndex: number, updateId: number): void {\n const itemsToResolve = fieldTrees.slice(startIndex, endIndex);\n if (itemsToResolve.length === 0) return;\n\n const itemObservables = itemsToResolve.map((fieldTree, i) => this.createResolveItemObservable(fieldTree, startIndex + i));\n\n forkJoin(itemObservables)\n .pipe(\n takeUntilDestroyed(this.destroyRef),\n map((items) => items.filter((item): item is ResolvedArrayItem => item !== undefined)),\n )\n .subscribe((newItems) => {\n if (updateId === this.updateVersion()) {\n this.resolvedItemsSignal.update((current) => [...current, ...newItems]);\n }\n });\n }\n\n private createResolveItemObservable(fieldTree: FieldTree<unknown> | null, index: number): Observable<ResolvedArrayItem | undefined> {\n const template = this.fieldTemplate();\n if (!template) return of(undefined);\n\n return resolveArrayItem({\n fieldTree,\n index,\n template,\n arrayField: this.field(),\n itemOrderSignal: this.itemOrderSignal,\n parentFieldSignalContext: this.parentFieldSignalContext,\n parentInjector: this.parentInjector,\n registry: this.rawFieldRegistry(),\n destroyRef: this.destroyRef,\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n });\n }\n\n private addItem(fieldTemplate: FieldDef<unknown> | null, index?: number): void {\n if (!fieldTemplate) {\n this.logger.error(\n `Cannot add item to array '${this.field().key}': no field template provided. ` +\n 'Ensure the array field has a fields property with at least one field definition.',\n );\n return;\n }\n\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const currentValue = parentForm().value() as TModel;\n const currentArray = getArrayValue(currentValue as Partial<TModel>, arrayKey);\n const insertIndex = index !== undefined ? Math.min(index, currentArray.length) : currentArray.length;\n\n const rawValue = getFieldDefaultValue(fieldTemplate, this.rawFieldRegistry());\n const valueHandling = getFieldValueHandling(fieldTemplate.type, this.rawFieldRegistry());\n\n // For fields with 'include' value handling (bare fields like input, checkbox, etc.),\n // wrap the value in an object using the field's key since arrays contain objects\n const value = valueHandling === 'include' && fieldTemplate.key ? { [fieldTemplate.key]: rawValue } : rawValue;\n\n const newArray = [...currentArray];\n newArray.splice(insertIndex, 0, value);\n\n // Update the parent form with the new array value\n // The `as any` is required due to Angular Signal Forms' complex conditional types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...currentValue, [arrayKey]: newArray } as any);\n }\n\n private removeItem(index?: number): void {\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const currentValue = parentForm().value() as TModel;\n const currentArray = getArrayValue(currentValue as Partial<TModel>, arrayKey);\n\n if (currentArray.length === 0) return;\n\n const removeIndex = index !== undefined ? Math.min(index, currentArray.length - 1) : currentArray.length - 1;\n const newArray = [...currentArray];\n newArray.splice(removeIndex, 1);\n\n // Update the parent form with the new array value\n // The `as any` is required due to Angular Signal Forms' complex conditional types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...currentValue, [arrayKey]: newArray } as any);\n }\n}\n\nexport { ArrayFieldComponent };\n","import { FieldTree } from '@angular/forms/signals';\n\n/**\n * Type representing a FieldTree for an array.\n * Extends FieldTree to add numeric indexing for accessing item FieldTrees.\n */\nexport type ArrayFieldTree<T> = FieldTree<T[]> & {\n readonly [index: number]: FieldTree<T> | undefined;\n};\n\n/**\n * Get the length of an array FieldTree.\n */\nexport function getArrayLength<T>(arrayFieldTree: ArrayFieldTree<T>): number {\n const value = arrayFieldTree().value();\n return Array.isArray(value) ? value.length : 0;\n}\n","import { ValidationError } from '../models/validation-types';\n\n/**\n * Interpolates {{param}} placeholders in message with error values\n *\n * @param message - Message template with {{param}} placeholders\n * @param error - Validation error containing parameter values\n * @returns Message with interpolated parameters\n *\n * @example\n * interpolateParams(\"Min value is {{min}}\", { kind: 'min', min: 5 })\n * // Returns: \"Min value is 5\"\n */\nexport function interpolateParams(message: string, error: ValidationError): string {\n let result = message;\n const params = extractErrorParams(error);\n\n Object.entries(params).forEach(([key, value]) => {\n const placeholder = new RegExp(`{{\\\\s*${key}\\\\s*}}`, 'g');\n result = result.replace(placeholder, safeToString(value));\n });\n\n return result;\n}\n\n/**\n * Safely converts a value to a string, handling complex objects\n * @internal\n */\nfunction safeToString(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Handle primitives directly\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n // Handle RegExp (has its own toString)\n if (value instanceof RegExp) {\n return value.toString();\n }\n\n // Handle Date\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n\n // For objects, try JSON.stringify first, fall back to empty string\n try {\n // Check if object has a custom toString that's not Object.prototype.toString\n if (typeof value === 'object' && value.toString !== Object.prototype.toString) {\n return value.toString();\n }\n // Otherwise use JSON representation\n return JSON.stringify(value);\n } catch {\n // If JSON.stringify fails (circular reference, etc.), return empty string\n return '[object]';\n }\n}\n\n/**\n * Extracts parameter values from validation error\n * @internal\n */\nfunction extractErrorParams(error: ValidationError): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n\n // Common validation error parameters\n if ('min' in error) params.min = error.min;\n if ('max' in error) params.max = error.max;\n if ('pattern' in error) params.pattern = error.pattern;\n if ('actual' in error) params.actual = error.actual;\n if ('expected' in error) params.expected = error.expected;\n\n // Handle length validation parameters\n // Angular Signal Forms uses 'minLength'/'maxLength' properties\n // Angular Classic Forms uses 'requiredLength'/'actualLength' properties\n // We support both formats and normalize to 'requiredLength' for message templates\n if ('requiredLength' in error) {\n params.requiredLength = error.requiredLength;\n } else if ('minLength' in error) {\n // Angular Signal Forms: minLength property maps to requiredLength for templates\n params.requiredLength = error.minLength;\n params.minLength = error.minLength;\n } else if ('maxLength' in error) {\n // Angular Signal Forms: maxLength property maps to requiredLength for templates\n params.requiredLength = error.maxLength;\n params.maxLength = error.maxLength;\n }\n if ('actualLength' in error) params.actualLength = error.actualLength;\n\n // Include all custom properties from error object (for custom validators)\n // Skip 'kind' as it's the error type identifier, not a parameter\n Object.keys(error).forEach((key) => {\n if (key !== 'kind' && !(key in params)) {\n params[key] = error[key as keyof ValidationError];\n }\n });\n\n return params;\n}\n","/**\n * @ng-forge/dynamic-forms\n *\n * Dynamic forms library for Angular applications.\n *\n * ## Public API (for end users)\n * - DynamicForm component\n * - provideDynamicForm() for configuration\n * - FormConfig and field definition types\n * - Event classes (SubmitEvent, PageChangeEvent, etc.)\n *\n * ## Integration API (for UI library authors)\n * Import from '@ng-forge/dynamic-forms/integration' for:\n * - Specific field types (InputField, SelectField, etc.)\n * - Field mappers (valueFieldMapper, checkboxFieldMapper, etc.)\n * - Error utilities (createResolvedErrorsSignal, shouldShowErrors)\n *\n */\n\n// ============================================================\n// PUBLIC API - For end users\n// ============================================================\n\n// Core Component\nexport { DynamicForm } from './dynamic-form.component';\n\n// Provider System\nexport { provideDynamicForm } from './providers';\nexport type { ExtractFieldDefs, ExtractFormValue } from './providers';\n\n// Logger Feature\nexport { withLoggerConfig } from './providers/features/logger/with-logger-config';\nexport { DynamicFormLogger } from './providers/features/logger/logger.token';\nexport type { Logger } from './providers/features/logger';\nexport { ConsoleLogger } from './providers/features/logger/console-logger';\nexport { NoopLogger } from './providers/features/logger/noop-logger';\n\n// Configuration Types\nexport type { CustomFnConfig, FormConfig, FormOptions } from './models';\nexport type { DynamicText, FieldOption, ValidationError, ValidationMessages } from './models';\n\n// Submission Config\nexport type { SubmissionConfig, SubmissionActionResult, SubmitButtonOptions, NextButtonOptions } from './models';\n\n// Form State Condition\nexport type { FormStateCondition } from './models';\nexport { isFormStateCondition } from './models';\n\n// Button Logic Resolver\nexport { resolveSubmitButtonDisabled, resolveNextButtonDisabled } from './core/logic';\nexport type { ButtonLogicContext } from './core/logic';\n\n// Abstract Base Field Types (for extension by UI libraries)\nexport type {\n BaseCheckedField,\n BaseValueField,\n CheckedFieldComponent,\n FieldComponent,\n FieldDef,\n FieldMeta,\n FieldWithValidation,\n ValueFieldComponent,\n ValueType,\n} from './definitions';\nexport { isCheckedField, isValueField } from './definitions';\n\n// Built-in Container Field Types\nexport type { ArrayField, GroupField, PageField, RowField, TextField, TextElementType, TextProps } from './definitions/default';\nexport { isRowField } from './definitions/default';\n\n// Validation Config Types\nexport type {\n AsyncValidatorConfig,\n BaseValidatorConfig,\n BuiltInValidatorConfig,\n CustomValidatorConfig,\n HttpValidatorConfig,\n ValidatorConfig,\n} from './models';\n\n// Validator Function Types (for customFnConfig)\nexport type { AsyncCustomValidator, CustomValidator, HttpCustomValidator } from './core/validation';\n\n// Logic & Expression Types\nexport type { ConditionalExpression, EvaluationContext, LogicConfig } from './models';\n\n// Schema Types\nexport type { SchemaApplicationConfig, SchemaDefinition } from './models';\n\n// Registry Types (for module augmentation)\nexport type {\n AvailableFieldTypes,\n ContainerFieldTypes,\n DynamicFormFieldRegistry,\n ExtractField,\n FieldRegistryContainers,\n FieldRegistryLeaves,\n LeafFieldTypes,\n NarrowField,\n NarrowFields,\n RegisteredFieldTypes,\n} from './models';\n\n// Utility Types\nexport type {\n ArrayAllowedChildren,\n FieldPathAccess,\n FormMode,\n FormModeDetectionResult,\n GroupAllowedChildren,\n InferFormValue,\n PageAllowedChildren,\n Prettify,\n RowAllowedChildren,\n WithInputSignals,\n} from './models';\n\n// Type Guards\nexport { isArrayField, isContainerField, isDisplayOnlyField, isGroupField, isLeafField, isPageField, isValueBearingField } from './models';\n\n// Events\nexport {\n AddArrayItemEvent,\n FormClearEvent,\n FormResetEvent,\n NextPageEvent,\n PageChangeEvent,\n PreviousPageEvent,\n RemoveArrayItemEvent,\n SubmitEvent,\n} from './events';\n\nexport type { FormEvent, FormEventConstructor, TokenContext, ArrayItemContext } from './events';\n\n// Helpers\nexport { formConfig } from './helpers';\n\n// Errors\nexport { DynamicFormError } from './errors/dynamic-form-error';\n\n// ============================================================\n// INTERNAL EXPORTS - Used by integration entrypoint\n// These are stable APIs for UI library authors\n// ============================================================\n\n// Base mapper utilities\nexport { baseFieldMapper, buildBaseInputs } from './mappers';\nexport { arrayFieldMapper, groupFieldMapper, pageFieldMapper, rowFieldMapper, textFieldMapper } from './mappers';\nexport type { ArrayContext, FieldSignalContext, MapperFn } from './mappers';\n\n// Field Type Definition - for registering custom field types\nexport type { FieldTypeDefinition, ValueHandlingMode } from './models';\nexport { FIELD_REGISTRY } from './models';\n\n// Signal Context - injection tokens for field components\nexport { ARRAY_CONTEXT, DEFAULT_PROPS, DEFAULT_VALIDATION_MESSAGES, FIELD_SIGNAL_CONTEXT, FORM_OPTIONS } from './models';\n\n// Dynamic Text utilities\nexport { dynamicTextToObservable } from './utils';\nexport { DynamicTextPipe } from './pipes';\n\n// Container Components - for building custom containers\nexport { ArrayFieldComponent, GroupFieldComponent, RowFieldComponent } from './fields';\n\n// Validation utilities\nexport { applyValidator, applyValidators } from './core/validation';\nexport type { HttpResourceRequest } from './core/validation';\n\n// FieldTree Utilities\nexport { getArrayLength } from './core/field-tree-utils';\nexport type { ArrayFieldTree } from './core/field-tree-utils';\n\n// Event utilities\nexport { EventBus, resolveTokens } from './events';\n\n// Registry Utilities\nexport { BUILT_IN_FIELDS } from './providers';\n\n// Object utilities (used by integration mappers)\nexport { isEqual, omit } from './utils/object-utils';\n\n// Interpolation utility (used by integration error utilities)\nexport { interpolateParams } from './utils/interpolate-params';\n\n// Meta utilities (used by UI library wrapped-meta directives)\nexport { applyMetaToElement } from './utils/apply-meta';\n\n// Registry services (used by UI library button mappers)\nexport { RootFormRegistryService } from './core/registry/root-form-registry.service';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["MAX_AST_CACHE_SIZE","isContainerWithFields","scan","map","filter","switchMap","traverseFields","collectFromField"],"mappings":";;;;;;;;;;;AAIA;;;AAGG;AACH,SAAS,aAAa,CAAC,KAAc,EAAA;IACnC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,CAAC;AACtE;AAEA;;;AAGG;AACH,SAAS,cAAc,CAAC,KAAc,EAAA;AACpC,IAAA,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC,CAAC;AACrI;AAoFA;SACgB,mBAAmB,CACjC,MAAuE,EACvE,QAAsE,EACtE,OAA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