{"version":3,"file":"index.mjs","names":["FRAME_PATTERN","buildError","buildError","buildError","hasHookAncestor","FUNCTION_TYPES","buildError","FUNCTION_TYPES","buildError","buildError","buildError","buildError","containsNode","buildError","containsNode","buildError","containsNode","containsNode","buildError","buildError","buildError","GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM","RUNTIME_DIAGNOSTICS_PARAM","isRecord","isRecord","CONTEXT","CONTEXT","HELPERS","CONTEXT","stringSchema","stringArgsSchema","stringSchema","stringArgsSchema","numberSchema","numberArgsSchema","numberRangeArgsSchema","arraySchema","getByPath","objectSchema","stringArgsSchema","generalConditionsRegistry","stringConditionsRegistry","emailConditionsRegistry","phoneConditionsRegistry","addressConditionsRegistry","dateConditionsRegistry","numberConditionsRegistry","arrayConditionsRegistry","objectConditionsRegistry","formatGeneratorsRegistry","dateGeneratorsRegistry","numberArgsSchema","stringTransformersRegistry","numberTransformersRegistry","arrayTransformersRegistry","objectTransformersRegistry","dateTransformersRegistry","field","buildField","buildBlock","traceComplete","traceComplete","traceBegin","traceBegin","traceComplete","traceBegin","traceComplete","traceComplete","traceComplete","traceComplete","traceComplete","EffectFunctionContextImpl","toOutput","isRenderBlock"],"sources":["../../forge-core/src/authoring/utils/deprecated/createFunctionsRegistry.ts","../../forge-core/src/authoring/types/enums.ts","../../forge-core/src/shared/diagnostics/formatCallsite.ts","../../forge-core/src/engine/errors/DiagnosticErrorFormatter.ts","../../forge-core/src/engine/errors/ForgeBaseError.ts","../../forge-core/src/engine/errors/ForgeAuthoringError.ts","../../forge-core/src/engine/errors/ForgeRegistryDuplicateError.ts","../../forge-core/src/authoring/builders/utils/captureCallsite.ts","../../forge-core/src/authoring/builders/utils/splitKey.ts","../../forge-core/src/authoring/builders/IterableBuilder.ts","../../forge-core/src/authoring/builders/ExpressionBuilder.ts","../../forge-core/src/authoring/builders/GeneratorBuilder.ts","../../forge-core/src/authoring/registries/BaseFunctionRegistry.ts","../../forge-core/src/engine/errors/ForgeRegistryValidationError.ts","../../forge-core/src/engine/chassis/registries/ComponentRegistry.ts","../../forge-core/src/engine/chassis/registries/ScopedComponentRegistry.ts","../../forge-core/src/engine/chassis/registries/FunctionRegistry.ts","../../forge-core/src/engine/chassis/registries/ScopedFunctionRegistry.ts","../../forge-core/src/engine/chassis/work/WorkExecutionError.ts","../../forge-core/src/engine/chassis/tracing/TraceSpan.ts","../../forge-core/src/engine/errors/ForgeInternalError.ts","../../forge-core/src/engine/chassis/work/WorkExecutor.ts","../../forge-core/src/engine/chassis/work/WorkContext.ts","../../forge-core/src/engine/chassis/tracing/TraceSpanSerializer.ts","../../forge-core/src/engine/chassis/compilation/pipeline/CompilationPipelineTraceProjector.ts","../../forge-core/src/engine/chassis/compilation/pipeline/CompilationState.ts","../../forge-core/src/engine/chassis/contracts/work/work.type.ts","../../forge-core/src/engine/chassis/work/workTask.ts","../../forge-core/src/engine/chassis/compilation/pipeline/CompilationPipelineWorkHandler.ts","../../forge-core/src/engine/errors/ForgeSerialisationError.ts","../../forge-core/src/engine/errors/ForgeSchemaError.ts","../../forge-core/src/engine/concerns/dsl-validation/schemas/base.schema.ts","../../forge-core/src/engine/concerns/dsl-validation/schemas/expressions.schema.ts","../../forge-core/src/engine/concerns/dsl-validation/schemas/predicates.schema.ts","../../forge-core/src/engine/concerns/dsl-validation/schemas/structures.schema.ts","../../forge-core/src/shared/diagnostics/DSLPathFormatter.ts","../../forge-core/src/shared/diagnostics/DSLSourceLocator.ts","../../forge-core/src/engine/concerns/dsl-validation/DSLValidator.ts","../../forge-core/src/engine/concerns/dsl-validation/CompilationDslValidationWorkHandler.ts","../../forge-core/src/engine/chassis/compilation/ast/ast-state/NodeIDGenerator.ts","../../forge-core/src/engine/errors/ForgeUnknownNodeTypeError.ts","../../forge-core/src/engine/errors/ForgeInvalidNodeError.ts","../../forge-core/src/engine/chassis/contracts/ast/enums.ts","../../forge-core/src/engine/chassis/contracts/ast/nodes.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/template.ts","../../forge-core/src/components/typeguards.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/structures.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/expressions.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/predicates.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/hooks.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/outcomes.ts","../../forge-core/src/engine/chassis/compilation/ast/nodes/NodeFactory.ts","../../forge-core/src/engine/chassis/compilation/ast/ast-state/ASTNodeIndex.ts","../../forge-core/src/engine/chassis/compilation/ast/ast-state/TemplateNodeIndex.ts","../../forge-core/src/engine/chassis/compilation/ast/ast-state/NodeRegistrationWalker.ts","../../forge-core/src/engine/chassis/compilation/ast/CompilationAstWorkHandler.ts","../../forge-core/src/engine/errors/ForgeReferenceScopeError.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateReferenceScopes.ts","../../forge-core/src/engine/chassis/contracts/ast/structure-nodes.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateSelfScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateAnswerScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateEffectScope.ts","../../forge-core/src/engine/errors/ForgeUnregisteredFunctionError.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateRegisteredFunctions.ts","../../forge-core/src/engine/errors/ForgeFunctionArityError.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateFunctionArity.ts","../../forge-core/src/engine/errors/ForgeUnregisteredComponentError.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateRegisteredComponents.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateValidationScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateOutcomeScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateHookScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateTieBreakerScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateStructureScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateBlockScope.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateFieldCodeUniqueness.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateFunctionArguments.ts","../../forge-core/src/engine/concerns/semantic-analysis/rules/validateContainerTypes.ts","../../forge-core/src/engine/concerns/semantic-analysis/ASTSemanticValidator.ts","../../forge-core/src/engine/concerns/semantic-analysis/CompilationSemanticAnalysisWorkHandler.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/Ancestry.ts","../../forge-core/src/engine/chassis/contracts/models/authoredValue.type.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/AuthoredValueClassifier.ts","../../forge-core/src/engine/chassis/contracts/models/validationRules.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/FieldModelBuilder.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/NodeLabeller.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/OwnershipIndex.ts","../../forge-core/src/shared/routePath.ts","../../forge-core/src/engine/chassis/compilation/analysis/shared/MountInfoAnalyzer.ts","../../forge-core/src/engine/chassis/contracts/ast/outcome-nodes.ts","../../forge-core/src/engine/concerns/reachability/analysis/RequestTimeReferenceAnalyzer.ts","../../forge-core/src/engine/concerns/reachability/analysis/ForwardNavigationAnalyzer.ts","../../forge-core/src/engine/concerns/reachability/analysis/ReachabilityAnalyzer.ts","../../forge-core/src/engine/concerns/answer-cleardown/analysis/AnswerCleardownAnalyzer.ts","../../forge-core/src/engine/concerns/answer-preparation/analysis/AnswerPreparationAnalyzer.ts","../../forge-core/src/engine/concerns/hooks/analysis/HookAnalyzer.ts","../../forge-core/src/engine/concerns/validation/analysis/ValidationAnalyzer.ts","../../forge-core/src/engine/concerns/resolve/analysis/ResolveAnalyzer.ts","../../forge-core/src/engine/concerns/route/analysis/RouteAnalyzer.ts","../../forge-core/src/engine/chassis/compilation/analysis/CompilationModelBuilder.ts","../../forge-core/src/engine/chassis/compilation/analysis/CompilationAnalysisWorkHandler.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/ArrayExpressionToken.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/CallExpressionToken.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/IdentifierName.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/ObjectExpressionToken.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/PositionedCodeToken.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/CodeFragment.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/CodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/AssignmentCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/BlankLineCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/BreakCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/CommentCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ContinueCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/DeclarationCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/DirectiveCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ExpressionCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ForRangeCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/FunctionCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/fragments/FunctionExpressionToken.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/IfCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/PositionedCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ReturnCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ScopeCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/ThrowCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/TryCatchCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/statements/WhileCodeNode.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/CodeGenerator.ts","../../forge-core/src/engine/chassis/compilation/lowering/emitters/FieldCodeEmitter.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/NullishNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/emitters/DiagnosticEmitter.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/ReferenceNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/PredicateNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/PipelineNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/ConditionalNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/MatchNodeCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/expressions/ExpressionDispatcher.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/rendering/SourceRenderer.ts","../../forge-core/src/engine/chassis/compilation/lowering/codegen/rendering/sourceMapEncoder.ts","../../forge-core/src/engine/concerns/render/contracts/renderBlock.brand.ts","../../forge-core/src/engine/chassis/compilation/lowering/generatedFunctionRuntimeLibrary.ts","../../forge-core/src/engine/errors/ForgeCompilationError.ts","../../forge-core/src/engine/errors/ForgeRuntimeEvaluationError.ts","../../forge-core/src/engine/chassis/compilation/lowering/GeneratedFunctionCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/emitters/IteratorLoopEmitter.ts","../../forge-core/src/engine/chassis/compilation/lowering/structures/RuntimeValueCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/structures/ScopedTemplateCompiler.ts","../../forge-core/src/engine/concerns/validation/lowering/StepValidationCompiler.ts","../../forge-core/src/engine/concerns/validation/lowering/EntryValidationCompiler.ts","../../forge-core/src/engine/concerns/reachability/lowering/ReachabilityCompiler.ts","../../forge-core/src/engine/concerns/reachability/lowering/graph/ReachabilityPathAnalyzer.ts","../../forge-core/src/engine/concerns/reachability/lowering/graph/routeTemplateTargetResolver.ts","../../forge-core/src/engine/concerns/reachability/lowering/graph/ReachabilityGraphBuilder.ts","../../forge-core/src/engine/concerns/reachability/lowering/graph/ReachabilityStateProjector.ts","../../forge-core/src/engine/concerns/reachability/lowering/graph/evaluateReachabilityState.ts","../../forge-core/src/engine/concerns/answer-cleardown/lowering/StepFieldInventoryCompiler.ts","../../forge-core/src/engine/concerns/resolve/lowering/StepResolveCompiler.ts","../../forge-core/src/engine/concerns/answer-preparation/lowering/StepAnswerPreparationCompiler.ts","../../forge-core/src/engine/concerns/hooks/lowering/HookLifecycleCompiler.ts","../../forge-core/src/engine/concerns/route/lowering/RouteMetadataCompiler.ts","../../forge-core/src/engine/chassis/compilation/lowering/CodegenOrchestrator.ts","../../forge-core/src/engine/chassis/compilation/lowering/CompilationLoweringWorkHandler.ts","../../forge-core/src/engine/concerns/route/analysis/RouteIndexBuilder.ts","../../forge-core/src/engine/concerns/route/analysis/CompilationRoutesWorkHandler.ts","../../forge-core/src/engine/chassis/compilation/pipeline/CompilationPipelineBootstrap.ts","../../forge-core/src/engine/chassis/compilation/pipeline/CompilationPipeline.ts","../../forge-core/src/engine/PackageInstance.ts","../../forge-core/src/authoring/registries/ConditionRegistry.ts","../../forge-core/src/built-ins/functions/conditions/generalConditions.ts","../../forge-core/src/built-ins/functions/conditions/stringConditions.ts","../../forge-core/src/built-ins/functions/conditions/addressConditions.ts","../../forge-core/src/built-ins/functions/conditions/emailConditions.ts","../../forge-core/src/built-ins/functions/conditions/dateConditions.ts","../../forge-core/src/built-ins/functions/conditions/numberConditions.ts","../../forge-core/src/built-ins/functions/conditions/phoneConditions.ts","../../forge-core/src/built-ins/functions/conditions/arrayConditions.ts","../../forge-core/src/built-ins/functions/conditions/objectConditions.ts","../../forge-core/src/built-ins/functions/conditions/index.ts","../../forge-core/src/authoring/registries/GeneratorRegistry.ts","../../forge-core/src/built-ins/functions/generators/dateGenerators.ts","../../forge-core/src/built-ins/functions/generators/formatGenerators.ts","../../forge-core/src/built-ins/functions/generators/index.ts","../../forge-core/src/authoring/registries/TransformerRegistry.ts","../../forge-core/src/built-ins/functions/transformers/arrayTransformers.ts","../../forge-core/src/built-ins/functions/transformers/dateTransformers.ts","../../forge-core/src/built-ins/functions/transformers/numberTransformers.ts","../../forge-core/src/built-ins/functions/transformers/objectTransformers.ts","../../forge-core/src/built-ins/sanitize.ts","../../forge-core/src/built-ins/functions/transformers/stringTransformers.ts","../../forge-core/src/built-ins/functions/transformers/index.ts","../../forge-core/src/authoring/builders/ReferenceBuilder.ts","../../forge-core/src/authoring/builders/LoopReferenceBuilder.ts","../../forge-core/src/authoring/builders/references.ts","../../forge-core/src/authoring/builders/utils/finaliseBuilders.ts","../../forge-core/src/authoring/builders/structures.ts","../../forge-core/src/authoring/builders/values.ts","../../forge-core/src/authoring/builders/combinators.ts","../../forge-core/src/components/component.ts","../../forge-core/src/built-ins/components/html.ts","../../forge-core/src/built-ins/components/collectionBlock.ts","../../forge-core/src/built-ins/components/templateWrapper.ts","../../forge-core/src/built-ins/components/fragment.ts","../../forge-core/src/built-ins/components/index.ts","../../forge-core/src/shared/ForgeDeprecations.ts","../../forge-core/src/engine/concerns/route/contracts/routeTree.type.ts","../../forge-core/src/engine/errors/ForgeDuplicateRouteError.ts","../../forge-core/src/engine/concerns/route/runtime/RouteTreeBuilder.ts","../../forge-core/src/engine/chassis/registries/MountRegistry.ts","../../forge-core/src/engine/chassis/runtime/context/EffectFunctionContext.ts","../../forge-core/src/engine/concerns/answer-preparation/runtime/FieldAnswerPreparationWorkHandler.ts","../../forge-core/src/engine/concerns/answer-preparation/runtime/AnswerPreparationWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/FieldValidationWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/DomainValidationWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/StepValidationWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/CurrentStepValidationWorkHandler.ts","../../forge-core/src/engine/chassis/work/WorkTaskPropsWalker.ts","../../forge-core/src/engine/concerns/resolve/runtime/ResolveBlockWorkHandler.ts","../../forge-core/src/engine/concerns/resolve/runtime/ResolveBlocksWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/AccessHookNextWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/AccessHookWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/AccessLifecycleWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/AccessHookWhenWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/HookEffectWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/SubmitHookWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/SubmitLifecycleWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/SubmitHookPredicateWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/SubmitBranchWorkHandler.ts","../../forge-core/src/engine/errors/ForgeIteratorBudgetExceededError.ts","../../forge-core/src/engine/chassis/runtime/pipeline/IteratorBudget.ts","../../forge-core/src/engine/chassis/runtime/context/compiledEvaluationContext.ts","../../forge-core/src/engine/concerns/validation/runtime/stepValidationStore.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestState.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestPipelineWorkHandler.ts","../../forge-core/src/engine/chassis/runtime/pipeline/contextSnapshot.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestContextPreparationWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/RequestAccessWorkHandler.ts","../../forge-core/src/engine/concerns/answer-preparation/runtime/RequestAnswerPreparationWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/reachabilityValidityState.ts","../../forge-core/src/engine/concerns/validation/runtime/ReachabilityValiditiesWorkHandler.ts","../../forge-core/src/engine/concerns/reachability/runtime/reachabilityRedirects.ts","../../forge-core/src/engine/concerns/reachability/runtime/RequestReachabilityWorkHandler.ts","../../forge-core/src/engine/concerns/answer-cleardown/runtime/evaluateAnswerCleardown.ts","../../forge-core/src/engine/concerns/answer-cleardown/runtime/RequestAnswerCleardownWorkHandler.ts","../../forge-core/src/engine/concerns/hooks/runtime/RequestSubmitWorkHandler.ts","../../forge-core/src/engine/concerns/validation/runtime/RequestEntryValidationWorkHandler.ts","../../forge-core/src/engine/concerns/resolve/runtime/RequestResolveWorkHandler.ts","../../forge-core/src/engine/concerns/route/runtime/hydrateRouteTree.ts","../../forge-core/src/engine/concerns/route/runtime/RequestRouteTreeWorkHandler.ts","../../forge-core/src/engine/concerns/render/runtime/RenderAssemblePageWorkHandler.ts","../../forge-core/src/engine/concerns/render/runtime/RenderBlockWorkHandler.ts","../../forge-core/src/engine/concerns/render/runtime/RenderBlocksWorkHandler.ts","../../forge-core/src/engine/concerns/render/runtime/RequestRenderWorkHandler.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestPipelineBootstrap.ts","../../forge-core/src/engine/concerns/route/runtime/redirectTarget.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestPipelineTraceProjector.ts","../../forge-core/src/framework/types/responseBindings.type.ts","../../forge-core/src/engine/chassis/runtime/pipeline/RequestPipeline.ts","../../forge-core/src/engine/chassis/tracing/ForgeTraceSinkDispatcher.ts","../../forge-core/src/engine/errors/RegistrationErrorFormatter.ts","../../forge-core/src/engine/errors/ForgeRegistrationError.ts","../../forge-core/src/engine/Forge.ts","../../forge-core/src/engine/concerns/resolve/runtime/typeguards.ts"],"sourcesContent":["import { FunctionRegistryObject } from '../../types/functions.type'\nimport type { FunctionType } from '../../types/enums'\nimport type { FunctionImplementations, FunctionShapeMap, NoDeps } from './defineFunction.type'\n\nfunction extractFactory(entry: unknown): (deps: unknown) => unknown {\n  if (typeof entry === 'function') {\n    return entry as (deps: unknown) => unknown\n  }\n\n  return (entry as { factory: (deps: unknown) => unknown }).factory\n}\n\nfunction extractFunctionType(entry: unknown): FunctionType | undefined {\n  return (entry as { functionType?: FunctionType }).functionType\n}\n\n/**\n * Resolves function factory entries into a registry of ready-to-call evaluators.\n *\n * Each entry can be a plain factory function (back-compat) or an object with\n * `{ factory, functionType?, prepare? }`. The registry decomposes each entry,\n * calls the factory with `deps` to produce an evaluator, and preserves its\n * `functionType` metadata for the engine to use at runtime.\n *\n * @deprecated Use BaseFunctionRegistry.build() instead.\n *\n * @param implementations - Object mapping function names to factory entries\n * @param deps - Dependencies to inject into each factory (omit if none needed)\n *\n * @returns A registry object mapping function names to `{ name, evaluate, functionType? }`\n */\nexport function createFunctionsRegistry<TShapes extends FunctionShapeMap>(\n  implementations: FunctionImplementations<TShapes, NoDeps>,\n): FunctionRegistryObject\nexport function createFunctionsRegistry<TShapes extends FunctionShapeMap, TDeps>(\n  implementations: FunctionImplementations<TShapes, TDeps>,\n  deps: TDeps,\n): FunctionRegistryObject\nexport function createFunctionsRegistry<TShapes extends FunctionShapeMap, TDeps>(\n  implementations: FunctionImplementations<TShapes, TDeps>,\n  deps?: TDeps,\n): FunctionRegistryObject {\n  const resolvedDeps = (deps ?? {}) as TDeps\n  const registry = {} as FunctionRegistryObject\n\n  Object.keys(implementations).forEach(name => {\n    const entry = (implementations as Record<string, unknown>)[name]\n    const factory = extractFactory(entry)\n    const evaluate = factory(resolvedDeps) as FunctionRegistryObject[string]['evaluate']\n    const functionType = extractFunctionType(entry)\n\n    registry[name] = {\n      name,\n      evaluate,\n      functionType,\n    }\n  })\n\n  return registry\n}\n","/**\n * Discriminates the four kinds of registered function a call expression can\n * target: conditions test values, transformers reshape them, generators\n * produce them, and effects perform side effects in hooks.\n */\nexport enum FunctionType {\n  CONDITION = 'FunctionType.Condition',\n  TRANSFORMER = 'FunctionType.Transformer',\n  GENERATOR = 'FunctionType.Generator',\n  EFFECT = 'FunctionType.Effect',\n}\n\n/**\n * Discriminates the structural nodes a form is built from: journeys contain\n * steps, steps contain blocks.\n */\nexport enum StructureType {\n  BLOCK = 'StructureType.Block',\n  JOURNEY = 'StructureType.Journey',\n  STEP = 'StructureType.Step',\n}\n\n/**\n * Distinguishes field blocks, which collect answers, from basic blocks,\n * which only display content.\n */\nexport enum BlockType {\n  FIELD = 'BlockType.field',\n  BASIC = 'BlockType.basic',\n}\n\n/**\n * Discriminates expression nodes: value expressions such as references,\n * pipelines, conditionals, and iterations, plus rule nodes such as\n * validations and tie-breakers.\n */\nexport enum ExpressionType {\n  REFERENCE = 'ExpressionType.Reference',\n  PIPELINE = 'ExpressionType.Pipeline',\n  NULLISH = 'ExpressionType.Nullish',\n  NEXT = 'ExpressionType.Next',\n  VALIDATION = 'ExpressionType.Validation',\n  ITERATE = 'ExpressionType.Iterate',\n  CONDITIONAL = 'ExpressionType.Conditional',\n  MATCH = 'ExpressionType.Match',\n  TIE_BREAKER = 'ExpressionType.TieBreaker',\n}\n\n/**\n * Discriminates the per-item operations an iterate expression can apply to\n * a collection.\n */\nexport enum IteratorType {\n  MAP = 'IteratorType.Map',\n  FILTER = 'IteratorType.Filter',\n  FIND = 'IteratorType.Find',\n  SOME = 'IteratorType.Some',\n  EVERY = 'IteratorType.Every',\n  COUNT = 'IteratorType.Count',\n}\n\n/**\n * Discriminates predicate nodes: a single condition test, or a logical\n * combination of other predicates.\n */\nexport enum PredicateType {\n  TEST = 'PredicateType.Test',\n  AND = 'PredicateType.And',\n  OR = 'PredicateType.Or',\n  XOR = 'PredicateType.Xor',\n  NOT = 'PredicateType.Not',\n}\n\n/**\n * Discriminates the logical combinations of a subject-less condition\n * combinator tree, as used by match branches. Unlike PredicateType, whose\n * TEST leaves carry their own subject, these trees combine bare conditions\n * and take their subject from the surrounding match expression.\n */\nexport enum ConditionCombinatorType {\n  AND = 'ConditionCombinatorType.And',\n  OR = 'ConditionCombinatorType.Or',\n  XOR = 'ConditionCombinatorType.Xor',\n  NOT = 'ConditionCombinatorType.Not',\n}\n\n/**\n * Discriminates lifecycle hooks: access hooks run on every request, submit\n * hooks run on form submission.\n */\nexport enum HookType {\n  ACCESS = 'HookType.Access',\n  SUBMIT = 'HookType.Submit',\n}\n\n/**\n * Discriminates the outcomes a hook can halt with: a redirect or a thrown\n * error.\n */\nexport enum OutcomeType {\n  REDIRECT = 'Outcome.Redirect',\n  THROW_ERROR = 'Outcome.ThrowError',\n}\n","const FRAME_PATTERN = /^\\s+at /\n\nconst MAX_CHAIN_LENGTH = 3\n\nexport const isInternalFrame = (frame: string): boolean =>\n  frame.includes('node:') ||\n  frame.includes('node_modules') ||\n  frame.includes('forge-core/src') ||\n  frame.includes('forge-core/dist') ||\n  frame.includes('forge:compiled/') ||\n  frame.includes('(<anonymous>)')\n\n// Bundler module-wiring helpers (esbuild's __init/__require, webpack's require) —\n// shared by every definition in a module, so they never distinguish one.\nconst BUNDLER_HELPER_PATTERN = /^(?:__init|__require|__commonJS|__esm|__toESM|__webpack_require__) /\n\n/**\n * Formats a captured callsite into the chain of author-facing \"defined at\"\n * frames, innermost first. Frames inside forge-core, node internals, and\n * node_modules are skipped because registry handles are often invoked by\n * forge-internal callers. The chain keeps walking past frames in the capture\n * site's file (wrapper DSL utilities produce several), stops once it has the\n * first frame from a different file, and caps at three entries — enough to\n * read past a wrapper layer to the author's own file without printing the\n * whole capture. Reading `.stack` here triggers V8's lazy trace formatting,\n * so call this only at display time.\n */\nexport const formatCallsiteChain = (callsite: { readonly stack?: string } | undefined): string[] => {\n  const stack = callsite?.stack\n  if (!stack) {\n    return []\n  }\n\n  const frames = extractFrames(stack)\n\n  if (frames.length === 0) {\n    return []\n  }\n\n  const chainFrames = selectAuthorChainFrames(frames)\n\n  if (chainFrames.length === 0) {\n    return [frames[0]]\n  }\n\n  return chainFrames.map(collapseModuleNamedFrame)\n}\n\nconst extractFrames = (stack: string): string[] =>\n  stack\n    .split('\\n')\n    .filter(line => FRAME_PATTERN.test(line))\n    .map(line => line.replace(FRAME_PATTERN, ''))\n\n/**\n * The author-facing chain frames, innermost first: walks past frames in the\n * capture site's file, stops after the first frame from a different file,\n * caps at `MAX_CHAIN_LENGTH`.\n */\nconst selectAuthorChainFrames = (frames: string[]): string[] => {\n  const authorFrames = frames.filter(frame => !isInternalFrame(frame) && !BUNDLER_HELPER_PATTERN.test(frame))\n\n  if (authorFrames.length === 0) {\n    return []\n  }\n\n  const captureSiteFile = frameFile(authorFrames[0])\n  const chain: string[] = []\n\n  authorFrames.some(frame => {\n    chain.push(frame)\n\n    return chain.length >= MAX_CHAIN_LENGTH || frameFile(frame) !== captureSiteFile\n  })\n\n  return chain\n}\n\n// V8 names top-level module frames by module id — `server/forms/index.ts\n// (/app/server/forms/index.ts:40:40)` — so the name restates the path. Collapse\n// those to the bare location, matching the anonymous-frame grammar.\nconst collapseModuleNamedFrame = (frame: string): string => {\n  const match = /^(.+) \\((.+):(\\d+:\\d+)\\)$/.exec(frame)\n\n  if (match === null) {\n    return frame\n  }\n\n  const [, name, file, position] = match\n\n  return file.endsWith(name) ? `${file}:${position}` : frame\n}\n\n/**\n * Formats a captured callsite into the single innermost author-facing frame —\n * the first entry of `formatCallsiteChain`.\n */\nexport const formatCallsite = (callsite: { readonly stack?: string } | undefined): string | undefined => {\n  const chain = formatCallsiteChain(callsite)\n\n  return chain.length > 0 ? chain[0] : undefined\n}\n\nexport interface CallsitePosition {\n  readonly file: string\n  readonly line: number\n  readonly column: number\n}\n\n/**\n * Resolves a captured callsite to the structured positions (1-based line and\n * column) of the author chain frames `formatCallsiteChain` renders, innermost\n * first. Every chain frame is a legitimate breakpoint home: a node built\n * inside a shared wiring helper is \"defined at\" both the helper's line and\n * the line that called the helper. Unlike the display formatters there is no\n * fallback to an internal frame when every frame is filtered — a source-map\n * entry pointing into forge internals is worse than none. Reading `.stack`\n * triggers V8's lazy trace formatting, so call this at codegen time only.\n */\nexport const resolveCallsitePositionChain = (callsite: { readonly stack?: string } | undefined): CallsitePosition[] => {\n  const stack = callsite?.stack\n  if (!stack) {\n    return []\n  }\n\n  return selectAuthorChainFrames(extractFrames(stack))\n    .map(parseFramePosition)\n    .filter(position => position !== undefined)\n}\n\nconst parseFramePosition = (frame: string): CallsitePosition | undefined => {\n  const location = /\\((.+)\\)$/.exec(frame)?.[1] ?? frame\n  const match = /^(.+):(\\d+):(\\d+)$/.exec(location)\n\n  if (match === null) {\n    return undefined\n  }\n\n  return { file: match[1], line: Number(match[2]), column: Number(match[3]) }\n}\n\nconst frameFile = (frame: string): string => {\n  const location = /\\((.+)\\)$/.exec(frame)?.[1] ?? frame\n\n  return location.replace(/:\\d+:\\d+$/, '')\n}\n","import { isInternalFrame } from '../../shared/diagnostics/formatCallsite'\n\nexport interface RuntimeDiagnosticFields {\n  readonly phase: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n}\n\nconst FRAME_PATTERN = /^\\s+at /\n\n/**\n * Renders the author-facing sections of a forge error's `stack`: the\n * diagnostics block and the folded frame list. Indentation is deliberate —\n * the block header sits at frame depth (4 spaces) with fields nested at 6, so\n * Node's `[cause]:` (fixed at 2 spaces in `util.inspect`) visibly outdents as\n * a sibling of the whole error instead of reading as another diagnostics\n * field.\n */\nexport default class DiagnosticErrorFormatter {\n  static formatRuntimeDiagnostics(diagnostics: RuntimeDiagnosticFields): string {\n    const formattedFields = [\n      { label: 'Phase', value: diagnostics.phase },\n      { label: 'Path', value: diagnostics.formattedPath },\n      { label: 'Function', value: diagnostics.functionName },\n      { label: 'Type', value: diagnostics.functionType },\n    ]\n      .filter(field => field.value !== undefined)\n      .map(field => `      ${field.label}: ${field.value}`)\n\n    return ['    Forge diagnostics:', ...formattedFields].join('\\n')\n  }\n\n  static extractStackFrames(stack: string | undefined): string[] {\n    if (stack === undefined) {\n      return []\n    }\n\n    return stack\n      .split('\\n')\n      .filter(line => FRAME_PATTERN.test(line))\n      .map(line => line.replace(FRAME_PATTERN, ''))\n  }\n\n  /**\n   * Collapses each consecutive run of forge-internal frames into one summary\n   * line naming the run's first and last frame. Author frames always render.\n   * The summary line deliberately does not match the `at ...` frame grammar so\n   * error trackers never ingest it as an execution frame.\n   */\n  static foldStackFrames(frames: string[]): string[] {\n    const folded: string[] = []\n    let internalRun: string[] = []\n\n    const flushRun = (): void => {\n      if (internalRun.length === 0) {\n        return\n      }\n\n      folded.push(DiagnosticErrorFormatter.formatFoldedRun(internalRun))\n      internalRun = []\n    }\n\n    frames.forEach(frame => {\n      if (isInternalFrame(frame)) {\n        internalRun.push(frame)\n\n        return\n      }\n\n      flushRun()\n      folded.push(`    at ${frame}`)\n    })\n    flushRun()\n\n    return folded\n  }\n\n  private static formatFoldedRun(run: string[]): string {\n    if (run.length === 1) {\n      return `    ... 1 forge frame (${frameName(run[0])}) — FORGE_FULL_STACK=1 to expand`\n    }\n\n    const summary = `${frameName(run[0])} → ${frameName(run[run.length - 1])}`\n\n    return `    ... ${run.length} forge frames (${summary}) — FORGE_FULL_STACK=1 to expand`\n  }\n}\n\nconst frameName = (frame: string): string => {\n  const parenIndex = frame.indexOf(' (')\n\n  return parenIndex === -1 ? frame : frame.slice(0, parenIndex)\n}\n","import DiagnosticErrorFormatter from './DiagnosticErrorFormatter'\n\nexport interface ForgeErrorDiagnostics {\n  /** Human-readable path through the journey DSL */\n  readonly formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  readonly callsite?: { readonly stack?: string }\n}\n\n/**\n * Base class for every error the engine throws. Owns the diagnostic fields\n * shared across the family (`formattedPath`, `callsite`), stamps `name` from\n * the concrete class, and owns `stack` rendering: raw frames are captured once\n * at construction (with constructor frames trimmed) and the display string —\n * folded forge-internal frames, defined-at frames, diagnostics block — is\n * assembled lazily on first read, so errors that get caught and handled never\n * pay for formatting. The unfolded original stays reachable via the\n * non-enumerable `rawStack`, and `FORGE_FULL_STACK=1` renders every frame.\n */\nexport default abstract class ForgeBaseError extends Error {\n  readonly formattedPath?: string\n\n  readonly callsite?: { readonly stack?: string }\n\n  declare readonly rawStack: string | undefined\n\n  private readonly rawStackHolder: { stack?: string }\n\n  protected constructor(message: string, diagnostics?: ForgeErrorDiagnostics) {\n    super(message)\n    this.name = new.target.name\n    this.formattedPath = diagnostics?.formattedPath\n    this.callsite = diagnostics?.callsite\n    const canCapture = typeof Error.captureStackTrace === 'function'\n\n    this.rawStackHolder = canCapture ? {} : { stack: this.stack }\n\n    if (canCapture) {\n      Error.captureStackTrace(this.rawStackHolder, new.target)\n    }\n\n    Object.defineProperty(this, 'stack', {\n      get: () => this.renderStack(),\n      set: (value: string | undefined) => {\n        Object.defineProperty(this, 'stack', { value, writable: true, configurable: true, enumerable: false })\n      },\n      configurable: true,\n      enumerable: false,\n    })\n    Object.defineProperty(this, 'rawStack', {\n      get: () => this.renderRawStack(),\n      configurable: true,\n      enumerable: false,\n    })\n  }\n\n  /** ForgeInternalError opts out: when the engine itself is broken, the internals are the story. */\n  protected get foldsInternalStackFrames(): boolean {\n    return true\n  }\n\n  /** The stack string whose frames form the rendered body — subclasses may substitute a cause's stack. */\n  protected stackBodySource(): string | undefined {\n    return this.rawStackHolder.stack\n  }\n\n  /** Definition-site frames rendered after the execution frames as `at [defined] ...` lines. */\n  protected definedAtStackFrames(): string[] {\n    return []\n  }\n\n  /** The `Forge diagnostics:` block appended after the frames, if the subclass carries one. */\n  protected formatDiagnosticsBlock(): string | undefined {\n    return undefined\n  }\n\n  private renderStack(): string {\n    const frames = DiagnosticErrorFormatter.extractStackFrames(this.stackBodySource())\n    const foldDisabled = process.env.FORGE_FULL_STACK === '1' || !this.foldsInternalStackFrames\n    const frameLines = foldDisabled\n      ? frames.map(frame => `    at ${frame}`)\n      : DiagnosticErrorFormatter.foldStackFrames(frames)\n    const definedLines = this.definedAtStackFrames().map(frame => `    at [defined] ${frame}`)\n    const diagnosticsBlock = this.formatDiagnosticsBlock()\n\n    const sections = [\n      [`${this.name}: ${this.message}`, ...frameLines].join('\\n'),\n      definedLines.length > 0 ? definedLines.join('\\n') : undefined,\n      diagnosticsBlock,\n    ].filter(section => section !== undefined)\n\n    return sections.join('\\n\\n')\n  }\n\n  private renderRawStack(): string | undefined {\n    const rawFrames = DiagnosticErrorFormatter.extractStackFrames(this.rawStackHolder.stack)\n\n    return [`${this.name}: ${this.message}`, ...rawFrames.map(frame => `    at ${frame}`)].join('\\n')\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeAuthoringErrorOptions {\n  /** Human-readable error message */\n  message: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending definition was written */\n  callsite?: { readonly stack?: string }\n}\n\n/**\n * The authoring API was misused in a way the schema never gets to see -\n * thrown while builders and DSL helpers are still assembling the definition.\n */\nexport default class ForgeAuthoringError extends ForgeBaseError {\n  constructor(options: ForgeAuthoringErrorOptions) {\n    super(options.message, options)\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeRegistryDuplicateErrorOptions {\n  /** Type of registry (function or component) */\n  registryType: 'function' | 'component'\n  /** Name or variant of the item being registered */\n  itemName: string\n  /** Optional additional message */\n  message?: string\n}\n\nexport default class ForgeRegistryDuplicateError extends ForgeBaseError {\n  readonly registryType: 'function' | 'component'\n\n  readonly itemName: string\n\n  constructor(options: ForgeRegistryDuplicateErrorOptions) {\n    super(options.message ?? `Duplicate ${options.registryType} registration: \"${options.itemName}\"`)\n    this.registryType = options.registryType\n    this.itemName = options.itemName\n  }\n}\n","export interface Callsite {\n  readonly stack?: string\n}\n\n/**\n * Captures the caller's stack without formatting it: V8 defines `.stack` as a\n * lazy accessor, so the (expensive) trace formatting only happens if something\n * actually reads it. Do not read `.stack` here.\n *\n * @param skip - Frames above this function are kept; it and everything below are dropped\n */\nexport const captureCallsite = (skip: (...args: any[]) => unknown): Callsite => {\n  if (typeof Error.captureStackTrace !== 'function') {\n    return {}\n  }\n\n  const site: Callsite = {}\n  const previousLimit = Error.stackTraceLimit\n\n  // Deep enough that wrapper DSL layers (curried builders, native Array.map\n  // frames) cannot eat the whole budget before the author's own frame lands.\n  Error.stackTraceLimit = 15\n  try {\n    Error.captureStackTrace(site, skip)\n  } finally {\n    Error.stackTraceLimit = previousLimit\n  }\n\n  return site\n}\n\n/**\n * Attaches a captured callsite to an object as a non-enumerable `__callsite`.\n * configurable + writable so finalisation walks can re-stamp copies.\n */\nexport const stampCallsite = (target: unknown, callsite: Callsite): void => {\n  if (target === null || typeof target !== 'object' || !('stack' in callsite)) {\n    return\n  }\n\n  Object.defineProperty(target, '__callsite', {\n    value: callsite,\n    enumerable: false,\n    configurable: true,\n    writable: true,\n  })\n}\n","/**\n * Split a key string into path segments.\n * 'user.name' -> ['user', 'name']\n * 'simple' -> ['simple']\n */\nexport const splitKey = (key: string): string[] => (key.includes('.') ? key.split('.') : [key])\n","import {\n  ConditionFunctionExpr,\n  FilterIteratorConfig,\n  FindIteratorConfig,\n  IterateExpr,\n  IteratorConfig,\n  SomeIteratorConfig,\n  EveryIteratorConfig,\n  CountIteratorConfig,\n  CollectionPredicateExpr,\n  NullishExpr,\n  MapIteratorConfig,\n  PipelineExpr,\n  PredicateTestExpr,\n  ReferenceExpr,\n  TransformerFunctionExpr,\n  ResolvableValue,\n} from '../types/expressions.type'\nimport { ExpressionType, IteratorType, PredicateType } from '../types/enums'\nimport { ExpressionBuilder } from './ExpressionBuilder'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { splitKey } from './utils/splitKey'\n\n/**\n * Immutable builder for chainable iterate expressions.\n *\n * Created by .each() on ReferenceBuilder or ExpressionBuilder.\n * Supports chaining: .each().each().pipe()\n *\n * Enables fluent API patterns like:\n * - Data('items').each(Iterator.Map({ ... }))\n * - Data('items').each(Iterator.Filter(...)).each(Iterator.Map(...))\n * - Data('items').each(Iterator.Map({ ... })).pipe(Transformer.Array.Slice(0, 10))\n *\n * Key design decisions:\n * - Immutable: Each method returns a NEW instance\n * - Chainable: Multiple .each() calls compose iterators\n * - Escapable: .pipe() exits iteration mode to operate on the result array\n *\n * @internal Exposed to authors via the ChainableIterable interface.\n */\nexport class IterableBuilder {\n  readonly nodeKind = 'forge-builder' as const\n\n  private readonly expression: IterateExpr\n\n  private readonly negated: boolean\n\n  private constructor(expr: IterateExpr, negate: boolean) {\n    this.expression = expr\n    this.negated = negate\n  }\n\n  /**\n   * Create an iterable builder from a source and iterator.\n   */\n  static create(input: ResolvableValue, iterator: IteratorConfig): IterableBuilder {\n    return new IterableBuilder(\n      {\n        type: ExpressionType.ITERATE,\n        input,\n        iterator,\n      },\n      false,\n    )\n  }\n\n  /**\n   * Get the underlying expression.\n   */\n  get expr(): IterateExpr {\n    return this.expression\n  }\n\n  /**\n   * Build the final expression.\n   * Called automatically by finaliseBuilders().\n   */\n  build(): IterateExpr {\n    return this.expression\n  }\n\n  /**\n   * Chain a Find iterator.\n   * Returns an ExpressionBuilder since Find returns a single item, not an array.\n   *\n   * @example\n   * Data('items')\n   *   .each(Iterator.Filter(...))\n   *   .each(Iterator.Find(...))\n   *   .path('name')  // Navigate into the found item\n   */\n  each(iterator: FindIteratorConfig): ExpressionBuilder<ReferenceExpr>\n\n  /** Test the collection directly as a predicate. */\n  each(iterator: SomeIteratorConfig | EveryIteratorConfig): CollectionPredicateExpr\n\n  /** Count matching items and continue with the resulting number. */\n  each(iterator: CountIteratorConfig): ExpressionBuilder<IterateExpr>\n\n  /**\n   * Chain a Map or Filter iterator.\n   * Returns an IterableBuilder that can chain more .each() calls.\n   *\n   * @example\n   * Data('items')\n   *   .each(Iterator.Filter(Item().path('active').match(Condition.IsTrue())))\n   *   .each(Iterator.Map({ label: Item().path('name') }))\n   */\n  each(iterator: MapIteratorConfig | FilterIteratorConfig): IterableBuilder\n\n  /**\n   * Chain another iterator operation.\n   */\n  each(\n    iterator: IteratorConfig,\n  ): IterableBuilder | ExpressionBuilder<ReferenceExpr> | ExpressionBuilder<IterateExpr> | CollectionPredicateExpr {\n    if (iterator.type === IteratorType.COUNT) {\n      const expression: IterateExpr = { type: ExpressionType.ITERATE, input: this.expression, iterator }\n      const builder = ExpressionBuilder.from(expression)\n\n      stampCallsite(builder, captureCallsite(this.each))\n\n      return builder\n    }\n\n    if (iterator.type === IteratorType.SOME || iterator.type === IteratorType.EVERY) {\n      const predicate: CollectionPredicateExpr = { type: ExpressionType.ITERATE, input: this.expression, iterator }\n\n      stampCallsite(predicate, captureCallsite(this.each))\n\n      return predicate\n    }\n\n    if (iterator.type === IteratorType.FIND) {\n      // Find returns a single item - wrap in a reference with empty path\n      // so .path() works naturally\n      const iterateExpr: IterateExpr = {\n        type: ExpressionType.ITERATE,\n        input: this.expression,\n        iterator,\n      }\n      const referenceExpr: ReferenceExpr = {\n        type: ExpressionType.REFERENCE,\n        base: iterateExpr,\n        path: [],\n      }\n\n      return ExpressionBuilder.from(referenceExpr)\n    }\n\n    return IterableBuilder.create(this.expression, iterator)\n  }\n\n  /**\n   * Transform the output array through a pipeline.\n   * Exits iteration mode - operates on the whole result array.\n   *\n   * @example\n   * Data('items')\n   *   .each(Iterator.Map(Item().path('name')))\n   *   .pipe(Transformer.Array.Slice(0, 10))\n   */\n  pipe(...steps: TransformerFunctionExpr[]): ExpressionBuilder<PipelineExpr> {\n    return ExpressionBuilder.pipeline(this.expression, steps)\n  }\n\n  /** Uses the fallback only when the value is null or undefined, like `??`. */\n  nullish(fallback: ResolvableValue | undefined): ExpressionBuilder<NullishExpr> {\n    const expression: NullishExpr = {\n      type: ExpressionType.NULLISH,\n      input: this.expression,\n      ...(fallback !== undefined && { fallback }),\n    }\n    const builder = ExpressionBuilder.from(expression)\n\n    stampCallsite(builder, captureCallsite(this.nullish))\n\n    return builder\n  }\n\n  /**\n   * Navigate into a property of the iteration result.\n   * Useful after Iterator.Find() to extract a specific property from the found item.\n   *\n   * Creates a ReferenceExpr with the iterate expression as its base,\n   * which evaluates the iteration first and then navigates into the result.\n   *\n   * @param key - Property path to navigate into (supports dot notation)\n   * @returns ExpressionBuilder wrapping a ReferenceExpr\n   *\n   * @example\n   * // Find an item and get its 'goals' property\n   * Literal(areasOfNeed)\n   *   .each(Iterator.Find(Item().path('slug').match(Condition.Equals(Params('area')))))\n   *   .path('goals')\n   *\n   * @example\n   * // Nested path navigation\n   * Data('users')\n   *   .each(Iterator.Find(...))\n   *   .path('profile.settings')\n   */\n  path(key: string): ExpressionBuilder<ReferenceExpr> {\n    const referenceExpr: ReferenceExpr = {\n      type: ExpressionType.REFERENCE,\n      base: this.expression,\n      path: splitKey(key),\n    }\n\n    return ExpressionBuilder.from(referenceExpr)\n  }\n\n  /**\n   * Test the output array against a condition.\n   * Terminal operation - returns a plain PredicateTestExpr.\n   *\n   * @example\n   * Data('items')\n   *   .each(Iterator.Filter(...))\n   *   .match(Condition.Array.IsEmpty())\n   */\n  match(condition: ConditionFunctionExpr<any>): PredicateTestExpr {\n    const predicate: PredicateTestExpr = {\n      type: PredicateType.TEST,\n      subject: this.expression,\n      negate: this.negated,\n      condition,\n    }\n\n    stampCallsite(predicate, captureCallsite(this.match))\n\n    return predicate\n  }\n\n  /**\n   * Negate the next condition test.\n   * Returns a new builder with toggled negation.\n   *\n   * @example\n   * Data('items')\n   *   .each(Iterator.Filter(...))\n   *   .not.match(Condition.Array.IsEmpty())\n   */\n  get not(): IterableBuilder {\n    return new IterableBuilder(this.expression, !this.negated)\n  }\n}\n","import {\n  ConditionFunctionExpr,\n  FilterIteratorConfig,\n  FindIteratorConfig,\n  IteratorConfig,\n  SomeIteratorConfig,\n  EveryIteratorConfig,\n  CountIteratorConfig,\n  CollectionPredicateExpr,\n  NullishExpr,\n  IterateExpr,\n  MapIteratorConfig,\n  PipelineExpr,\n  PredicateTestExpr,\n  ReferenceExpr,\n  TransformerFunctionExpr,\n  ResolvableValue,\n} from '../types/expressions.type'\nimport { ExpressionType, IteratorType, PredicateType } from '../types/enums'\nimport { IterableBuilder } from './IterableBuilder'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { splitKey } from './utils/splitKey'\n\n/**\n * Immutable builder for creating chainable value expressions.\n *\n * Enables fluent API patterns like:\n * - Answer('email').pipe(Transformer.String.Trim).match(Condition.IsRequired())\n * - Self().not.match(Condition.String.IsEmpty())\n * - Answer('quantity').pipe(Transformer.Number.Parse).not.match(Condition.Number.LessThan(0))\n *\n * Key design decisions:\n * - Immutable: Each method returns a NEW instance\n * - Type-safe: Full TypeScript inference throughout chains\n * - Buildable: Implements build() for automatic finalization via finaliseBuilders()\n *\n * @internal Exposed to authors via the ChainableExpr interface.\n */\nexport class ExpressionBuilder<T extends ResolvableValue> {\n  readonly nodeKind = 'forge-builder' as const\n\n  private readonly expression: T\n\n  private readonly negate: boolean\n\n  private constructor(expr: T, negate: boolean) {\n    this.expression = expr\n    this.negate = negate\n  }\n\n  /**\n   * Create a builder from any value expression.\n   */\n  static from<E extends ResolvableValue>(expr: E): ExpressionBuilder<E> {\n    return new ExpressionBuilder(expr, false)\n  }\n\n  /**\n   * Create a builder wrapping a pipeline expression.\n   */\n  static pipeline(input: ResolvableValue, steps: TransformerFunctionExpr[]): ExpressionBuilder<PipelineExpr> {\n    return new ExpressionBuilder(\n      {\n        type: ExpressionType.PIPELINE,\n        input,\n        steps,\n      },\n      false,\n    )\n  }\n\n  /**\n   * Get the underlying expression.\n   */\n  get expr(): T {\n    return this.expression\n  }\n\n  /**\n   * Build the final expression.\n   * Called automatically by finaliseBuilders().\n   */\n  build(): T {\n    return this.expression\n  }\n\n  /**\n   * Transform the value through a pipeline of transformers.\n   * Each call creates a nested pipeline (input is the current expression).\n   *\n   * @example\n   * Answer('email').pipe(\n   *   Transformer.String.Trim,\n   *   Transformer.String.ToLowerCase,\n   * )\n   */\n  pipe(...steps: TransformerFunctionExpr[]): ExpressionBuilder<PipelineExpr> {\n    return ExpressionBuilder.pipeline(this.expression, steps)\n  }\n\n  /** Uses the fallback only when the value is null or undefined, like `??`. */\n  nullish(fallback: ResolvableValue | undefined): ExpressionBuilder<NullishExpr> {\n    const expression: NullishExpr = {\n      type: ExpressionType.NULLISH,\n      input: this.expression,\n      ...(fallback !== undefined && { fallback }),\n    }\n    const builder = ExpressionBuilder.from(expression)\n\n    stampCallsite(builder, captureCallsite(this.nullish))\n\n    return builder\n  }\n\n  /**\n   * Navigate into a property of the expression result.\n   * Creates a ReferenceExpr with this expression as its base.\n   *\n   * @param key - Property path to navigate into (supports dot notation)\n   * @returns ExpressionBuilder wrapping a ReferenceExpr\n   *\n   * @example\n   * // After a Find, navigate into the result\n   * Data('users').each(Iterator.Find(...)).path('profile.name')\n   */\n  path(key: string): ExpressionBuilder<ReferenceExpr> {\n    const referenceExpr: ReferenceExpr = {\n      type: ExpressionType.REFERENCE,\n      base: this.expression,\n      path: splitKey(key),\n    }\n\n    return ExpressionBuilder.from(referenceExpr)\n  }\n\n  /**\n   * Enter per-item iteration mode with a Find iterator.\n   * Returns an ExpressionBuilder since Find returns a single item, not an array.\n   *\n   * @example\n   * Data('users').each(Iterator.Find(Item().path('id').match(Condition.Equals(Params('userId')))))\n   *   .path('name')  // Navigate into the found item\n   */\n  each(iterator: FindIteratorConfig): ExpressionBuilder<ReferenceExpr>\n\n  /** Test the collection directly as a predicate. */\n  each(iterator: SomeIteratorConfig | EveryIteratorConfig): CollectionPredicateExpr\n\n  /** Count matching items and continue with the resulting number. */\n  each(iterator: CountIteratorConfig): ExpressionBuilder<IterateExpr>\n\n  /**\n   * Enter per-item iteration mode with a Map or Filter iterator.\n   * Returns an IterableBuilder that can chain more .each() calls or exit via .pipe().\n   *\n   * @example\n   * Literal(someArray).each(Iterator.Map(Item().path('name')))\n   */\n  each(iterator: MapIteratorConfig | FilterIteratorConfig): IterableBuilder\n\n  /**\n   * Enter per-item iteration mode with an iterator.\n   */\n  each(\n    iterator: IteratorConfig,\n  ): IterableBuilder | ExpressionBuilder<ReferenceExpr> | ExpressionBuilder<IterateExpr> | CollectionPredicateExpr {\n    if (iterator.type === IteratorType.COUNT) {\n      const expression: IterateExpr = { type: ExpressionType.ITERATE, input: this.expression, iterator }\n      const builder = ExpressionBuilder.from(expression)\n\n      stampCallsite(builder, captureCallsite(this.each))\n\n      return builder\n    }\n\n    if (iterator.type === IteratorType.SOME || iterator.type === IteratorType.EVERY) {\n      const predicate: CollectionPredicateExpr = { type: ExpressionType.ITERATE, input: this.expression, iterator }\n\n      stampCallsite(predicate, captureCallsite(this.each))\n\n      return predicate\n    }\n\n    if (iterator.type === IteratorType.FIND) {\n      // Find returns a single item - wrap in a reference with empty path\n      // so .path() works naturally\n      const iterateExpr = {\n        type: ExpressionType.ITERATE as const,\n        input: this.expression,\n        iterator,\n      }\n      const referenceExpr: ReferenceExpr = {\n        type: ExpressionType.REFERENCE,\n        base: iterateExpr,\n        path: [],\n      }\n\n      return ExpressionBuilder.from(referenceExpr)\n    }\n\n    return IterableBuilder.create(this.expression, iterator)\n  }\n\n  /**\n   * Test the value against a condition.\n   * Terminal operation - returns a plain PredicateTestExpr.\n   *\n   * @example\n   * Answer('age').match(Condition.Number.GreaterThan(18))\n   * Self().not.match(Condition.IsRequired())\n   */\n  match(condition: ConditionFunctionExpr<any>): PredicateTestExpr {\n    const predicate: PredicateTestExpr = {\n      type: PredicateType.TEST,\n      subject: this.expression,\n      negate: this.negate,\n      condition,\n    }\n\n    stampCallsite(predicate, captureCallsite(this.match))\n\n    return predicate\n  }\n\n  /**\n   * Negate the next condition test.\n   * Returns a new builder with toggled negation.\n   *\n   * @example\n   * Self().not.match(Condition.IsRequired())  // negate: true\n   * Self().not.not.match(Condition.IsRequired())  // negate: false (double negation)\n   */\n  get not(): ExpressionBuilder<T> {\n    return new ExpressionBuilder(this.expression, !this.negate)\n  }\n}\n","import { FunctionType, PredicateType, ExpressionType } from '../types/enums'\nimport {\n  ConditionFunctionExpr,\n  GeneratorFunctionExpr,\n  PipelineExpr,\n  NullishExpr,\n  PredicateTestExpr,\n  TransformerFunctionExpr,\n  ResolvableValue,\n} from '../types/expressions.type'\nimport { ExpressionBuilder } from './ExpressionBuilder'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { ChainableGenerator, ChainableNegation } from './types'\n\n/**\n * Immutable builder for creating generator function expressions.\n *\n * Generators produce values without requiring input, unlike conditions and transformers.\n * They can be used standalone, chained with transformers via pipelines, or tested with conditions.\n *\n * @example\n * // Standalone generator\n * Generator.Date.Now()\n *\n * @example\n * // Generator with pipeline\n * Generator.Date.Now().pipe(Transformer.Date.AddDays(7))\n *\n * @example\n * // Generator with condition\n * Generator.Date.Now().match(Condition.Date.IsFutureDate())\n *\n * @template A - The argument types for the generator function\n *\n * @internal Exposed to authors via the ChainableGenerator interface.\n */\nexport class GeneratorBuilder<A extends ResolvableValue[]> implements ChainableGenerator {\n  readonly nodeKind = 'forge-builder' as const\n\n  // The marker must exist on the class type so builders pass the weak-type\n  // check on Resolvable<T> argument slots; it is type-only and never set.\n  declare readonly __resolves?: any\n\n  private readonly expression: GeneratorFunctionExpr<A>\n\n  private readonly negated: boolean\n\n  private constructor(expr: GeneratorFunctionExpr<A>, negate: boolean = false) {\n    this.expression = expr\n    this.negated = negate\n  }\n\n  /**\n   * Create a new GeneratorBuilder with the given function name and arguments.\n   *\n   * @param name - The name of the generator function (must be registered)\n   * @param args - Arguments to pass to the generator function\n   */\n  static create<A extends ResolvableValue[]>(name: string, args: A): GeneratorBuilder<A> {\n    return new GeneratorBuilder(\n      {\n        type: FunctionType.GENERATOR,\n        name,\n        arguments: args,\n      },\n      false,\n    )\n  }\n\n  /**\n   * Get the underlying generator expression.\n   */\n  get expr(): GeneratorFunctionExpr<A> {\n    return this.expression\n  }\n\n  /**\n   * Build the final generator function expression.\n   * Called automatically by finaliseBuilders().\n   */\n  build(): GeneratorFunctionExpr<A> {\n    return this.expression\n  }\n\n  /**\n   * Transform the generated value through a pipeline of transformers.\n   * Creates a PipelineExpr with this generator as the input.\n   *\n   * @param steps - Transformer functions to apply sequentially\n   * @returns An ExpressionBuilder wrapping the pipeline\n   *\n   * @example\n   * Generator.Date.Now().pipe(\n   *   Transformer.Date.AddDays(7),\n   *   Transformer.Date.Format('YYYY-MM-DD')\n   * )\n   */\n  pipe(...steps: TransformerFunctionExpr[]): ExpressionBuilder<PipelineExpr> {\n    return ExpressionBuilder.pipeline(this.expression, steps)\n  }\n\n  /** Uses the fallback only when the value is null or undefined, like `??`. */\n  nullish(fallback: ResolvableValue | undefined): ExpressionBuilder<NullishExpr> {\n    const expression: NullishExpr = {\n      type: ExpressionType.NULLISH,\n      input: this.expression,\n      ...(fallback !== undefined && { fallback }),\n    }\n    const builder = ExpressionBuilder.from(expression)\n\n    stampCallsite(builder, captureCallsite(this.nullish))\n\n    return builder\n  }\n\n  /**\n   * Test the generated value against a condition.\n   * Terminal operation - returns a plain PredicateTestExpr.\n   *\n   * @example\n   * Generator.Date.Now().match(Condition.Date.IsFutureDate())\n   */\n  match(condition: ConditionFunctionExpr<any>): PredicateTestExpr {\n    const predicate: PredicateTestExpr = {\n      type: PredicateType.TEST,\n      subject: this.expression,\n      negate: this.negated,\n      condition,\n    }\n\n    stampCallsite(predicate, captureCallsite(this.match))\n\n    return predicate\n  }\n\n  /**\n   * Negate the next condition test.\n   * Returns a new builder with toggled negation.\n   *\n   * @example\n   * Generator.Date.Now().not.match(Condition.Date.IsPast())\n   */\n  get not(): ChainableNegation {\n    return new GeneratorBuilder(this.expression, !this.negated)\n  }\n}\n","import { z, type ZodType } from 'zod'\nimport { FunctionType } from '../types/enums'\nimport ForgeAuthoringError from '../../engine/errors/ForgeAuthoringError'\nimport ForgeRegistryDuplicateError from '../../engine/errors/ForgeRegistryDuplicateError'\nimport { GeneratorBuilder } from '../builders/GeneratorBuilder'\nimport { captureCallsite, stampCallsite } from '../builders/utils/captureCallsite'\nimport type { FunctionRegistryObject } from '../types/functions.type'\n\nexport interface RegistrationOptions {\n  inputSchema?: ZodType\n  argumentsSchema?: ZodType\n  outputSchema?: ZodType\n  prepare?: (...args: any[]) => any[]\n}\n\ninterface RegistrationWithFactory<TDeps = any> extends RegistrationOptions {\n  factory: (deps: TDeps) => (...args: any[]) => any\n}\n\ninterface StoredRegistration {\n  name: string\n  inputSchema?: ZodType\n  argumentsSchema?: ZodType\n  outputSchema?: ZodType\n  prepare?: (...args: any[]) => any[]\n  factory: (deps: any) => (...args: any[]) => any\n}\n\nexport const CONDITION_OUTPUT_SCHEMA = z.compile(z.boolean())\n\n// Each rolldown entry point (core, core/authoring) inlines its own copy of this class, so\n// `instanceof` fails when an instance from one bundle reaches a check in another. The\n// Symbol.for brand is process-global, so it survives the duplication.\n//\n// TODO: Probably should delete the brand/symbol machinery once the deprecated\n// implementations-map form of `functions` is removed — at that point the engine only needs\n// Array.isArray before calling .build(), and never needs to identify a registry.\nconst REGISTRY_BRAND = Symbol.for('forge:BaseFunctionRegistry')\n\nexport function isFunctionRegistry<T = any>(value: unknown): value is BaseFunctionRegistry<T> {\n  return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[REGISTRY_BRAND] === true\n}\n\nexport abstract class BaseFunctionRegistry<TDeps = Record<string, never>> {\n  readonly [REGISTRY_BRAND] = true\n\n  private readonly registrations = new Map<string, StoredRegistration>()\n\n  private anonymousCounter = 0\n\n  constructor(\n    private readonly functionType: FunctionType,\n    private readonly defaultOutputSchema?: ZodType,\n  ) {}\n\n  protected nextAnonymousName(): string {\n    return `__anon_${this.anonymousCounter++}`\n  }\n\n  protected parseArgs(\n    first: string | RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    second?: RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    third?: (deps: TDeps) => (...args: any[]) => any,\n  ): { name: string; options: RegistrationOptions; factory: (deps: TDeps) => (...args: any[]) => any } {\n    if (typeof first === 'function') {\n      return { name: first.name || this.nextAnonymousName(), options: {}, factory: first }\n    }\n\n    if (typeof first !== 'string') {\n      const factory = second as (deps: TDeps) => (...args: any[]) => any\n\n      return { name: factory.name || this.nextAnonymousName(), options: first, factory }\n    }\n\n    if (typeof second === 'function') {\n      return { name: first, options: {}, factory: second }\n    }\n\n    const options = second ?? {}\n\n    return { name: first, options, factory: third ?? this.requireEmbeddedFactory(first, options) }\n  }\n\n  private requireEmbeddedFactory(name: string, options: RegistrationOptions): (deps: TDeps) => (...args: any[]) => any {\n    const { factory } = options as RegistrationWithFactory<TDeps>\n\n    if (!factory) {\n      throw new ForgeAuthoringError({\n        message: `The ${this.functionType} registration \"${name}\" has no factory - pass one positionally or as options.factory`,\n      })\n    }\n\n    return factory\n  }\n\n  protected store(name: string, options: RegistrationOptions, factory: (deps: TDeps) => (...args: any[]) => any): void {\n    if (this.registrations.has(name)) {\n      throw new ForgeRegistryDuplicateError({\n        registryType: 'function',\n        itemName: name,\n        message: `A ${this.functionType} is already registered under the name \"${name}\"`,\n      })\n    }\n\n    const inputSchema = this.compileSchema(options.inputSchema)\n    const argumentsSchema = this.compileSchema(options.argumentsSchema)\n    const outputSchema = this.compileOutputSchema(options.outputSchema)\n\n    this.registrations.set(name, {\n      name,\n      inputSchema,\n      argumentsSchema,\n      outputSchema,\n      prepare: options.prepare,\n      factory,\n    })\n  }\n\n  protected buildExpressionHandle(name: string, prepare?: (...args: any[]) => any[]): (...args: any[]) => any {\n    const type = this.functionType\n\n    if (type === FunctionType.GENERATOR) {\n      const generatorHandle = (...args: any[]) => {\n        const prepared = prepare ? prepare(...args) : args\n        const builder = GeneratorBuilder.create(name, prepared)\n\n        stampCallsite(builder, captureCallsite(generatorHandle))\n        return builder\n      }\n\n      return generatorHandle\n    }\n\n    const expressionHandle = (...args: any[]) => {\n      const prepared = prepare ? prepare(...args) : args\n      const expr = { type, name, arguments: prepared }\n\n      stampCallsite(expr, captureCallsite(expressionHandle))\n      return expr\n    }\n\n    return expressionHandle\n  }\n\n  build(deps?: TDeps): FunctionRegistryObject {\n    const resolvedDeps = (deps ?? {}) as TDeps\n    const registry = {} as FunctionRegistryObject\n\n    this.registrations.forEach((registration, name) => {\n      const evaluate = registration.factory(resolvedDeps)\n\n      registry[name] = {\n        name,\n        evaluate,\n        inputSchema: registration.inputSchema,\n        argumentsSchema: registration.argumentsSchema,\n        outputSchema: registration.outputSchema,\n        functionType: this.functionType,\n      }\n    })\n\n    return registry\n  }\n\n  private compileSchema(schema: ZodType | undefined): ZodType | undefined {\n    if (schema === undefined) {\n      return undefined\n    }\n\n    return z.compile(schema)\n  }\n\n  private compileOutputSchema(schema: ZodType | undefined): ZodType | undefined {\n    if (schema === undefined) {\n      return this.defaultOutputSchema\n    }\n\n    return z.compile(schema)\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeRegistryValidationErrorOptions {\n  /** Type of registry (function or component) */\n  registryType: 'function' | 'component'\n  /** Name or variant of the item (if available) */\n  itemName?: string\n  /** What was expected */\n  expected: string\n  /** What was actually received */\n  received?: string\n  /** Human-readable error message */\n  message: string\n}\n\nexport default class ForgeRegistryValidationError extends ForgeBaseError {\n  readonly registryType: 'function' | 'component'\n\n  readonly itemName?: string\n\n  readonly expected: string\n\n  readonly received?: string\n\n  constructor(options: ForgeRegistryValidationErrorOptions) {\n    super(options.message)\n    this.registryType = options.registryType\n    this.itemName = options.itemName\n    this.expected = options.expected\n    this.received = options.received\n  }\n}\n","import { z } from 'zod'\nimport type { BlockDefinition } from '../../../components/types/structures.type'\nimport ForgeRegistryDuplicateError from '../../errors/ForgeRegistryDuplicateError'\nimport ForgeRegistryValidationError from '../../errors/ForgeRegistryValidationError'\nimport type { ComponentRegistryEntry } from '../../../components/types/components.type'\n\n/**\n * Registry for managing UI components in forge.\n * Components are stored by their variant name and can be retrieved during form rendering.\n */\nexport default class ComponentRegistry {\n  private readonly components = new Map<string, ComponentRegistryEntry<BlockDefinition, unknown>>()\n\n  /**\n   * Register multiple components at once\n   * @param components - Array of components to register\n   * @throws ForgeRegistryDuplicateError if a component with the same variant already exists\n   * @throws ForgeRegistryValidationError if a component is invalid\n   * @throws AggregateError if multiple validation errors occur\n   */\n  registerMany(components: ComponentRegistryEntry<BlockDefinition, unknown>[]): void {\n    if (!components || components.length === 0) {\n      return\n    }\n\n    const errors: Error[] = []\n\n    components.forEach(component => {\n      if (!component?.variant) {\n        errors.push(\n          new ForgeRegistryValidationError({\n            registryType: 'component',\n            expected: 'variant property',\n            received: 'no variant',\n            message: 'Component must have a variant property',\n          }),\n        )\n      } else if (!component.render || typeof component.render !== 'function') {\n        errors.push(\n          new ForgeRegistryValidationError({\n            registryType: 'component',\n            itemName: component.variant,\n            expected: 'render function',\n            received: typeof component.render,\n            message: `Component \"${component.variant}\" must have a render function`,\n          }),\n        )\n      } else if (this.components.has(component.variant)) {\n        errors.push(\n          new ForgeRegistryDuplicateError({\n            registryType: 'component',\n            itemName: component.variant,\n          }),\n        )\n      } else {\n        if (component.inputSchema === undefined) {\n          this.components.set(component.variant, component)\n\n          return\n        }\n\n        this.components.set(component.variant, {\n          ...component,\n          inputSchema: z.compile(component.inputSchema),\n        })\n      }\n    })\n\n    if (errors.length > 0) {\n      throw new AggregateError(errors, 'Component registration failed')\n    }\n  }\n\n  /**\n   * Get a component by variant\n   * @param variant - The variant of the component to retrieve\n   * @returns The component or undefined if not found\n   */\n  get<T extends BlockDefinition, TRenderOutput = unknown>(\n    variant: string,\n  ): ComponentRegistryEntry<T, TRenderOutput> | undefined {\n    return this.components.get(variant) as ComponentRegistryEntry<T, TRenderOutput> | undefined\n  }\n\n  /**\n   * Check if a component is registered\n   * @param variant - The variant of the component to check\n   * @returns True if the component exists, false otherwise\n   */\n  has(variant: string): boolean {\n    return this.components.has(variant)\n  }\n\n  /**\n   * Get all registered components\n   * @returns Map of all registered components\n   */\n  getAll(): Map<string, ComponentRegistryEntry<BlockDefinition, unknown>> {\n    return new Map(this.components)\n  }\n\n  /**\n   * Get the count of registered components\n   * @returns Number of registered components\n   */\n  size(): number {\n    return this.components.size\n  }\n}\n","import type { BlockDefinition } from '../../../components/types/structures.type'\nimport ComponentRegistry from './ComponentRegistry'\nimport { ComponentRegistryEntry } from '../../../components/types/components.type'\n\n/**\n * A component registry scoped to a specific journey, with fallback to a parent registry.\n *\n * Components registered in this registry take precedence over the parent.\n * This enables journey-specific components that don't clash with components\n * from other journeys, while still inheriting globally-registered components\n * like the built-in core components.\n */\nexport default class ScopedComponentRegistry extends ComponentRegistry {\n  constructor(private readonly parent: ComponentRegistry) {\n    super()\n  }\n\n  override get<T extends BlockDefinition, TRenderOutput = unknown>(\n    variant: string,\n  ): ComponentRegistryEntry<T, TRenderOutput> | undefined {\n    return super.get<T, TRenderOutput>(variant) ?? this.parent.get<T, TRenderOutput>(variant)\n  }\n\n  override has(variant: string): boolean {\n    return super.has(variant) || this.parent.has(variant)\n  }\n\n  override getAll(): Map<string, ComponentRegistryEntry<BlockDefinition, unknown>> {\n    const merged = this.parent.getAll()\n\n    for (const [variant, entry] of super.getAll()) {\n      merged.set(variant, entry)\n    }\n\n    return merged\n  }\n\n  override size(): number {\n    return this.getAll().size\n  }\n}\n","import ForgeRegistryDuplicateError from '../../errors/ForgeRegistryDuplicateError'\nimport ForgeRegistryValidationError from '../../errors/ForgeRegistryValidationError'\nimport { FunctionRegistryEntry, FunctionRegistryObject } from '../../../authoring/types/functions.type'\n\n/**\n * Registry for managing functions (conditions, transformers, effects) in forge.\n * Functions are stored by their unique names and can be retrieved during form evaluation.\n */\nexport default class FunctionRegistry {\n  private readonly functions = new Map<string, FunctionRegistryEntry>()\n\n  /**\n   * Register functions - accepts either an array of functions or a registry object\n   * @param input - Registry object created by the authoring function helpers\n   * @throws ForgeRegistryDuplicateError if a function with the same name already exists\n   * @throws ForgeRegistryValidationError if a function has invalid structure\n   * @throws AggregateError if multiple validation errors occur\n   */\n  register(input: FunctionRegistryObject): void {\n    const errors: Error[] = []\n\n    Object.values(input || {}).forEach(entry => {\n      if (!entry.name) {\n        errors.push(\n          new ForgeRegistryValidationError({\n            registryType: 'function',\n            expected: 'object with name property',\n            received: entry ? 'object without name' : 'no object',\n            message: 'Function must have a name property',\n          }),\n        )\n\n        return\n      }\n\n      if (!entry.evaluate || typeof entry.evaluate !== 'function') {\n        errors.push(\n          new ForgeRegistryValidationError({\n            registryType: 'function',\n            itemName: entry.name,\n            expected: 'evaluate function',\n            received: typeof entry.evaluate,\n            message: `Function \"${entry.name}\" must have an evaluate function`,\n          }),\n        )\n\n        return\n      }\n\n      if (this.functions.has(entry.name)) {\n        errors.push(\n          new ForgeRegistryDuplicateError({\n            registryType: 'function',\n            itemName: entry.name,\n          }),\n        )\n\n        return\n      }\n\n      this.functions.set(entry.name, entry)\n    })\n\n    if (errors.length > 0) {\n      throw new AggregateError(errors, 'Function registration failed')\n    }\n  }\n\n  /**\n   * Get a function by name\n   * @param name - The name of the function to retrieve\n   * @returns The function spec or undefined if not found\n   */\n  get(name: string): FunctionRegistryEntry | undefined {\n    return this.functions.get(name)\n  }\n\n  /**\n   * Check if a function is registered\n   * @param name - The name of the function to check\n   * @returns True if the function exists, false otherwise\n   */\n  has(name: string): boolean {\n    return this.functions.has(name)\n  }\n\n  /**\n   * Get all registered functions\n   * @returns Map of all registered functions\n   */\n  getAll(): Map<string, FunctionRegistryEntry> {\n    return new Map(this.functions)\n  }\n\n  /**\n   * Get the count of registered functions\n   * @returns Number of registered functions\n   */\n  size(): number {\n    return this.functions.size\n  }\n}\n","import FunctionRegistry from './FunctionRegistry'\nimport { FunctionRegistryEntry } from '../../../authoring/types/functions.type'\n\n/**\n * A function registry scoped to a specific journey, with fallback to a parent registry.\n *\n * Functions registered in this registry take precedence over the parent.\n * This enables journey-specific functions (effects, conditions, transformers) that\n * don't clash with functions from other journeys, while still inheriting\n * globally-registered functions like built-in conditions and transformers.\n */\nexport default class ScopedFunctionRegistry extends FunctionRegistry {\n  constructor(private readonly parent: FunctionRegistry) {\n    super()\n  }\n\n  override get(name: string): FunctionRegistryEntry | undefined {\n    return super.get(name) ?? this.parent.get(name)\n  }\n\n  override has(name: string): boolean {\n    return super.has(name) || this.parent.has(name)\n  }\n\n  override getAll(): Map<string, FunctionRegistryEntry> {\n    const merged = this.parent.getAll()\n\n    for (const [name, entry] of super.getAll()) {\n      merged.set(name, entry)\n    }\n\n    return merged\n  }\n\n  override size(): number {\n    return this.getAll().size\n  }\n}\n","import type TraceSpan from '../tracing/TraceSpan'\n\n/**\n * Thrown by `WorkExecutor.executeWithUnit` when execution fails mid-tree. It\n * carries the begun-but-not-completed root trace span so `RequestPipeline` can\n * serialize the partial work tree into the failed phase's trace, and the\n * original error so callers can unwrap it.\n */\nexport default class WorkExecutionError extends Error {\n  constructor(\n    readonly original: unknown,\n    readonly traceSpan: TraceSpan,\n  ) {\n    super(original instanceof Error ? original.message : String(original))\n    this.name = 'WorkExecutionError'\n  }\n}\n","import type { TraceSpanContract, TraceSpanExecutionSlice, TraceSpanFields } from './traceSpan.type'\n\nexport default class TraceSpan implements TraceSpanContract {\n  private readonly spanKey: string\n\n  private readonly spanKind: string\n\n  private readonly parentTraceSpan?: TraceSpan\n\n  private readonly childTraceSpans: TraceSpan[] = []\n\n  private readonly mutableStartedAtMs = performance.now()\n\n  private mutableBeginFields: TraceSpanFields = {}\n\n  private mutableCompleteFields: TraceSpanFields = {}\n\n  private mutableCompleted = false\n\n  private mutableCompletedAtMs: number | undefined\n\n  private mutableDurationMs: number | undefined\n\n  private mutableSelfDurationMs = 0\n\n  private readonly mutableExecutionSlices: TraceSpanExecutionSlice[] = []\n\n  private mutableOutput: unknown\n\n  private mutableOmitFromTrace = false\n\n  constructor(key: string, kind: string, parent?: TraceSpan) {\n    this.spanKey = key\n    this.spanKind = kind\n    this.parentTraceSpan = parent\n  }\n\n  get key(): string {\n    return this.spanKey\n  }\n\n  get kind(): string {\n    return this.spanKind\n  }\n\n  get parent(): TraceSpan | undefined {\n    return this.parentTraceSpan\n  }\n\n  get children(): readonly TraceSpan[] {\n    return this.childTraceSpans\n  }\n\n  get beginFields(): TraceSpanFields {\n    return this.mutableBeginFields\n  }\n\n  get completeFields(): TraceSpanFields {\n    return this.mutableCompleteFields\n  }\n\n  get completed(): boolean {\n    return this.mutableCompleted\n  }\n\n  get startedAtMs(): number {\n    return this.mutableStartedAtMs\n  }\n\n  get completedAtMs(): number | undefined {\n    return this.mutableCompletedAtMs\n  }\n\n  get durationMs(): number | undefined {\n    return this.mutableDurationMs\n  }\n\n  get selfDurationMs(): number {\n    return this.mutableSelfDurationMs\n  }\n\n  get executionSlices(): readonly TraceSpanExecutionSlice[] {\n    return this.mutableExecutionSlices\n  }\n\n  get output(): unknown {\n    return this.mutableOutput\n  }\n\n  get omitFromTrace(): boolean {\n    return this.mutableOmitFromTrace\n  }\n\n  addChild(childTraceSpan: TraceSpan): void {\n    this.childTraceSpans.push(childTraceSpan)\n  }\n\n  addSelfTime(ms: number): void {\n    this.mutableSelfDurationMs += ms\n  }\n\n  recordExecutionSlice(startedAtMs: number, completedAtMs: number): void {\n    this.mutableExecutionSlices.push({ startedAtMs, completedAtMs })\n  }\n\n  recordTraceMetadataAtStart(traceMetadata: TraceSpanFields | undefined): void {\n    this.mutableBeginFields = traceMetadata ?? {}\n  }\n\n  recordTraceMetadataAtFinish(traceMetadata: TraceSpanFields | undefined): void {\n    this.mutableCompleteFields = traceMetadata ?? {}\n  }\n\n  complete(output: unknown): void {\n    const completedAtMs = performance.now()\n\n    this.mutableOutput = output\n    this.mutableCompleted = true\n    this.mutableCompletedAtMs = completedAtMs\n    this.mutableDurationMs = completedAtMs - this.mutableStartedAtMs\n  }\n\n  markOmitFromTrace(): void {\n    this.mutableOmitFromTrace = true\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\n/**\n * A state the engine should make impossible - thrown when an internal\n * consistency check fails. Reaching one is a bug in Forge, not an authoring\n * mistake.\n */\nexport default class ForgeInternalError extends ForgeBaseError {\n  constructor(message: string) {\n    super(message)\n  }\n\n  protected override get foldsInternalStackFrames(): boolean {\n    return false\n  }\n}\n","import WorkContext from './WorkContext'\nimport WorkExecutionError from './WorkExecutionError'\nimport TraceSpan from '../tracing/TraceSpan'\nimport type { TraceSpanFields } from '../tracing/traceSpan.type'\nimport type { CompletedWork, WorkGroup, WorkTask } from '../contracts/work/work.type'\nimport type { WorkOutputOf } from '../contracts/work/workOutput.type'\nimport ForgeInternalError from '../../errors/ForgeInternalError'\n\ntype InOrderWorkGroup = Extract<WorkGroup, { readonly mode: 'sequential' | 'first-match' }>\ntype InstrumentedWorkTask<TWorkKind extends string> = WorkTask<TWorkKind> & {\n  readonly instrumentation: NonNullable<WorkTask<TWorkKind>['instrumentation']>\n}\n\n/**\n * A plain value while every step has stayed synchronous, a promise from the moment\n * any handler suspends. One executor recursion serves both the async request\n * pipeline and fully-synchronous compilation trees without forking the code path.\n */\ntype MaybeAsync<TValue> = TValue | Promise<TValue>\n\nexport type WorkExecutionResult<TWorkKind extends string> = CompletedWork<WorkOutputOf<TWorkKind>>\n\nexport interface WorkExecutionResultWithUnit<TWorkKind extends string> {\n  readonly completedWork: WorkExecutionResult<TWorkKind>\n  readonly traceSpan: TraceSpan\n}\n\nexport default class WorkExecutor {\n  constructor(private readonly traceEnabled: boolean = true) {}\n\n  async execute<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n  ): Promise<WorkExecutionResult<TWorkKind>> {\n    return this.runWithSpan(task, ctx)\n  }\n\n  async executeWithUnit<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n  ): Promise<WorkExecutionResultWithUnit<TWorkKind>> {\n    const traceSpan = this.createTraceSpan(task, ctx)\n\n    try {\n      const completedWork = await this.runUnit(task, ctx, traceSpan)\n\n      return { completedWork, traceSpan }\n    } catch (error) {\n      throw new WorkExecutionError(error, traceSpan)\n    }\n  }\n\n  /**\n   * Runs a task tree that must never suspend, staying off the microtask queue\n   * entirely. Compilation executes through this: its handlers are all synchronous,\n   * so a promise from any of them is a programming error, not an outcome.\n   */\n  executeSync<TWorkKind extends string>(task: WorkTask<TWorkKind>, ctx: WorkContext): WorkExecutionResult<TWorkKind> {\n    return requireSyncResult(this.runWithSpan(task, ctx), task)\n  }\n\n  executeSyncWithUnit<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n  ): WorkExecutionResultWithUnit<TWorkKind> {\n    const traceSpan = this.createTraceSpan(task, ctx)\n\n    try {\n      const completedWork = requireSyncResult(this.runUnit(task, ctx, traceSpan), task)\n\n      return { completedWork, traceSpan }\n    } catch (error) {\n      throw new WorkExecutionError(error, traceSpan)\n    }\n  }\n\n  private createTraceSpan(task: WorkTask, ctx: WorkContext): TraceSpan {\n    const parentTraceSpan = ctx.work\n\n    if (parentTraceSpan !== undefined && !(parentTraceSpan instanceof TraceSpan)) {\n      throw new ForgeInternalError('Work context parent must be a TraceSpan to nest in the trace tree')\n    }\n\n    const traceSpan = new TraceSpan(task.key, task.handler.kind, parentTraceSpan)\n\n    parentTraceSpan?.addChild(traceSpan)\n\n    return traceSpan\n  }\n\n  private runWithSpan<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n  ): MaybeAsync<WorkExecutionResult<TWorkKind>> {\n    return this.runUnit(task, ctx, this.createTraceSpan(task, ctx))\n  }\n\n  private runUnit<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n    traceSpan: TraceSpan,\n  ): MaybeAsync<WorkExecutionResult<TWorkKind>> {\n    const workCtx = ctx.withWork(traceSpan, task.props)\n\n    traceSpan.recordTraceMetadataAtStart(this.resolveTraceMetadataAtStart(task, workCtx))\n\n    // Measure only the synchronous span of the handler calls: awaiting across a suspension\n    // would fold in siblings' interleaved work, which is exactly the queue-wait smear we drop.\n    const beginStartedAtMs = performance.now()\n    const beginResult = task.handler.begin(workCtx)\n    const beginCompletedAtMs = performance.now()\n\n    traceSpan.addSelfTime(beginCompletedAtMs - beginStartedAtMs)\n    traceSpan.recordExecutionSlice(beginStartedAtMs, beginCompletedAtMs)\n\n    return chain(beginResult, begin =>\n      chain(this.executeGroups(begin.groups ?? [], workCtx), children => {\n        const completeStartedAtMs = performance.now()\n        const completeResult = this.completeWork(task, workCtx, children, begin.output)\n        const completeCompletedAtMs = performance.now()\n\n        traceSpan.addSelfTime(completeCompletedAtMs - completeStartedAtMs)\n        traceSpan.recordExecutionSlice(completeStartedAtMs, completeCompletedAtMs)\n\n        return chain(completeResult, output => {\n          traceSpan.recordTraceMetadataAtFinish(this.resolveTraceMetadataAtFinish(task, workCtx, output))\n          traceSpan.complete(output)\n\n          return {\n            key: task.key,\n            kind: task.handler.kind,\n            output,\n            children,\n          }\n        })\n      }),\n    )\n  }\n\n  private executeGroups(groups: readonly WorkGroup[], ctx: WorkContext): MaybeAsync<CompletedWork[]> {\n    return groups.reduce<MaybeAsync<CompletedWork[]>>(\n      (accumulated, group) =>\n        chain(accumulated, children =>\n          chain(this.executeGroup(group, ctx), groupChildren => [...children, ...groupChildren]),\n        ),\n      [],\n    )\n  }\n\n  private executeGroup(group: WorkGroup, ctx: WorkContext): MaybeAsync<CompletedWork[]> {\n    switch (group.mode) {\n      case 'concurrent':\n        return this.executeConcurrently(group, ctx)\n      case 'sequential':\n      case 'first-match':\n        return this.executeInOrder(group, ctx)\n      default:\n        return assertNever(group)\n    }\n  }\n\n  private executeConcurrently(group: WorkGroup, ctx: WorkContext): MaybeAsync<CompletedWork[]> {\n    const results = group.children.map(child => this.runWithSpan(child, ctx))\n\n    return results.some(result => result instanceof Promise) ? Promise.all(results) : (results as CompletedWork[])\n  }\n\n  private executeInOrder(group: InOrderWorkGroup, ctx: WorkContext): MaybeAsync<CompletedWork[]> {\n    const stopWhen = group.mode === 'first-match' ? group.matches : undefined\n    const completedChildren: CompletedWork[] = []\n\n    const runFrom = (index: number): MaybeAsync<CompletedWork[]> => {\n      if (index >= group.children.length) {\n        return completedChildren\n      }\n\n      return chain(this.runWithSpan(group.children[index], ctx), completedChild => {\n        completedChildren.push(completedChild)\n\n        return stopWhen?.(completedChild) === true ? completedChildren : runFrom(index + 1)\n      })\n    }\n\n    return runFrom(0)\n  }\n\n  private resolveTraceMetadataAtStart<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n  ): TraceSpanFields | undefined {\n    if (!this.traceEnabled || !isInstrumentedWorkTask(task)) {\n      return undefined\n    }\n\n    return task.instrumentation.resolveTraceMetadataAtStart(ctx)\n  }\n\n  private resolveTraceMetadataAtFinish<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n    output: WorkOutputOf<TWorkKind>,\n  ): TraceSpanFields | undefined {\n    if (!this.traceEnabled || !isInstrumentedWorkTask(task)) {\n      return undefined\n    }\n\n    return task.instrumentation.resolveTraceMetadataAtFinish(ctx, output)\n  }\n\n  private completeWork<TWorkKind extends string>(\n    task: WorkTask<TWorkKind>,\n    ctx: WorkContext,\n    children: CompletedWork[],\n    beginOutput: unknown,\n  ): MaybeAsync<WorkOutputOf<TWorkKind>> {\n    if (task.handler.complete === undefined) {\n      return beginOutput as WorkOutputOf<TWorkKind>\n    }\n\n    return task.handler.complete(ctx, children)\n  }\n}\n\nfunction chain<TIn, TOut>(value: MaybeAsync<TIn>, next: (value: TIn) => MaybeAsync<TOut>): MaybeAsync<TOut> {\n  return value instanceof Promise ? value.then(next) : next(value)\n}\n\nfunction requireSyncResult<TValue>(result: MaybeAsync<TValue>, task: WorkTask): TValue {\n  if (result instanceof Promise) {\n    // The stray asynchronous work is already in flight; silence its settlement so it\n    // cannot fire an unhandled rejection on top of the error thrown here.\n    result.catch(() => undefined)\n    throw new ForgeInternalError(`Synchronous execution encountered asynchronous work under task \"${task.key}\"`)\n  }\n\n  return result\n}\n\nfunction assertNever(value: never): never {\n  throw new ForgeInternalError(`Unhandled work group mode: ${JSON.stringify(value)}`)\n}\n\nfunction isInstrumentedWorkTask<TWorkKind extends string>(\n  task: WorkTask<TWorkKind>,\n): task is InstrumentedWorkTask<TWorkKind> {\n  return task.instrumentation !== undefined\n}\n","import TraceSpan from '../tracing/TraceSpan'\nimport type { TraceSpanReference } from '../tracing/traceSpan.type'\nimport type { WorkContextContract } from '../contracts/work/work.type'\n\nexport default class WorkContext<TStageState = unknown, TProps = unknown> implements WorkContextContract<\n  TStageState,\n  TProps\n> {\n  private readonly stageState: TStageState\n\n  private readonly workProps?: TProps\n\n  private readonly traceSpan?: TraceSpanReference\n\n  constructor(state: TStageState, work?: TraceSpanReference, props?: TProps) {\n    this.stageState = state\n    this.traceSpan = work\n    this.workProps = props\n  }\n\n  get state(): TStageState {\n    return this.stageState\n  }\n\n  // `props` is always set by `withWork` before any handler or instrumentation reads it;\n  // the root seed context (no work, no props) is never passed to a handler.\n  get props(): TProps {\n    return this.workProps as TProps\n  }\n\n  get work(): TraceSpanReference | undefined {\n    return this.traceSpan\n  }\n\n  withWork(work: TraceSpanReference, props: TProps): WorkContext<TStageState, TProps> {\n    return new WorkContext<TStageState, TProps>(this.stageState, work, props)\n  }\n\n  omitFromTrace(): void {\n    if (this.traceSpan instanceof TraceSpan) {\n      this.traceSpan.markOmitFromTrace()\n    }\n  }\n}\n","import type { SerializedTraceSpan, TraceSpanContract } from './traceSpan.type'\n\nexport default class TraceSpanSerializer {\n  serialize(span: TraceSpanContract): SerializedTraceSpan {\n    return {\n      key: span.key,\n      kind: span.kind,\n      beginFields: span.beginFields,\n      completeFields: span.completeFields,\n      completed: span.completed,\n      startedAtMs: span.startedAtMs,\n      completedAtMs: span.completedAtMs,\n      durationMs: span.durationMs,\n      selfDurationMs: span.selfDurationMs,\n      // Spans with no recorded slices omit the field rather than carry an empty array.\n      ...(span.executionSlices.length > 0 ? { executionSlices: span.executionSlices } : {}),\n      children: span.children.filter(child => !child.omitFromTrace).map(child => this.serialize(child)),\n    }\n  }\n}\n","import type TraceSpan from '../../tracing/TraceSpan'\nimport TraceSpanSerializer from '../../tracing/TraceSpanSerializer'\nimport type {\n  CompilationTrace,\n  CompilationTraceError,\n  CompilationTracePhase,\n} from '../../contracts/compilation/trace.type'\nimport type { ForgeInstrumentation } from '../../tracing/ForgeTraceSinkDispatcher'\n\nexport interface CompilationTraceEmission {\n  readonly instrumentation: ForgeInstrumentation\n  /** The `compilation.pipeline` root span the work executor produced, if compilation got far enough to have one. */\n  readonly root: TraceSpan | undefined\n  readonly journeyCode: string | undefined\n  readonly outcome: 'compiled' | 'error'\n  readonly error?: unknown\n}\n\nexport default class CompilationPipelineTraceProjector {\n  private readonly serializer = new TraceSpanSerializer()\n\n  emit(emission: CompilationTraceEmission): void {\n    const { instrumentation, root, journeyCode, outcome, error } = emission\n\n    if (!instrumentation.enabled || root === undefined || root.children.length === 0) {\n      return\n    }\n\n    // A failed compilation leaves the root span incomplete; close it here so\n    // the emitted trace carries a duration either way.\n    if (!root.completed) {\n      root.complete(undefined)\n    }\n\n    const phases = this.project(root)\n\n    instrumentation.onCompilationTrace({\n      journeyCode,\n      trace: { outcome, ...this.traceTiming(root), ...this.traceErrorDetail(outcome, error), phases },\n    })\n  }\n\n  private project(root: TraceSpan): CompilationTracePhase[] {\n    return root.children.map(phaseSpan => {\n      const phase = this.phaseName(phaseSpan.kind)\n      const units = phaseSpan.children\n        .filter(child => !child.omitFromTrace)\n        .map(child => this.serializer.serialize(child))\n\n      return { phase, ...this.traceTiming(phaseSpan), units }\n    })\n  }\n\n  private traceErrorDetail(outcome: 'compiled' | 'error', error: unknown): Pick<CompilationTrace, 'error'> {\n    if (outcome !== 'error') {\n      return {}\n    }\n\n    return { error: this.errorDetail(error) }\n  }\n\n  private errorDetail(error: unknown): CompilationTraceError {\n    if (error instanceof Error) {\n      return { message: error.message, stack: error.stack }\n    }\n\n    return { message: String(error) }\n  }\n\n  private traceTiming(traceSpan: TraceSpan): Pick<CompilationTrace, 'startedAtMs' | 'completedAtMs' | 'durationMs'> {\n    return {\n      startedAtMs: traceSpan.startedAtMs,\n      completedAtMs: traceSpan.completedAtMs,\n      durationMs: traceSpan.durationMs,\n    }\n  }\n\n  private phaseName(kind: string): string {\n    const prefix = 'compilation.'\n\n    return kind.startsWith(prefix) ? kind.slice(prefix.length) : kind\n  }\n}\n","import type { JourneyDefinition } from '../../../../authoring/types/structures.type'\nimport type { JourneyASTNode } from '../../contracts/ast/structures.type'\nimport type { NodeId } from '../../contracts/ast/engine.type'\nimport type { CompilationModel } from '../../contracts/models/compilationModel.type'\nimport type {\n  CompiledJourney,\n  CompiledPackageFunctions,\n  CompiledStep,\n} from '../../contracts/plans/compilationArtefacts.type'\nimport type { JourneyRouteIndex, StepRouteIndex } from '../../../concerns/route/contracts/routeDescriptors.type'\nimport type { CompilationDependencies } from '../lowering/compilationDependencies.type'\nimport type ASTNodeIndex from '../ast/ast-state/ASTNodeIndex'\nimport type TemplateNodeIndex from '../ast/ast-state/TemplateNodeIndex'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nexport interface AstContext {\n  readonly rootNode: JourneyASTNode\n  readonly nodeIndex: ASTNodeIndex\n  /** Template contents indexed for semantic analysis only — analysis and lowering must not plan against them. */\n  readonly templateNodeIndex: TemplateNodeIndex\n}\n\nexport interface RouteIndexes {\n  readonly stepRouteIndex: StepRouteIndex\n  readonly journeyRouteIndex: JourneyRouteIndex\n}\n\n/**\n * The draft the compilation phases build up, one phase at a time: the AST\n * phase records the tree, analysis records the model, the codegen tasks fill\n * the artifact maps, and the route phase records the indexes. Each getter\n * throws when read before its phase has run — the phase order is fixed, so a\n * missing value is a pipeline bug, not an outcome.\n *\n * Like the AST and the compilation model, this state never leaves\n * compilation: the pipeline assembles the `CompiledPackage` from it and only\n * that crosses the boundary.\n */\nexport default class CompilationState {\n  readonly journeys = new Map<NodeId, CompiledJourney>()\n\n  readonly steps = new Map<NodeId, CompiledStep>()\n\n  private mutableAst?: AstContext\n\n  private mutableJourneyCode?: string\n\n  private mutableModel?: CompilationModel\n\n  private mutablePackageFunctions?: CompiledPackageFunctions\n\n  private mutableRouteIndexes?: RouteIndexes\n\n  constructor(\n    readonly journeyDefinition: JourneyDefinition,\n    readonly dependencies: CompilationDependencies,\n  ) {}\n\n  get ast(): AstContext {\n    if (this.mutableAst === undefined) {\n      throw new ForgeInternalError('Compilation state read before the AST phase recorded the tree')\n    }\n\n    return this.mutableAst\n  }\n\n  /** Undefined until the AST phase has run — the error path reports traces for packages that failed before then. */\n  get journeyCode(): string | undefined {\n    return this.mutableJourneyCode\n  }\n\n  get model(): CompilationModel {\n    if (this.mutableModel === undefined) {\n      throw new ForgeInternalError('Compilation state read before the analysis phase recorded the model')\n    }\n\n    return this.mutableModel\n  }\n\n  get packageFunctions(): CompiledPackageFunctions {\n    if (this.mutablePackageFunctions === undefined) {\n      throw new ForgeInternalError('Compilation state read before the package functions were compiled')\n    }\n\n    return this.mutablePackageFunctions\n  }\n\n  get routeIndexes(): RouteIndexes {\n    if (this.mutableRouteIndexes === undefined) {\n      throw new ForgeInternalError('Compilation state read before the route phase recorded the indexes')\n    }\n\n    return this.mutableRouteIndexes\n  }\n\n  recordAst(ast: AstContext): void {\n    this.mutableAst = ast\n    this.mutableJourneyCode = ast.rootNode.properties.code\n  }\n\n  recordModel(model: CompilationModel): void {\n    this.mutableModel = model\n  }\n\n  recordPackageFunctions(packageFunctions: CompiledPackageFunctions): void {\n    this.mutablePackageFunctions = packageFunctions\n  }\n\n  recordRouteIndexes(routeIndexes: RouteIndexes): void {\n    this.mutableRouteIndexes = routeIndexes\n  }\n}\n","import type { TraceSpanFields, TraceSpanReference } from '../../tracing/traceSpan.type'\nimport type { WorkOutputOf } from './workOutput.type'\n\nexport const FORGE_WORK = Symbol.for('forge.work')\n\nexport interface WorkContextContract<TStageState = unknown, TProps = unknown> {\n  readonly state: TStageState\n  readonly props: TProps\n  readonly work?: TraceSpanReference\n\n  withWork(work: TraceSpanReference, props: TProps): WorkContextContract<TStageState, TProps>\n\n  // Lets a work task drop its own trace unit (a no-op'd, unselected hook branch).\n  // Optional because trace omission is best-effort and not every context records work.\n  omitFromTrace?(): void\n}\n\nexport interface WorkInstrumentation<TProps = unknown, TOutput = unknown> {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<unknown, TProps>): TraceSpanFields | undefined\n\n  resolveTraceMetadataAtFinish(ctx: WorkContextContract<unknown, TProps>, output: TOutput): TraceSpanFields | undefined\n}\n\nexport interface WorkHandler<K extends string = string, TProps = unknown> {\n  readonly kind: K\n\n  begin(ctx: WorkContextContract<unknown, TProps>): WorkBegin<K> | Promise<WorkBegin<K>>\n\n  complete?(\n    ctx: WorkContextContract<unknown, TProps>,\n    children: readonly CompletedWork[],\n  ): WorkOutputOf<K> | Promise<WorkOutputOf<K>>\n}\n\nexport interface WorkTask<K extends string = string, TProps = unknown> {\n  readonly $$typeof: typeof FORGE_WORK\n  readonly key: string\n  readonly handler: WorkHandler<K, TProps>\n  readonly props: TProps\n  readonly instrumentation?: WorkInstrumentation<TProps, WorkOutputOf<K>>\n}\n\nexport type WorkBegin<K extends string = string> =\n  | { readonly output: WorkOutputOf<K>; readonly groups?: never }\n  | { readonly groups: readonly WorkGroup[]; readonly output?: never }\n\nexport interface CompletedWork<TOutput = unknown> {\n  readonly key: string\n  readonly kind: string\n  readonly output: TOutput\n  readonly children: readonly CompletedWork[]\n}\n\nexport type WorkGroup =\n  | { readonly mode: 'sequential'; readonly children: readonly WorkTask[] }\n  | { readonly mode: 'concurrent'; readonly children: readonly WorkTask[] }\n  | {\n      readonly mode: 'first-match'\n      readonly children: readonly WorkTask[]\n      readonly matches: (work: CompletedWork) => boolean\n    }\n","import { FORGE_WORK } from '../contracts/work/work.type'\nimport type { CompletedWork, WorkGroup, WorkHandler, WorkInstrumentation, WorkTask } from '../contracts/work/work.type'\nimport type { WorkOutputOf } from '../contracts/work/workOutput.type'\n\nexport function createWorkTask<K extends string, TProps>(\n  key: string,\n  handler: WorkHandler<K, TProps>,\n  props: TProps,\n  instrumentation?: WorkInstrumentation<TProps, WorkOutputOf<K>>,\n): WorkTask<K, TProps> {\n  return { $$typeof: FORGE_WORK, key, handler, props, instrumentation }\n}\n\n/**\n * Reads the output of the first completed child of a given kind. The kind keys the\n * registry, so the returned type is exactly that kind's output — the caller never\n * re-proves the shape.\n */\nexport function singleChildOutput<K extends string>(\n  children: readonly CompletedWork[],\n  kind: K,\n): WorkOutputOf<K> | undefined {\n  return children.find(child => child.kind === kind)?.output as WorkOutputOf<K> | undefined\n}\n\n/**\n * Reads the outputs of every completed child of a given kind, each typed as that\n * kind's registry output. Used by the fan-out parents (resolve blocks, step\n * validation, validities).\n */\nexport function childOutputs<K extends string>(\n  children: readonly CompletedWork[],\n  kind: K,\n): readonly WorkOutputOf<K>[] {\n  return children.filter(child => child.kind === kind).map(child => child.output as WorkOutputOf<K>)\n}\n\n/**\n * Finds the completed child produced by a specific task, matching on the task's\n * key and kind. Returns the completed work so callers can both test existence and\n * read the typed output via `?.output`.\n */\nexport function findChildByTask<K extends string>(\n  children: readonly CompletedWork[],\n  task: WorkTask<K>,\n): CompletedWork<WorkOutputOf<K>> | undefined {\n  return children.find(child => child.key === task.key && child.kind === task.handler.kind) as\n    | CompletedWork<WorkOutputOf<K>>\n    | undefined\n}\n\n/**\n * Narrows an untrusted value to a work task of a specific kind. Used to validate\n * the task a compiled function returned before running it as child work.\n */\nexport function isWorkTaskOfKind(value: unknown, kind: string): value is WorkTask {\n  return isWorkTask(value) && value.handler.kind === kind\n}\n\n/**\n * Wraps a single task as a phase's child work: one sequential, reduce-all group.\n * The return is the `WorkBegin` groups-arm shape so it assigns to every phase's\n * kind-specific `WorkBegin`.\n */\nexport function singleTaskGroup(task: WorkTask): { readonly groups: readonly WorkGroup[] } {\n  return { groups: [{ mode: 'sequential', children: [task] }] }\n}\n\n/**\n * True when a hook stage produced a terminal result. Reads the `status` field\n * structurally so the work primitives stay free of the hook-stage type.\n */\nexport function isTerminalStage(output: unknown): boolean {\n  return typeof output === 'object' &&\n    output !== null &&\n    'status' in output &&\n    (output as { status: unknown }).status === 'terminal'\n}\n\n/**\n * Returns the result carried by the first terminal hook stage, or undefined when\n * every stage continued. Lets a hook's `complete` fold its stage list in one pass.\n */\nexport function findTerminalStage<TResult>(children: readonly CompletedWork[]): TResult | undefined {\n  const terminal = children.find(child => isTerminalStage(child.output))\n\n  return terminal === undefined ? undefined : (terminal.output as { result: TResult }).result\n}\n\nexport function isWorkTask(value: unknown): value is WorkTask {\n  if (value === undefined || value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const candidate = value as Partial<WorkTask>\n\n  return candidate.$$typeof === FORGE_WORK &&\n    typeof candidate.key === 'string' &&\n    isWorkHandler(candidate.handler) &&\n    'props' in candidate\n}\n\nfunction isWorkHandler(value: unknown): value is WorkHandler {\n  if (value === undefined || value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const candidate = value as Partial<WorkHandler>\n\n  return typeof candidate.kind === 'string' && typeof candidate.begin === 'function'\n}\n","import type { WorkHandler, WorkTask } from '../../contracts/work/work.type'\nimport { createWorkTask } from '../../work/workTask'\n\nexport interface CompilationPipelineWorkProps {\n  readonly phases: readonly WorkTask[]\n}\n\n/**\n * The whole compilation as one work handler. `begin` runs the ordered phases as a\n * single sequential group - each phase assumes the previous one's recordings on the\n * shared `CompilationState`, so a phase that throws stops the pipeline with its span\n * left incomplete. There is no `complete` fold: phases record onto the state, and\n * the pipeline assembles the package from it afterwards.\n */\nexport const COMPILATION_PIPELINE_WORK_HANDLER: WorkHandler<'compilation.pipeline', CompilationPipelineWorkProps> = {\n  kind: 'compilation.pipeline',\n\n  begin(ctx) {\n    return {\n      groups: [\n        {\n          mode: 'sequential',\n          children: [...ctx.props.phases],\n        },\n      ],\n    }\n  },\n}\n\nexport function createCompilationPipelineTask(props: CompilationPipelineWorkProps) {\n  return createWorkTask('compilation', COMPILATION_PIPELINE_WORK_HANDLER, props)\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeSerialisationErrorOptions {\n  type: string\n  /** Human-readable error message */\n  message?: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Captured author callsite for the offending node, when available */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeSerialisationError extends ForgeBaseError {\n  readonly type: string\n\n  constructor(options: ForgeSerialisationErrorOptions) {\n    super(\n      options.message ?? `${options.type} at ${options.formattedPath ?? 'unknown'} (not JSON serializable)`,\n      options,\n    )\n    this.type = options.type\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeSchemaErrorOptions {\n  /** Human-readable error message */\n  message: string\n  /** Expected value type/format */\n  expected?: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Captured author callsite for the offending node, when available */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeSchemaError extends ForgeBaseError {\n  readonly expected?: string\n\n  constructor(options: ForgeSchemaErrorOptions) {\n    super(options.message, options)\n    this.expected = options.expected\n  }\n}\n","import { z } from 'zod'\nimport { FunctionType } from '../../../../authoring/types/enums'\n\n/**\n * Simple ResolvableValue for function arguments\n * This is a simplified version used only in function schemas\n */\nconst FunctionArgumentSchema: z.ZodType<any> = z.lazy(() =>\n  z.union([\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.null(),\n    z.array(FunctionArgumentSchema),\n    z.record(z.string(), z.any()),\n  ]),\n)\n\n/**\n * @see {@link ConditionFunctionExpr}\n */\nexport const ConditionFunctionExprSchema = z.object({\n  type: z.literal(FunctionType.CONDITION),\n  name: z.string().trim().min(1),\n  arguments: z.array(FunctionArgumentSchema),\n})\n\n/**\n * @see {@link TransformerFunctionExpr}\n */\nexport const TransformerFunctionExprSchema = z.object({\n  type: z.literal(FunctionType.TRANSFORMER),\n  name: z.string().trim().min(1),\n  arguments: z.array(FunctionArgumentSchema),\n})\n\n/**\n * @see {@link EffectFunctionExpr}\n */\nexport const EffectFunctionExprSchema = z.object({\n  type: z.literal(FunctionType.EFFECT),\n  name: z.string().trim().min(1),\n  arguments: z.array(FunctionArgumentSchema),\n})\n\n/**\n * @see {@link GeneratorFunctionExpr}\n */\nexport const GeneratorFunctionExprSchema = z.object({\n  type: z.literal(FunctionType.GENERATOR),\n  name: z.string().trim().min(1),\n  arguments: z.array(FunctionArgumentSchema),\n})\n\n/**\n * @see {@link FunctionExpr}\n */\nexport const FunctionExprSchema = z.union([\n  ConditionFunctionExprSchema,\n  TransformerFunctionExprSchema,\n  EffectFunctionExprSchema,\n  GeneratorFunctionExprSchema,\n])\n","import { z } from 'zod'\nimport { ExpressionType, IteratorType } from '../../../../authoring/types/enums'\nimport { TransformerFunctionExprSchema, GeneratorFunctionExprSchema } from './base.schema'\n\n/**\n * @see {@link ResolvableValue}\n */\nexport const ResolvableValueSchema: z.ZodType<any> = z.lazy(() =>\n  z.union([\n    ReferenceExprSchema,\n    TransformerFunctionExprSchema,\n    GeneratorFunctionExprSchema,\n    PipelineExprSchema,\n    NullishExprSchema,\n    IterateExprSchema,\n    z.array(ResolvableValueSchema),\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.null(),\n    z.record(z.string(), z.any()),\n  ]),\n)\n\n/**\n * @see {@link ReferenceExpr}\n */\nexport const ReferenceExprSchema = z.looseObject({\n  type: z.literal(ExpressionType.REFERENCE),\n  path: z.array(z.string()),\n})\n\n/** Validates a lazy fallback expression. */\nexport const NullishExprSchema = z.looseObject({\n  type: z.literal(ExpressionType.NULLISH),\n  input: ResolvableValueSchema,\n  fallback: ResolvableValueSchema.optional(),\n})\n\n/**\n * @see {@link PipelineExpr}\n */\nexport const PipelineExprSchema = z.looseObject({\n  type: z.literal(ExpressionType.PIPELINE),\n  input: ResolvableValueSchema,\n  steps: z.array(TransformerFunctionExprSchema),\n})\n\n/**\n * @see {@link MapIteratorConfig}\n */\nconst MapIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.MAP),\n  yield: z.any(),\n})\n\n/**\n * @see {@link FilterIteratorConfig}\n */\nconst FilterIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.FILTER),\n  predicate: z.any(),\n})\n\n/**\n * @see {@link FindIteratorConfig}\n */\nconst FindIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.FIND),\n  predicate: z.any(),\n})\n\nconst SomeIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.SOME),\n  predicate: z.unknown(),\n})\n\nconst EveryIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.EVERY),\n  predicate: z.unknown(),\n})\n\nconst CountIteratorConfigSchema = z.looseObject({\n  type: z.literal(IteratorType.COUNT),\n  predicate: z.unknown(),\n})\n\n/**\n * @see {@link IteratorConfig}\n */\nconst IteratorConfigSchema = z.union([\n  MapIteratorConfigSchema,\n  FilterIteratorConfigSchema,\n  FindIteratorConfigSchema,\n  SomeIteratorConfigSchema,\n  EveryIteratorConfigSchema,\n  CountIteratorConfigSchema,\n])\n\n/**\n * @see {@link IterateExpr}\n */\nexport const IterateExprSchema = z.looseObject({\n  type: z.literal(ExpressionType.ITERATE),\n  input: ResolvableValueSchema,\n  iterator: IteratorConfigSchema,\n})\n","import { z } from 'zod'\nimport {\n  PredicateType,\n  ExpressionType,\n  IteratorType,\n  OutcomeType,\n  ConditionCombinatorType,\n} from '../../../../authoring/types/enums'\nimport { ResolvableValueSchema } from './expressions.schema'\nimport { ConditionFunctionExprSchema } from './base.schema'\n\n/**\n * @see {@link PredicateExpr}\n */\nexport const PredicateExprSchema: z.ZodType<any> = z.lazy(() =>\n  z.union([\n    PredicateTestExprSchema,\n    PredicateAndExprSchema,\n    PredicateOrExprSchema,\n    PredicateXorExprSchema,\n    PredicateNotExprSchema,\n    CollectionPredicateExprSchema,\n  ]),\n)\n\n/** A boolean iterator can be used wherever a predicate is expected. */\nconst CollectionPredicateExprSchema = z.object({\n  type: z.literal(ExpressionType.ITERATE),\n  input: ResolvableValueSchema,\n  iterator: z.object({\n    type: z.enum([IteratorType.SOME, IteratorType.EVERY]),\n    predicate: PredicateExprSchema,\n  }),\n})\n\n/**\n * @see {@link PredicateTestExpr}\n */\nconst PredicateTestExprSchema = z.object({\n  type: z.literal(PredicateType.TEST),\n  subject: ResolvableValueSchema,\n  negate: z.boolean(),\n  condition: ConditionFunctionExprSchema,\n})\n\n/**\n * @see {@link PredicateAndExpr}\n */\nconst PredicateAndExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(PredicateType.AND),\n  operands: z.array(PredicateExprSchema).min(2),\n})\n\n/**\n * @see {@link PredicateOrExpr}\n */\nconst PredicateOrExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(PredicateType.OR),\n  operands: z.array(PredicateExprSchema).min(2),\n})\n\n/**\n * @see {@link PredicateXorExpr}\n */\nconst PredicateXorExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(PredicateType.XOR),\n  operands: z.array(PredicateExprSchema).min(2),\n})\n\n/**\n * @see {@link PredicateNotExpr}\n */\nconst PredicateNotExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(PredicateType.NOT),\n  operand: PredicateExprSchema,\n})\n\n/**\n * @see {@link ConditionalExpr}\n */\nexport const ConditionalExprSchema = z.lazy(() =>\n  z.object({\n    type: z.literal(ExpressionType.CONDITIONAL),\n    predicate: PredicateExprSchema,\n    thenValue: ResolvableValueSchema.optional(),\n    elseValue: ResolvableValueSchema.optional(),\n  }),\n)\n\n/**\n * @see {@link ConditionBranchExpr}\n */\nconst ConditionBranchExprSchema: z.ZodType<any> = z.lazy(() =>\n  z.union([\n    ConditionFunctionExprSchema,\n    ConditionAndExprSchema,\n    ConditionOrExprSchema,\n    ConditionXorExprSchema,\n    ConditionNotExprSchema,\n  ]),\n)\n\n/**\n * @see {@link ConditionAndExpr}\n */\nconst ConditionAndExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(ConditionCombinatorType.AND),\n  operands: z.array(ConditionBranchExprSchema).min(2),\n})\n\n/**\n * @see {@link ConditionOrExpr}\n */\nconst ConditionOrExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(ConditionCombinatorType.OR),\n  operands: z.array(ConditionBranchExprSchema).min(2),\n})\n\n/**\n * @see {@link ConditionXorExpr}\n */\nconst ConditionXorExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(ConditionCombinatorType.XOR),\n  operands: z.array(ConditionBranchExprSchema).min(2),\n})\n\n/**\n * @see {@link ConditionNotExpr}\n */\nexport const ConditionNotExprSchema: z.ZodType<any> = z.looseObject({\n  type: z.literal(ConditionCombinatorType.NOT),\n  operand: ConditionBranchExprSchema,\n})\n\n/**\n * @see {@link MatchBranch}\n */\nexport const MatchBranchSchema = z.union([\n  z.object({ condition: ConditionBranchExprSchema, value: ResolvableValueSchema }),\n  z.object({ expected: ResolvableValueSchema, value: ResolvableValueSchema }),\n])\n\n/**\n * @see {@link MatchExpr}\n */\nexport const MatchExprSchema = z.lazy(() =>\n  z.object({\n    type: z.literal(ExpressionType.MATCH),\n    subject: ResolvableValueSchema,\n    branches: z.array(MatchBranchSchema).min(1),\n    otherwise: ResolvableValueSchema.optional(),\n  }),\n)\n\n/**\n * @see {@link RedirectOutcome}\n */\nconst RedirectOutcomeSchema = z.object({\n  type: z.literal(OutcomeType.REDIRECT),\n  when: PredicateExprSchema.optional(),\n  goto: z.union([z.string(), ResolvableValueSchema]),\n})\n\n/**\n * @see {@link ThrowErrorOutcome}\n */\nconst ThrowErrorOutcomeSchema = z.object({\n  type: z.literal(OutcomeType.THROW_ERROR),\n  when: PredicateExprSchema.optional(),\n  status: z.number().int().min(100).max(599),\n  message: z.union([z.string(), ResolvableValueSchema]),\n})\n\n/**\n * @see {@link HookOutcome}\n */\nexport const HookOutcomeSchema = z.discriminatedUnion('type', [RedirectOutcomeSchema, ThrowErrorOutcomeSchema])\n","import { z } from 'zod'\nimport {\n  BlockType,\n  ExpressionType,\n  FunctionType,\n  HookType,\n  IteratorType,\n  OutcomeType,\n  PredicateType,\n  StructureType,\n} from '../../../../authoring/types/enums'\nimport {\n  ReferenceExprSchema,\n  PipelineExprSchema,\n  NullishExprSchema,\n  IterateExprSchema,\n  ResolvableValueSchema,\n} from './expressions.schema'\nimport { PredicateExprSchema, ConditionalExprSchema, MatchExprSchema, HookOutcomeSchema } from './predicates.schema'\nimport {\n  TransformerFunctionExprSchema,\n  GeneratorFunctionExprSchema,\n  FunctionExprSchema,\n  EffectFunctionExprSchema,\n} from './base.schema'\n\n/**\n * @see {@link ViewConfig}\n */\nconst ViewConfigSchema = z.object({\n  template: z.string().optional(),\n  locals: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst staticDataDynamicMarkers = new Set<string>([\n  ...Object.values(ExpressionType),\n  ...Object.values(FunctionType),\n  ...Object.values(HookType),\n  ...Object.values(IteratorType),\n  ...Object.values(OutcomeType),\n  ...Object.values(PredicateType),\n])\n\nconst StaticDataValueSchema: z.ZodType<unknown> = z.lazy(() =>\n  z\n    .union([\n      z.string(),\n      z.number(),\n      z.boolean(),\n      z.null(),\n      z.array(StaticDataValueSchema),\n      z.record(z.string(), StaticDataValueSchema),\n    ])\n    .superRefine((value, ctx) => {\n      if (value === null || Array.isArray(value) || typeof value !== 'object') {\n        return\n      }\n\n      const type = (value as { type?: unknown }).type\n\n      if (typeof type !== 'string' || !staticDataDynamicMarkers.has(type)) {\n        return\n      }\n\n      ctx.addIssue({\n        code: 'custom',\n        message: 'Forge expressions are not supported in static data',\n      })\n    }),\n)\n\nconst StaticDataSchema = z.record(z.string(), StaticDataValueSchema)\n\n// TODO: Probably should add the remaining resolvable schemas, such as ResolvableNumber/Array/Object.\n/**\n * @see {@link ResolvableString}\n */\nconst ResolvableStringSchema = z.union([\n  z.string(),\n  ReferenceExprSchema,\n  GeneratorFunctionExprSchema,\n  PipelineExprSchema,\n  NullishExprSchema,\n  ConditionalExprSchema,\n  MatchExprSchema,\n])\n\n/**\n * @see {@link ResolvableBoolean}\n */\nconst ResolvableBooleanSchema = z.union([\n  z.boolean(),\n  PredicateExprSchema,\n  ReferenceExprSchema,\n  GeneratorFunctionExprSchema,\n  PipelineExprSchema,\n  NullishExprSchema,\n  ConditionalExprSchema,\n  MatchExprSchema,\n])\n\n/**\n * @see {@link RouteMetadata}\n */\nconst RouteMetadataSchema = z.record(z.string(), ResolvableValueSchema.optional())\n\n/**\n * @see {@link ValidationExpr}\n */\nconst ValidationExprSchema = z.looseObject({\n  type: z.literal(ExpressionType.VALIDATION),\n  condition: PredicateExprSchema,\n  message: ResolvableStringSchema,\n  submissionOnly: z.boolean().optional(),\n  groups: z.array(z.string().trim().min(1)).optional(),\n  details: z.record(z.string(), z.any()).optional(),\n})\n\nconst ValidWhenItemSchema = z.discriminatedUnion('type', [ValidationExprSchema, IterateExprSchema])\nconst ValidWhenSchema = z.preprocess(value => {\n  if (\n    value !== null &&\n    value !== undefined &&\n    typeof value === 'object' &&\n    !Array.isArray(value) &&\n    (value as { type?: unknown }).type === ExpressionType.ITERATE\n  ) {\n    return [value]\n  }\n\n  return value\n}, z.array(ValidWhenItemSchema))\n\n/**\n * @see {@link BlockDefinition}\n */\nconst BlockSchema: z.ZodType<any> = z.lazy(() => {\n  const baseBlock = z.looseObject({\n    type: z.literal(StructureType.BLOCK),\n    variant: z.string(),\n    visibleWhen: ResolvableBooleanSchema.optional(),\n    metadata: z.record(z.string(), z.any()).optional(),\n  })\n\n  const fieldBlockProps = z.looseObject({\n    code: ResolvableStringSchema,\n    defaultValue: z.union([ResolvableStringSchema, z.array(ResolvableStringSchema), FunctionExprSchema]).optional(),\n    formatters: z.array(TransformerFunctionExprSchema).optional(),\n    parsers: z.array(TransformerFunctionExprSchema).optional(),\n    errors: z\n      .array(\n        z.object({\n          message: z.string().trim().min(1, { message: 'Validation message must not be empty' }),\n          details: z.record(z.string(), z.any()).optional(),\n        }),\n      )\n      .optional(),\n    validWhen: ValidWhenSchema.optional(),\n    dependentWhen: PredicateExprSchema.optional(),\n  })\n\n  const fieldBlock = baseBlock.extend({\n    blockType: z.literal(BlockType.FIELD),\n    ...fieldBlockProps.shape,\n  })\n\n  const basicBlock = baseBlock.extend({\n    blockType: z.literal(BlockType.BASIC),\n  })\n\n  return z.discriminatedUnion('blockType', [fieldBlock, basicBlock])\n})\n\n/**\n * @see {@link AccessHook}\n *\n * Access hooks handle access control, data loading, and outcomes.\n * All properties except `type` are optional.\n */\nconst AccessHookSchema = z.object({\n  type: z.literal(HookType.ACCESS),\n  when: PredicateExprSchema.optional(),\n  effects: z.array(EffectFunctionExprSchema).optional(),\n  next: z.array(HookOutcomeSchema).optional(),\n})\n\n/**\n * @see {@link SubmitHook}\n */\nconst SubmitHookSchema = z.object({\n  type: z.literal(HookType.SUBMIT),\n  when: PredicateExprSchema.optional(),\n  guards: PredicateExprSchema.optional(),\n  validate: z\n    .union([\n      z.boolean(),\n      z.object({\n        groups: z.array(z.string().trim().min(1)).min(1),\n      }),\n    ])\n    .optional(),\n  onAlways: z\n    .object({\n      effects: z.array(EffectFunctionExprSchema).optional(),\n      next: z.array(HookOutcomeSchema).optional(),\n    })\n    .optional(),\n  onValid: z\n    .object({\n      effects: z.array(EffectFunctionExprSchema).optional(),\n      next: z.array(HookOutcomeSchema).optional(),\n    })\n    .optional(),\n  onInvalid: z\n    .object({\n      effects: z.array(EffectFunctionExprSchema).optional(),\n      next: z.array(HookOutcomeSchema).optional(),\n    })\n    .optional(),\n})\n\nconst TieBreakerSchema = z.looseObject({\n  type: z.literal(ExpressionType.TIE_BREAKER),\n  priority: z.number(),\n  when: PredicateExprSchema.optional(),\n})\n\nconst StepReachabilitySchema = z\n  .object({\n    entryWhen: ResolvableBooleanSchema.optional(),\n    tieBreakers: z.array(TieBreakerSchema).optional(),\n  })\n  .optional()\n\nconst StepEntryValidationSchema = z.object({\n  groups: z.array(z.string().trim().min(1)).min(1),\n  when: ResolvableBooleanSchema,\n})\n\nconst JourneyReachabilitySchema = z\n  .object({\n    resumeWhen: ResolvableBooleanSchema.optional(),\n    unreachableRedirect: z.enum(['entry', 'frontier']).optional(),\n    disableReachabilityChecks: z.boolean().optional(),\n  })\n  .optional()\n\n/**\n * @see {@link StepDefinition}\n */\nconst StepSchema = z.looseObject({\n  type: z.literal(StructureType.STEP),\n  path: z.string(),\n  blocks: z.array(BlockSchema).optional(),\n  onAccess: z.array(AccessHookSchema).optional(),\n  onSubmission: z.array(SubmitHookSchema).optional(),\n  validateOnEntry: z.array(StepEntryValidationSchema).optional(),\n  title: ResolvableStringSchema,\n  description: ResolvableStringSchema.optional(),\n  view: ViewConfigSchema.optional(),\n  reachability: StepReachabilitySchema,\n  backlink: z.string().optional(),\n  metadata: RouteMetadataSchema.optional(),\n  data: StaticDataSchema.optional(),\n  validWhen: ValidWhenSchema.optional(),\n})\n\n/**\n * @see {@link JourneyDefinition}\n */\nexport const JourneySchema: z.ZodType<any> = z.lazy(() =>\n  z.looseObject({\n    type: z.literal(StructureType.JOURNEY),\n    path: z.string(),\n    code: z.string(),\n    onAccess: z.array(AccessHookSchema).optional(),\n    steps: z.array(StepSchema).optional(),\n    children: z.array(JourneySchema).optional(),\n    title: ResolvableStringSchema,\n    description: ResolvableStringSchema.optional(),\n    view: ViewConfigSchema.optional(),\n    metadata: RouteMetadataSchema.optional(),\n    data: StaticDataSchema.optional(),\n    reachability: JourneyReachabilitySchema,\n  }),\n)\n","import {\n  BlockType,\n  ExpressionType,\n  FunctionType,\n  IteratorType,\n  PredicateType,\n  StructureType,\n} from '../../authoring/types/enums'\nimport type { DSLPathSegment } from './sourceLocation.type'\n\ntype DSLRecord = Record<string, unknown>\n\nconst FUNCTION_TYPE_VALUES: ReadonlySet<string> = new Set(Object.values(FunctionType))\n\ninterface PathFormatState {\n  readonly current: unknown\n  readonly index: number\n  readonly segments: readonly string[]\n}\n\nexport default class DSLPathFormatter {\n  format(root: unknown, path: readonly DSLPathSegment[]): string {\n    const rootSegment = this.formatJourneySegment(root) ?? 'root'\n    const segments = this.formatPathSegments(path, { current: root, index: 0, segments: [rootSegment] })\n\n    return segments.join(' > ')\n  }\n\n  private formatPathSegments(path: readonly DSLPathSegment[], state: PathFormatState): readonly string[] {\n    if (state.index >= path.length) {\n      return state.segments\n    }\n\n    const pathPart = path[state.index]\n\n    if (this.isArrayIndex(pathPart)) {\n      const nextValue = Array.isArray(state.current) ? state.current[pathPart] : undefined\n      const nextSegments = [...state.segments, `[${pathPart}]`]\n\n      return this.formatPathSegments(path, { current: nextValue, index: state.index + 1, segments: nextSegments })\n    }\n\n    const nextPathPart = path[state.index + 1]\n    const propertyValue = this.getNextValue(state.current, pathPart)\n\n    if (this.isArrayIndex(nextPathPart)) {\n      const arrayValue = Array.isArray(propertyValue) ? propertyValue[nextPathPart] : undefined\n      const nextSegments = [...state.segments, this.formatArraySegment(pathPart, nextPathPart, arrayValue)]\n\n      return this.formatPathSegments(path, { current: arrayValue, index: state.index + 2, segments: nextSegments })\n    }\n\n    const propertySegments = this.formatPropertySegments(pathPart, state.current, propertyValue)\n    const nextSegments = [...state.segments, ...propertySegments]\n\n    return this.formatPathSegments(path, { current: propertyValue, index: state.index + 1, segments: nextSegments })\n  }\n\n  private formatArraySegment(key: string, index: number, value: unknown): string {\n    if (key === 'steps') {\n      return this.formatStepSegment(value) ?? `${key}[${index}]`\n    }\n\n    if (key === 'children') {\n      return this.formatJourneySegment(value) ?? `${key}[${index}]`\n    }\n\n    const base = `${key}[${index}]`\n    const context = key === 'blocks' ? this.formatBlockContext(value) : this.formatFunctionContext(value)\n\n    return context ? `${base} (${context})` : base\n  }\n\n  private formatPropertySegments(key: string, current: unknown, value: unknown): readonly string[] {\n    if (key === 'condition' && this.isPredicateTest(current) && this.formatFunctionContext(value)) {\n      return []\n    }\n\n    if (this.isRecord(current) && current.type === ExpressionType.ITERATE && key === 'input') {\n      return ['source']\n    }\n\n    if (this.isRecord(current) && current.type === ExpressionType.ITERATE && key === 'iterator') {\n      return ['source', 'iterator']\n    }\n\n    if (this.isRecord(current) && current.type === IteratorType.MAP && key === 'yield') {\n      return ['template']\n    }\n\n    return [key]\n  }\n\n  private formatJourneySegment(value: unknown): string | undefined {\n    const code = this.getStringProperty(value, 'code')\n    const path = this.getStringProperty(value, 'path')\n    const title = this.getStringProperty(value, 'title')\n\n    return code ?? (path ? this.trimPath(path) : undefined) ?? title\n  }\n\n  private formatStepSegment(value: unknown): string | undefined {\n    const code = this.getStringProperty(value, 'code')\n    const path = this.getStringProperty(value, 'path')\n    const title = this.getStringProperty(value, 'title')\n\n    return code ?? (path ? this.trimPath(path) : undefined) ?? title\n  }\n\n  private formatFunctionContext(value: unknown): string | undefined {\n    if (!this.isRecord(value)) {\n      return undefined\n    }\n\n    const type = this.getStringProperty(value, 'type')\n    const name = this.getStringProperty(value, 'name')\n\n    if (!type || !name || !FUNCTION_TYPE_VALUES.has(type)) {\n      return undefined\n    }\n\n    return `${this.formatFunctionType(type)} - ${name}`\n  }\n\n  private isPredicateTest(value: unknown): boolean {\n    return this.isRecord(value) && value.type === PredicateType.TEST\n  }\n\n  private formatBlockContext(value: unknown): string | undefined {\n    if (!this.isRecord(value) || value.type !== StructureType.BLOCK) {\n      return undefined\n    }\n\n    const variant = this.getStringProperty(value, 'variant')\n\n    if (!variant) {\n      return undefined\n    }\n\n    const code = value.blockType === BlockType.FIELD ? this.getStringProperty(value, 'code') : undefined\n\n    return code ? `${variant} - ${code}` : variant\n  }\n\n  private formatFunctionType(functionType: string): string {\n    const suffix = functionType.split('.').at(-1)\n\n    return suffix?.toLowerCase() ?? functionType\n  }\n\n  private getNextValue(current: unknown, key: string): unknown {\n    if (!this.isRecord(current)) {\n      return undefined\n    }\n\n    return current[key]\n  }\n\n  private getStringProperty(value: unknown, property: string): string | undefined {\n    if (!this.isRecord(value)) {\n      return undefined\n    }\n\n    const propertyValue = value[property]\n\n    return typeof propertyValue === 'string' && propertyValue.trim() !== '' ? propertyValue : undefined\n  }\n\n  private trimPath(path: string): string {\n    const trimmed = path.replace(/^\\/+|\\/+$/g, '')\n\n    return trimmed === '' ? path : trimmed\n  }\n\n  private isRecord(value: unknown): value is DSLRecord {\n    return typeof value === 'object' && value !== undefined && value !== null && !Array.isArray(value)\n  }\n\n  private isArrayIndex(value: unknown): value is number {\n    return typeof value === 'number'\n  }\n}\n","import DSLPathFormatter from './DSLPathFormatter'\nimport type { DSLPathSegment, DSLSourceLocation } from './sourceLocation.type'\n\nconst isValidCallsite = (value: unknown): value is { readonly stack?: string } =>\n  typeof value === 'object' &&\n  value !== null &&\n  (!('stack' in value) || typeof (value as { stack?: unknown }).stack === 'string')\n\nexport default class DSLSourceLocator {\n  constructor(\n    private readonly root: unknown,\n    private readonly pathFormatter = new DSLPathFormatter(),\n  ) {}\n\n  fromPath(path: readonly DSLPathSegment[]): DSLSourceLocation {\n    return {\n      path,\n      formattedPath: this.pathFormatter.format(this.root, path),\n    }\n  }\n\n  /**\n   * Resolves the captured author callsite for the node at the given path by\n   * reading the nearest `__callsite` stamp, walking from the node itself up\n   * through its ancestors to the root.\n   */\n  callsiteFromPath(path: readonly DSLPathSegment[]): { readonly stack?: string } | undefined {\n    const objects: object[] = []\n    let current: unknown = this.root\n\n    for (let i = 0; i < path.length && current !== null && typeof current === 'object'; i += 1) {\n      objects.push(current)\n      current = (current as Record<DSLPathSegment, unknown>)[path[i]]\n    }\n\n    if (current !== null && typeof current === 'object') {\n      objects.push(current)\n    }\n\n    for (let i = objects.length - 1; i >= 0; i -= 1) {\n      const callsite = Object.getOwnPropertyDescriptor(objects[i], '__callsite')?.value\n\n      if (isValidCallsite(callsite)) {\n        return callsite\n      }\n    }\n\n    return undefined\n  }\n}\n","import type { JourneyDefinition } from '../../../authoring/types/structures.type'\nimport ForgeSerialisationError from '../../errors/ForgeSerialisationError'\nimport ForgeSchemaError from '../../errors/ForgeSchemaError'\nimport { JourneySchema } from './schemas/structures.schema'\nimport DSLSourceLocator from '../../../shared/diagnostics/DSLSourceLocator'\nimport type { DSLPathSegment } from '../../../shared/diagnostics/sourceLocation.type'\n\nexport class DSLValidator {\n  static validateSchema(input: unknown): asserts input is JourneyDefinition {\n    const result = JourneySchema.safeParse(input)\n\n    if (!result.success) {\n      const sourceLocator = new DSLSourceLocator(input)\n      const schemaErrors = result.error.issues.map(issue => {\n        const path = issue.path.map(pathPart => (typeof pathPart === 'symbol' ? pathPart.toString() : pathPart))\n\n        return new ForgeSchemaError({\n          message: issue.message,\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          expected: 'expected' in issue && typeof issue.expected === 'string' ? issue.expected : undefined,\n          callsite: sourceLocator.callsiteFromPath(path),\n        })\n      })\n\n      throw new AggregateError(schemaErrors, 'Schema validation failed')\n    }\n  }\n\n  /**\n   * //TODO: This is probably poorly named, as it doesnt actually validate pure JSON, it validates\n   *    that an object CAN be serialised into JSON without any issue.\n   */\n  static validateJSON(input: unknown): void {\n    if (input === undefined) {\n      throw new ForgeSerialisationError({\n        message: 'Input is undefined (not valid JSON)',\n        formattedPath: 'root',\n        type: 'non_serializable',\n      })\n    }\n\n    const sourceLocator = new DSLSourceLocator(input)\n    const errors = this.checkSerializableTypes(input, [], sourceLocator)\n\n    if (errors.length > 0) {\n      throw new AggregateError(errors, 'JSON validation failed due to non-serializable types')\n    }\n\n    try {\n      const serialized = JSON.stringify(input)\n      JSON.parse(serialized)\n    } catch (error) {\n      throw new ForgeSerialisationError({\n        message: `JSON serialization failed: ${(error as Error).message}`,\n        formattedPath: sourceLocator.fromPath([]).formattedPath,\n        type: 'json_error',\n        callsite: sourceLocator.callsiteFromPath([]),\n      })\n    }\n  }\n\n  private static checkSerializableTypes(\n    obj: unknown,\n    path: DSLPathSegment[] = [],\n    sourceLocator: DSLSourceLocator = new DSLSourceLocator(obj),\n    seen = new WeakSet(),\n  ): ForgeSerialisationError[] {\n    const errors: ForgeSerialisationError[] = []\n\n    if (obj === undefined) {\n      errors.push(\n        new ForgeSerialisationError({\n          type: 'Undefined value',\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          callsite: sourceLocator.callsiteFromPath(path),\n        }),\n      )\n    } else if (typeof obj === 'function') {\n      errors.push(\n        new ForgeSerialisationError({\n          type: 'Function',\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          callsite: sourceLocator.callsiteFromPath(path),\n        }),\n      )\n    } else if (typeof obj === 'symbol') {\n      errors.push(\n        new ForgeSerialisationError({\n          type: 'Symbol',\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          callsite: sourceLocator.callsiteFromPath(path),\n        }),\n      )\n    } else if (typeof obj === 'bigint') {\n      errors.push(\n        new ForgeSerialisationError({\n          type: 'BigInt',\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          callsite: sourceLocator.callsiteFromPath(path),\n        }),\n      )\n    } else if (obj instanceof Date) {\n      errors.push(\n        new ForgeSerialisationError({\n          type: 'Date object',\n          formattedPath: sourceLocator.fromPath(path).formattedPath,\n          callsite: sourceLocator.callsiteFromPath(path),\n        }),\n      )\n    } else if (obj && typeof obj === 'object') {\n      if (seen.has(obj)) {\n        return errors\n      }\n\n      seen.add(obj)\n\n      if (Array.isArray(obj)) {\n        obj.forEach((item, i) => {\n          errors.push(...this.checkSerializableTypes(item, [...path, i], sourceLocator, seen))\n        })\n      } else if (Object.getPrototypeOf(obj) !== Object.prototype) {\n        const constructorName =\n          typeof obj.constructor === 'function' && obj.constructor.name ? obj.constructor.name : 'unknown'\n\n        errors.push(\n          new ForgeSerialisationError({\n            type: `Non-plain object (${constructorName})`,\n            formattedPath: sourceLocator.fromPath(path).formattedPath,\n          }),\n        )\n      } else {\n        Object.entries(obj).forEach(([key, value]) => {\n          errors.push(...this.checkSerializableTypes(value, [...path, key], sourceLocator, seen))\n        })\n      }\n    }\n\n    return errors\n  }\n}\n","import type { WorkContextContract, WorkHandler } from '../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../chassis/work/workTask'\nimport type { JourneyDefinition } from '../../../authoring/types/structures.type'\nimport { DSLValidator } from './DSLValidator'\n\n/**\n * Structural slice of the compilation state this phase reads. dsl-validation\n * runs before the AST exists and must not import from compilation/, so it\n * declares only the shape it needs rather than the full state type.\n */\nexport interface DslValidationTarget {\n  readonly journeyDefinition: JourneyDefinition\n}\n\nexport const COMPILATION_DSL_VALIDATION_WORK_HANDLER: WorkHandler<'compilation.dsl-validation', undefined> = {\n  kind: 'compilation.dsl-validation',\n\n  begin(ctx: WorkContextContract<DslValidationTarget, undefined>) {\n    const { journeyDefinition } = ctx.state\n\n    DSLValidator.validateJSON(journeyDefinition)\n    DSLValidator.validateSchema(journeyDefinition)\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationDslValidationTask() {\n  return createWorkTask('dsl-validation', COMPILATION_DSL_VALIDATION_WORK_HANDLER, undefined)\n}\n","import { AstNodeId, TemplateNodeId } from '../../../contracts/ast/engine.type'\n\n/**\n * Separate ID namespaces keep shared AST IDs deterministic while template\n * compilation creates stable runtime instance ID prefixes.\n */\ntype NodeIDCounterName = 'compile_ast' | 'template'\n\n/**\n * Generates deterministic compile-time IDs for the shared AST and templates.\n */\nexport class NodeIDGenerator {\n  private readonly counters = new Map<NodeIDCounterName, number>([\n    ['compile_ast', 0],\n    ['template', 0],\n  ])\n\n  /**\n   * AST IDs are used by registered AST nodes and runtime plans.\n   */\n  nextAstNodeId(): AstNodeId {\n    return this.next('compile_ast') as AstNodeId\n  }\n\n  /**\n   * Template IDs become the stable prefix for generated collection block IDs.\n   */\n  nextTemplateNodeId(): TemplateNodeId {\n    return this.next('template') as TemplateNodeId\n  }\n\n  private next(counterName: NodeIDCounterName): string {\n    const current = this.counters.get(counterName)!\n    const next = current + 1\n\n    this.counters.set(counterName, next)\n\n    return `${counterName}:${next}`\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeUnknownNodeTypeErrorOptions {\n  /** The unknown type encountered */\n  nodeType?: string\n  /** The actual node object */\n  node?: any\n  /** List of valid types (for helpful error messages) */\n  validTypes?: string[]\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeUnknownNodeTypeError extends ForgeBaseError {\n  readonly nodeType?: string\n\n  readonly node?: any\n\n  readonly validTypes?: string[]\n\n  constructor(options: ForgeUnknownNodeTypeErrorOptions) {\n    const nodeType = options.nodeType || 'undefined'\n\n    let message = `Unknown node type: ${nodeType}`\n\n    if (options.node && typeof options.node === 'object') {\n      const keys = Object.keys(options.node)\n      if (keys.length > 0) {\n        message += ` (found object with keys: ${keys.slice(0, 5).join(', ')}${keys.length > 5 ? '...' : ''})`\n      } else {\n        message += ' (found empty object)'\n      }\n    } else if (options.node !== undefined) {\n      message += ` (found ${typeof options.node}: ${JSON.stringify(options.node).slice(0, 50)})`\n    }\n\n    if (options.formattedPath) {\n      message += ` at ${options.formattedPath}`\n    }\n\n    super(message, options)\n    this.nodeType = options.nodeType\n    this.node = options.node\n    this.validTypes = options.validTypes\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeInvalidNodeErrorOptions {\n  /** Specific validation failure message */\n  message: string\n  /** The invalid node */\n  node?: any\n  /** What was expected */\n  expected?: string\n  /** What was actually found */\n  actual?: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeInvalidNodeError extends ForgeBaseError {\n  readonly node?: any\n\n  readonly expected?: string\n\n  readonly actual?: string\n\n  constructor(options: ForgeInvalidNodeErrorOptions) {\n    let { message } = options\n\n    if (options.expected && options.actual) {\n      message += ` (expected: ${options.expected}, got: ${options.actual})`\n    }\n\n    if (options.formattedPath) {\n      message += ` at ${options.formattedPath}`\n    }\n\n    super(message, options)\n    this.node = options.node\n    this.expected = options.expected\n    this.actual = options.actual\n  }\n}\n","export enum ASTNodeType {\n  JOURNEY = 'AstNode.Journey',\n  STEP = 'AstNode.Step',\n  BLOCK = 'AstNode.Block',\n  EXPRESSION = 'AstNode.Expression',\n  PREDICATE = 'AstNode.Predicate',\n  HOOK = 'AstNode.Hook',\n  OUTCOME = 'AstNode.Outcome',\n  TEMPLATE = 'AstNode.Template',\n}\n","import { ASTNode } from './engine.type'\nimport { ASTNodeType } from './enums'\nimport type { TemplateNode } from './template.type'\n\nconst AST_NODE_TYPES: ReadonlySet<string> = new Set(Object.values(ASTNodeType))\n\n/**\n * Check if a value is an AST node (excludes template nodes)\n */\nexport function isASTNode(value: any): value is ASTNode {\n  return value != null &&\n    typeof value === 'object' &&\n    typeof value.type === 'string' &&\n    value.type !== ASTNodeType.TEMPLATE &&\n    AST_NODE_TYPES.has(value.type)\n}\n\n/**\n * Check if a value is a template node\n */\nexport function isTemplateNode(value: unknown): value is TemplateNode {\n  return value != null && typeof value === 'object' && 'type' in value && value.type === ASTNodeType.TEMPLATE\n}\n","import { ASTNodeType } from '../../../contracts/ast/enums'\nimport { ASTNode } from '../../../contracts/ast/engine.type'\nimport { TemplateNode, TemplateValue } from '../../../contracts/ast/template.type'\nimport { isASTNode } from '../../../contracts/ast/nodes'\nimport { NodeIDGenerator } from '../ast-state/NodeIDGenerator'\n\nfunction isObjectValue(obj: unknown): obj is Record<string, unknown> {\n  return obj != null && typeof obj === 'object' && !Array.isArray(obj) && obj.constructor === Object\n}\n\n/**\n * Compile an AST value tree into a reusable template.\n *\n * Templates preserve the shape of AST nodes but swap the type to TEMPLATE\n * so they're excluded from traversal, registration, and normalization.\n * The original type is stored in originalType for restoration on instantiation.\n * Template IDs become stable generated runtime instance ID prefixes.\n *\n * Used by the iterate creator to compile iterator payloads once, then\n * instantiate them per collection item at runtime with fresh IDs.\n *\n * AST nodes are converted to template nodes (type swapped to TEMPLATE,\n * original type preserved, id stripped).\n * All other values (primitives, arrays, plain objects) are recursively compiled.\n */\nexport function compileTemplate(value: unknown, nodeIDGenerator: NodeIDGenerator): TemplateValue {\n  if (Array.isArray(value)) {\n    return value.map(entry => compileTemplate(entry, nodeIDGenerator))\n  }\n\n  if (!isObjectValue(value)) {\n    return value as TemplateValue\n  }\n\n  if (isASTNode(value)) {\n    return compileTemplateNode(value, nodeIDGenerator)\n  }\n\n  const compiled: Record<string, TemplateValue> = {}\n\n  Object.entries(value as Record<string, unknown>).forEach(([key, entry]) => {\n    compiled[key] = compileTemplate(entry, nodeIDGenerator)\n  })\n\n  return compiled\n}\n\nfunction compileTemplateNode(node: ASTNode, nodeIDGenerator: NodeIDGenerator): TemplateNode {\n  const compiled: TemplateNode = {\n    type: ASTNodeType.TEMPLATE,\n    originalType: node.type,\n    id: nodeIDGenerator.nextTemplateNodeId(),\n    diagnostics: node.diagnostics,\n  }\n\n  Object.entries(node).forEach(([key, value]) => {\n    if (key === 'id' || key === 'type' || key === 'diagnostics') {\n      return\n    }\n\n    if (key === 'properties' && isObjectValue(value) && !Array.isArray(value)) {\n      compiled.properties = {}\n\n      Object.entries(value as Record<string, unknown>).forEach(([propKey, propValue]) => {\n        compiled.properties![propKey] = compileTemplate(propValue, nodeIDGenerator)\n      })\n\n      return\n    }\n\n    compiled[key] = compileTemplate(value, nodeIDGenerator)\n  })\n\n  return compiled\n}\n","import { BlockDefinition, FieldBlockDefinition, RenderedBlock } from './types/structures.type'\nimport { BlockType, StructureType } from '../authoring/types/enums'\n\nfunction isBlockDefinition(obj: any): obj is BlockDefinition {\n  return obj != null && obj.type === StructureType.BLOCK\n}\n\nexport function isFieldBlockDefinition(obj: any): obj is FieldBlockDefinition {\n  return isBlockDefinition(obj) && obj.blockType === BlockType.FIELD\n}\n\nexport function isRenderedBlock(obj: unknown): obj is RenderedBlock {\n  return obj != null &&\n    typeof obj === 'object' &&\n    'html' in obj &&\n    typeof obj.html === 'string' &&\n    'block' in obj &&\n    isBlockDefinition(obj.block)\n}\n","import { isFieldBlockDefinition } from '../../../../../components/typeguards'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport { ExpressionType, BlockType } from '../../../../../authoring/types/enums'\nimport {\n  BasicBlockASTNode,\n  BlockASTNode,\n  FieldBlockASTNode,\n  JourneyASTNode,\n  JourneyReachabilityAST,\n  StepASTNode,\n  StepReachabilityAST,\n} from '../../../contracts/ast/structures.type'\nimport ForgeInvalidNodeError from '../../../../errors/ForgeInvalidNodeError'\nimport type { JourneyDefinition, StepDefinition, TieBreaker } from '../../../../../authoring/types/structures.type'\nimport type { BlockDefinition, FieldBlockDefinition } from '../../../../../components/types/structures.type'\nimport type { NodeBuildContext } from './NodeFactory'\n\nfunction isTieBreaker(obj: unknown): obj is TieBreaker {\n  return obj != null && (obj as { type?: string }).type === ExpressionType.TIE_BREAKER\n}\n\n/**\n * Journey: Top-level form container\n * Extracts properties and recursively transforms nested steps/children\n */\nexport function createJourneyNode(json: JourneyDefinition, ctx: NodeBuildContext): JourneyASTNode {\n  const { type, ...dataProperties } = json\n\n  const properties: JourneyASTNode['properties'] = {\n    code: dataProperties.code,\n    path: dataProperties.path,\n    title: ctx.transformValue(dataProperties.title),\n  }\n\n  if (dataProperties.code === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Journey requires a code property',\n      node: json,\n      expected: 'code property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (dataProperties.path === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Journey requires a path property',\n      node: json,\n      expected: 'path property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (dataProperties.title === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Journey requires a title property',\n      node: json,\n      expected: 'title property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (dataProperties.description !== undefined) {\n    properties.description = ctx.transformValue(dataProperties.description)\n  }\n\n  if (dataProperties.onAccess !== undefined) {\n    properties.onAccess = ctx.transformValue(dataProperties.onAccess)\n  }\n\n  if (dataProperties.steps !== undefined) {\n    properties.steps = ctx.transformValue(dataProperties.steps)\n  }\n\n  if (dataProperties.children !== undefined) {\n    properties.children = ctx.transformValue(dataProperties.children)\n  }\n\n  if (dataProperties.view !== undefined) {\n    properties.view = ctx.transformValue(dataProperties.view)\n  }\n\n  if (dataProperties.metadata !== undefined) {\n    properties.metadata = ctx.transformValue(dataProperties.metadata)\n  }\n\n  if (dataProperties.data !== undefined) {\n    properties.data = dataProperties.data\n  }\n\n  if (dataProperties.reachability !== undefined) {\n    const { resumeWhen, unreachableRedirect, disableReachabilityChecks } = dataProperties.reachability\n    const reachability: JourneyReachabilityAST = {}\n\n    // false compiles like undefined; only true and expressions reach the AST\n    if (resumeWhen === true) {\n      reachability.resumeWhen = true\n    } else if (resumeWhen !== undefined && resumeWhen !== false) {\n      reachability.resumeWhen = ctx.createNode(resumeWhen)\n    }\n\n    if (unreachableRedirect !== undefined) {\n      reachability.unreachableRedirect = unreachableRedirect\n    }\n\n    if (disableReachabilityChecks !== undefined) {\n      reachability.disableReachabilityChecks = disableReachabilityChecks\n    }\n\n    properties.reachability = reachability\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.JOURNEY,\n    properties,\n  }\n}\n\n/**\n * Step: Single page within a journey\n * Contains blocks and hooks for user interaction\n */\nexport function createStepNode(json: StepDefinition, ctx: NodeBuildContext): StepASTNode {\n  const { type, ...dataProperties } = json\n\n  const properties: StepASTNode['properties'] = {\n    path: json.path,\n    title: ctx.transformValue(json.title),\n  }\n\n  if (dataProperties.path === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Step requires a path property',\n      node: json,\n      expected: 'path property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (dataProperties.title === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Step requires a title property',\n      node: json,\n      expected: 'title property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (dataProperties.onAccess !== undefined) {\n    properties.onAccess = ctx.transformValue(dataProperties.onAccess)\n  }\n\n  if (dataProperties.code !== undefined) {\n    properties.code = dataProperties.code\n  }\n\n  if (dataProperties.onSubmission !== undefined) {\n    properties.onSubmission = ctx.transformValue(dataProperties.onSubmission)\n  }\n\n  if (dataProperties.validateOnEntry !== undefined) {\n    properties.validateOnEntry = dataProperties.validateOnEntry.flatMap(entry => {\n      if (entry.when === false) {\n        return []\n      }\n\n      return {\n        groups: entry.groups,\n        when: entry.when === true ? true : ctx.createNode(entry.when),\n      }\n    })\n  }\n\n  if (dataProperties.blocks !== undefined) {\n    properties.blocks = ctx.transformValue(dataProperties.blocks)\n  }\n\n  if (dataProperties.description !== undefined) {\n    properties.description = ctx.transformValue(dataProperties.description)\n  }\n\n  if (dataProperties.view !== undefined) {\n    properties.view = ctx.transformValue(dataProperties.view)\n  }\n\n  if (dataProperties.reachability !== undefined) {\n    const { entryWhen, tieBreakers } = dataProperties.reachability\n    const reachability: StepReachabilityAST = {}\n\n    // false compiles like undefined; only true and expressions reach the AST\n    if (entryWhen === true) {\n      reachability.entryWhen = true\n    } else if (entryWhen !== undefined && entryWhen !== false) {\n      reachability.entryWhen = ctx.createNode(entryWhen)\n    }\n\n    if (tieBreakers?.every(isTieBreaker)) {\n      reachability.tieBreakers = ctx.transformValue(tieBreakers)\n    }\n\n    properties.reachability = reachability\n  }\n\n  if (dataProperties.backlink !== undefined) {\n    properties.backlink = dataProperties.backlink\n  }\n\n  if (dataProperties.metadata !== undefined) {\n    properties.metadata = ctx.transformValue(dataProperties.metadata)\n  }\n\n  if (dataProperties.data !== undefined) {\n    properties.data = dataProperties.data\n  }\n\n  if (dataProperties.validWhen !== undefined) {\n    properties.validWhen = ctx.transformValue(dataProperties.validWhen)\n  }\n\n  if (dataProperties.cleardownFieldCodes !== undefined) {\n    properties.cleardownFieldCodes = dataProperties.cleardownFieldCodes\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.STEP,\n    properties,\n  }\n}\n\n/**\n * Block: UI component within a step (basic or field)\n * Basic blocks render but don't collect data; field blocks collect user data\n * via a code property.\n */\nexport function createBlockNode(json: BlockDefinition | FieldBlockDefinition, ctx: NodeBuildContext): BlockASTNode {\n  if (isFieldBlockDefinition(json)) {\n    return createFieldBlock(json, ctx)\n  }\n\n  return createBasicBlock(json, ctx)\n}\n\nfunction createBasicBlock(json: BlockDefinition, ctx: NodeBuildContext): BasicBlockASTNode {\n  const { variant, type, ...dataProperties } = json\n  const properties: BasicBlockASTNode['properties'] = {}\n\n  Object.entries(dataProperties).forEach(([key, value]) => {\n    properties[key] = ctx.transformValue(value)\n  })\n\n  if (dataProperties.metadata !== undefined) {\n    properties.metadata = dataProperties.metadata\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.BLOCK,\n    variant,\n    blockType: BlockType.BASIC,\n    properties,\n  }\n}\n\nfunction createFieldBlock(json: FieldBlockDefinition, ctx: NodeBuildContext): FieldBlockASTNode {\n  const { variant, type, ...dataProperties } = json\n\n  if (dataProperties.code === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Field block requires a code property',\n      node: json,\n      expected: 'code property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  const properties: FieldBlockASTNode['properties'] = {}\n\n  Object.entries(dataProperties).forEach(([key, value]) => {\n    properties[key] = ctx.transformValue(value)\n  })\n\n  // Override properties that should not be transformed\n  if (dataProperties.metadata !== undefined) {\n    properties.metadata = dataProperties.metadata\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.BLOCK,\n    variant,\n    blockType: BlockType.FIELD,\n    properties,\n  }\n}\n","import { ASTNodeType } from '../../../contracts/ast/enums'\nimport {\n  ConditionCombinatorType,\n  ExpressionType,\n  FunctionType,\n  IteratorType,\n  OutcomeType,\n  PredicateType,\n} from '../../../../../authoring/types/enums'\nimport {\n  ConditionalASTNode,\n  NullishASTNode,\n  FunctionASTNode,\n  IterateASTNode,\n  MatchASTNode,\n  PipelineASTNode,\n  ReferenceASTNode,\n  TieBreakerASTNode,\n  ValidationASTNode,\n} from '../../../contracts/ast/expressions.type'\nimport type { ASTNode } from '../../../contracts/ast/engine.type'\nimport type { TemplateValue } from '../../../contracts/ast/template.type'\nimport {\n  ConditionalExpr,\n  NullishExpr,\n  ConditionAndExpr,\n  ConditionCombinatorExpr,\n  ConditionBranchExpr,\n  ConditionFunctionExpr,\n  ConditionNotExpr,\n  ConditionOrExpr,\n  ConditionXorExpr,\n  FunctionExpr,\n  IterateExpr,\n  MatchExpr,\n  PipelineExpr,\n  ReferenceExpr,\n  ResolvableValue,\n} from '../../../../../authoring/types/expressions.type'\nimport type { TieBreaker, ValidationExpr } from '../../../../../authoring/types/structures.type'\nimport type { ASTNodeDiagnostics } from '../../../../../shared/diagnostics/sourceLocation.type'\nimport type {\n  AndPredicateASTNode,\n  NotPredicateASTNode,\n  OrPredicateASTNode,\n  PredicateASTNode,\n  TestPredicateASTNode,\n  XorPredicateASTNode,\n} from '../../../contracts/ast/predicates.type'\nimport ForgeInvalidNodeError from '../../../../errors/ForgeInvalidNodeError'\nimport type { NodeBuildContext } from './NodeFactory'\n\n/**\n * Every `type` discriminant that marks an authored expression, as opposed to\n * a structure (journey/step/block), a hook, or plain data.\n *\n * ExpressionType.NEXT and IteratorType are deliberately absent: nothing in\n * the authoring surface produces a NEXT expression, and iterator configs are\n * inline configuration consumed by Iterate expressions, not expressions\n * themselves.\n */\nconst EXPRESSION_TYPES: ReadonlySet<string> = new Set([\n  ExpressionType.REFERENCE,\n  ExpressionType.PIPELINE,\n  ExpressionType.NULLISH,\n  ExpressionType.CONDITIONAL,\n  ExpressionType.MATCH,\n  ExpressionType.ITERATE,\n  ExpressionType.VALIDATION,\n  ExpressionType.TIE_BREAKER,\n  ...Object.values(PredicateType),\n  ...Object.values(ConditionCombinatorType),\n  ...Object.values(FunctionType),\n  ...Object.values(OutcomeType),\n])\n\nfunction isExpression(node: any): boolean {\n  return node != null && EXPRESSION_TYPES.has(node.type)\n}\n\nconst CONDITION_COMBINATOR_TYPES: ReadonlySet<string> = new Set(Object.values(ConditionCombinatorType))\n\nfunction isConditionNotExpr(obj: any): obj is ConditionNotExpr {\n  return obj != null && obj.type === ConditionCombinatorType.NOT\n}\n\nfunction isConditionCombinatorExpr(obj: any): obj is ConditionCombinatorExpr {\n  return obj != null && CONDITION_COMBINATOR_TYPES.has(obj.type)\n}\n\n/**\n * Reference: Points to data in context\n * Examples: Answer('field'), Data('external.value'), Self(), Item()\n *\n * When `base` is present, the reference evaluates the base expression first\n * and then navigates into the result using the path. Empty path is valid\n * when base is present (returns base result directly).\n */\nexport function createReferenceNode(json: ReferenceExpr, ctx: NodeBuildContext): ReferenceASTNode {\n  // Transform base expression if present\n  const base = json.base ? ctx.transformValue<ASTNode>(json.base) : undefined\n\n  // Build path - allow empty path when base is present\n  const referencePath = buildReferencePath(json.path, ctx, !!base)\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.REFERENCE,\n    properties: { path: referencePath, base },\n  }\n}\n\n/**\n * Build the reference path, transforming any dynamic expressions.\n * Path splitting is done at the builder level - the creator just passes through.\n */\nfunction buildReferencePath(\n  path: readonly unknown[],\n  ctx: NodeBuildContext,\n  allowEmpty = false,\n): ReferenceASTNode['properties']['path'] {\n  if (!Array.isArray(path) || (!allowEmpty && path.length === 0)) {\n    throw new ForgeInvalidNodeError({\n      message: 'Reference path must be a non-empty array',\n      actual: JSON.stringify(path),\n    })\n  }\n\n  // Transform any expressions in the path (e.g., dynamic keys)\n  return path.map(segment => (isExpression(segment) ? ctx.transformValue(segment) : assertReferenceSegment(segment)))\n}\n\nfunction assertReferenceSegment(segment: unknown): string | number {\n  if (typeof segment === 'string' || typeof segment === 'number') {\n    return segment\n  }\n\n  throw new ForgeInvalidNodeError({\n    message: 'Reference path segments must be strings, numbers, or expressions',\n    actual: JSON.stringify(segment),\n  })\n}\n\n/**\n * Pipeline: Sequential data transformations\n * Input flows through each step: input -> step1 -> step2 -> output\n */\nexport function createPipelineNode(json: PipelineExpr, ctx: NodeBuildContext): PipelineASTNode {\n  // Initial value to transform - use transformValue to support both AST nodes and literals\n  const input = ctx.transformValue(json.input)\n\n  // Transform each pipeline step\n  const steps = json.steps.map((arg: unknown) => ctx.transformValue<ASTNode>(arg))\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.PIPELINE,\n    properties: {\n      input,\n      steps,\n    },\n  }\n}\n\n/**\n * Conditional: If-then-else logic, evaluating a predicate to choose between\n * two values. Defaults: thenValue = true, elseValue = false\n */\nexport function createConditionalNode(json: ConditionalExpr, ctx: NodeBuildContext): ConditionalASTNode {\n  if (!json.predicate) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Conditional expression requires a predicate',\n      node: json,\n      expected: 'predicate property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.CONDITIONAL,\n    properties: {\n      predicate: ctx.createNode(json.predicate),\n      thenValue: json.thenValue !== undefined ? ctx.transformValue(json.thenValue) : true,\n      elseValue: json.elseValue !== undefined ? ctx.transformValue(json.elseValue) : false,\n    },\n  }\n}\n\n/**\n * Iterate: Per-item iteration over collections\n * Iterator payloads are compiled once into reusable templates.\n * At runtime, those templates are instantiated per collection item with fresh IDs.\n */\nexport function createIterateNode(json: IterateExpr, ctx: NodeBuildContext): IterateASTNode {\n  const properties: {\n    input: ASTNode | unknown\n    iterator: {\n      type: IteratorType\n      yieldTemplate?: TemplateValue\n      predicateTemplate?: TemplateValue\n    }\n  } = {\n    // Transform the input data source (this IS an expression that needs evaluation)\n    input: ctx.transformValue(json.input),\n    iterator: {\n      type: json.iterator.type,\n    },\n  }\n\n  switch (json.iterator.type) {\n    // For MAP: compile yield template once and instantiate per item at runtime\n    case IteratorType.MAP:\n      properties.iterator.yieldTemplate = compileIteratorTemplate(json.iterator.yield, ctx)\n      break\n    // For FILTER/FIND: compile predicate template once and instantiate per item at runtime\n    case IteratorType.FILTER:\n    case IteratorType.FIND:\n    case IteratorType.SOME:\n    case IteratorType.EVERY:\n    case IteratorType.COUNT:\n      properties.iterator.predicateTemplate = compileIteratorTemplate(json.iterator.predicate, ctx)\n      break\n    default:\n      // Unknown iterator types compile without a template, matching the old\n      // guard-based behaviour; semantic analysis owns rejecting them.\n      break\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.ITERATE,\n    properties,\n  }\n}\n\nfunction compileIteratorTemplate(template: unknown, ctx: NodeBuildContext): TemplateValue {\n  return ctx.compileTemplate(ctx.transformValue(template))\n}\n\n/**\n * Validation: Field validation rules\n * Contains predicate condition and error message.\n */\nexport function createValidationNode(json: ValidationExpr, ctx: NodeBuildContext): ValidationASTNode {\n  const properties: {\n    condition: ASTNode\n    message: ASTNode | string\n    submissionOnly?: boolean\n    groups?: string[]\n    details?: Record<string, unknown>\n  } = {\n    condition: ctx.createNode(json.condition),\n    message: ctx.transformValue(json.message || ''),\n    submissionOnly: false,\n    groups: json.groups ?? ['default'],\n  }\n\n  if (json.submissionOnly !== undefined) {\n    properties.submissionOnly = json.submissionOnly\n  }\n\n  if (json.details) {\n    properties.details = ctx.transformValue(json.details)\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.VALIDATION,\n    properties,\n  }\n}\n\n/**\n * TieBreaker: Reachability priority rule with an optional condition\n */\nexport function createTieBreakerNode(json: TieBreaker, ctx: NodeBuildContext): TieBreakerASTNode {\n  const properties: TieBreakerASTNode['properties'] = {\n    priority: json.priority,\n  }\n\n  if (json.when !== undefined) {\n    properties.when = ctx.createNode(json.when)\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.TIE_BREAKER,\n    properties,\n  }\n}\n\n/**\n * Function: Registered function calls\n * Types: Condition (boolean), Transformer (value), Effect (side-effect), Generator (value)\n */\nexport function createFunctionNode(json: FunctionExpr<ResolvableValue[]>, ctx: NodeBuildContext): FunctionASTNode {\n  const funcType = json.type\n\n  // Transform arguments recursively\n  const args = json.arguments.map((arg: unknown) => ctx.transformValue(arg))\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: funcType,\n    properties: {\n      name: json.name,\n      arguments: args,\n    },\n  }\n}\n\n/** The shared match subject and root branch condition every synthesised predicate needs. */\ninterface BranchConditionContext {\n  subject: ResolvableValue\n  branchCondition: ConditionBranchExpr\n}\n\nconst LOGICAL_PREDICATE_TYPES = {\n  [ConditionCombinatorType.AND]: PredicateType.AND,\n  [ConditionCombinatorType.OR]: PredicateType.OR,\n  [ConditionCombinatorType.XOR]: PredicateType.XOR,\n} as const\n\n/**\n * Match: Evaluates a subject against multiple branches, returning the value\n * of the first branch whose condition matches.\n *\n * A branch condition is either a single condition or a subject-less combinator\n * tree over conditions. The creator expands that tree into the predicate nodes\n * the engine already understands: each condition leaf becomes a TEST predicate\n * pairing the shared match subject with the leaf, and each combinator becomes\n * the matching AND/OR/XOR/NOT predicate over its expanded operands.\n */\nexport function createMatchNode(json: MatchExpr, ctx: NodeBuildContext): MatchASTNode {\n  // Only undefined means missing - 0, '' and false are legal literal subjects\n  if (json.subject === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Match expression requires a subject',\n      node: json,\n      expected: 'subject property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (!json.branches || json.branches.length === 0) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Match expression requires at least one branch',\n      node: json,\n      expected: 'non-empty branches array',\n      actual: json.branches ? 'empty array' : 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  const compiledBranches = json.branches.map(branch => ({\n    ...('condition' in branch\n      ? {\n          predicate: expandCondition(\n            branch.condition,\n            { subject: json.subject, branchCondition: branch.condition },\n            ctx,\n          ),\n        }\n      : { expected: ctx.transformValue(branch.expected) }),\n    value: ctx.transformValue(branch.value),\n  }))\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.MATCH,\n    properties: {\n      subject: ctx.transformValue(json.subject),\n      branches: compiledBranches,\n      ...(json.otherwise !== undefined && {\n        otherwise: ctx.transformValue(json.otherwise),\n      }),\n    },\n  }\n}\n\nfunction expandCondition(\n  condition: ConditionBranchExpr,\n  context: BranchConditionContext,\n  ctx: NodeBuildContext,\n): PredicateASTNode {\n  if (isConditionNotExpr(condition)) {\n    return createNotPredicate(condition, context, ctx)\n  }\n\n  if (isConditionCombinatorExpr(condition)) {\n    return createLogicalPredicate(condition, context, ctx)\n  }\n\n  return createTestPredicate(condition, context, ctx)\n}\n\nfunction createTestPredicate(\n  condition: ConditionFunctionExpr,\n  context: BranchConditionContext,\n  ctx: NodeBuildContext,\n): TestPredicateASTNode {\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.PREDICATE,\n    predicateType: PredicateType.TEST,\n    ...createBranchDiagnostics(context, ctx),\n    properties: {\n      subject: ctx.transformValue(context.subject),\n      condition: ctx.createNode(condition),\n      negate: false,\n    },\n  }\n}\n\nfunction createNotPredicate(\n  combinator: ConditionNotExpr,\n  context: BranchConditionContext,\n  ctx: NodeBuildContext,\n): NotPredicateASTNode {\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.PREDICATE,\n    predicateType: PredicateType.NOT,\n    ...createBranchDiagnostics(context, ctx),\n    properties: {\n      operand: expandCondition(combinator.operand, context, ctx),\n    },\n  }\n}\n\nfunction createLogicalPredicate(\n  combinator: ConditionAndExpr | ConditionOrExpr | ConditionXorExpr,\n  context: BranchConditionContext,\n  ctx: NodeBuildContext,\n): AndPredicateASTNode | OrPredicateASTNode | XorPredicateASTNode {\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.PREDICATE,\n    predicateType: LOGICAL_PREDICATE_TYPES[combinator.type],\n    ...createBranchDiagnostics(context, ctx),\n    properties: {\n      operands: combinator.operands.map(operand => expandCondition(operand, context, ctx)),\n    },\n  } as AndPredicateASTNode | OrPredicateASTNode | XorPredicateASTNode\n}\n\nfunction createBranchDiagnostics(\n  context: BranchConditionContext,\n  ctx: NodeBuildContext,\n): { diagnostics: ASTNodeDiagnostics } | undefined {\n  const diagnostics = ctx.diagnosticsFor(context.branchCondition)\n\n  return diagnostics && { diagnostics }\n}\n\n/** Builds both operands for analysis while leaving fallback evaluation to lowering. */\nexport function createNullishNode(json: NullishExpr, ctx: NodeBuildContext): NullishASTNode {\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.EXPRESSION,\n    expressionType: ExpressionType.NULLISH,\n    properties: {\n      input: ctx.transformValue(json.input),\n      fallback: ctx.transformValue(json.fallback),\n    },\n  }\n}\n","import { ASTNodeType } from '../../../contracts/ast/enums'\nimport { PredicateType } from '../../../../../authoring/types/enums'\nimport {\n  PredicateAndExpr,\n  PredicateNotExpr,\n  PredicateOrExpr,\n  PredicateTestExpr,\n  PredicateXorExpr,\n} from '../../../../../authoring/types/expressions.type'\nimport ForgeInvalidNodeError from '../../../../errors/ForgeInvalidNodeError'\nimport {\n  AndPredicateASTNode,\n  NotPredicateASTNode,\n  OrPredicateASTNode,\n  PredicateASTNode,\n  TestPredicateASTNode,\n  XorPredicateASTNode,\n} from '../../../contracts/ast/predicates.type'\nimport type { NodeBuildContext } from './NodeFactory'\n\ntype PredicateNaryExpr = PredicateAndExpr | PredicateOrExpr | PredicateXorExpr\ntype NaryPredicateASTNode = AndPredicateASTNode | OrPredicateASTNode | XorPredicateASTNode\n\nconst NARY_PREDICATE_NAMES = {\n  [PredicateType.AND]: 'And',\n  [PredicateType.OR]: 'Or',\n  [PredicateType.XOR]: 'Xor',\n} as const\n\n/**\n * Test: subject.condition with optional negation\n * Defaults: negate = false\n */\nexport function createTestPredicateNode(json: PredicateTestExpr, ctx: NodeBuildContext): TestPredicateASTNode {\n  // Only undefined means missing - 0, '' and false are legal literal subjects\n  if (json.subject === undefined) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Test predicate requires a subject',\n      node: json,\n      expected: 'subject property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  if (!json.condition) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Test predicate requires a condition',\n      node: json,\n      expected: 'condition property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.PREDICATE,\n    predicateType: PredicateType.TEST,\n    properties: {\n      // Use transformValue to support both AST nodes and literals\n      subject: ctx.transformValue(json.subject),\n      condition: ctx.createNode(json.condition),\n      negate: json.negate ?? false,\n    },\n  }\n}\n\n/**\n * Not: Single operand negation\n */\nexport function createNotPredicateNode(json: PredicateNotExpr, ctx: NodeBuildContext): NotPredicateASTNode {\n  if (!json.operand) {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: 'Not predicate requires an operand',\n      node: json,\n      expected: 'operand property',\n      actual: 'undefined',\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.PREDICATE,\n    predicateType: PredicateType.NOT,\n    properties: {\n      operand: ctx.createNode(json.operand),\n    },\n  }\n}\n\n/**\n * And/Or/Xor: Multiple operands combined by the given predicate type.\n * The three n-ary predicates only differ by their discriminant, so one\n * parameterised creator covers all of them.\n */\nexport function naryPredicateCreator(\n  predicateType: PredicateType.AND | PredicateType.OR | PredicateType.XOR,\n): (json: PredicateNaryExpr, ctx: NodeBuildContext) => NaryPredicateASTNode {\n  return (json, ctx) => {\n    if (!json.operands || !Array.isArray(json.operands) || json.operands.length === 0) {\n      const diagnostics = ctx.diagnosticsFor(json)\n\n      throw new ForgeInvalidNodeError({\n        message: `${NARY_PREDICATE_NAMES[predicateType]} predicate requires a non-empty operands array`,\n        node: json,\n        expected: 'operands array with at least one element',\n        actual: json.operands ? `array with ${json.operands.length} elements` : 'undefined',\n        formattedPath: diagnostics?.source.formattedPath,\n        callsite: diagnostics?.callsite,\n      })\n    }\n\n    return {\n      id: ctx.nextId(),\n      type: ASTNodeType.PREDICATE,\n      predicateType,\n      properties: {\n        operands: json.operands.map((operand: unknown) => ctx.createNode(operand)) as PredicateASTNode[],\n      },\n    } as NaryPredicateASTNode\n  }\n}\n","import { ASTNodeType } from '../../../contracts/ast/enums'\nimport { HookType } from '../../../../../authoring/types/enums'\nimport { AccessHookASTNode, SubmitHookASTNode } from '../../../contracts/ast/expressions.type'\nimport { AccessHook, SubmitHook } from '../../../../../authoring/types/expressions.type'\nimport type { ASTNode } from '../../../contracts/ast/engine.type'\nimport type { NodeBuildContext } from './NodeFactory'\n\ntype SubmitBranch = NonNullable<SubmitHook['onAlways']>\ntype SubmitBranchAST = {\n  effects?: ASTNode[]\n  next?: ASTNode[]\n}\n\n/**\n * Access hook: Access control, data loading, and outcomes through:\n * - `when` conditions for conditional execution\n * - `effects` for data loading and side effects\n * - `next` outcomes for redirects and errors (first-match semantics)\n */\nexport function createAccessHookNode(json: AccessHook, ctx: NodeBuildContext): AccessHookASTNode {\n  const properties: AccessHookASTNode['properties'] = {}\n\n  if (json.when) {\n    properties.when = ctx.createNode(json.when)\n  }\n\n  if (Array.isArray(json.effects)) {\n    properties.effects = json.effects.map((effect: unknown) => ctx.createNode(effect))\n  }\n\n  if (Array.isArray(json.next)) {\n    properties.next = json.next.map((outcome: unknown) => ctx.createNode(outcome))\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.HOOK,\n    hookType: HookType.ACCESS,\n    properties,\n  }\n}\n\n/**\n * Submit hook: Form submission handling\n * Manages validation, effects, and navigation on submit\n */\nexport function createSubmitHookNode(json: SubmitHook, ctx: NodeBuildContext): SubmitHookASTNode {\n  const properties: SubmitHookASTNode['properties'] = {\n    validate: json.validate !== undefined && json.validate !== false,\n    validationGroups: getValidationGroups(json.validate),\n  }\n\n  if (json.when) {\n    properties.when = ctx.createNode(json.when)\n  }\n\n  if (json.guards) {\n    properties.guards = ctx.createNode(json.guards)\n  }\n\n  if (json.onAlways) {\n    properties.onAlways = transformBranch(json.onAlways, ctx)\n  }\n\n  if (json.onValid) {\n    properties.onValid = transformBranch(json.onValid, ctx)\n  }\n\n  if (json.onInvalid) {\n    properties.onInvalid = transformBranch(json.onInvalid, ctx)\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.HOOK,\n    hookType: HookType.SUBMIT,\n    properties,\n  }\n}\n\nfunction getValidationGroups(validate: SubmitHook['validate']): string[] {\n  if (validate === true) {\n    return ['default']\n  }\n\n  if (validate === false || validate === undefined) {\n    return []\n  }\n\n  return validate.groups\n}\n\nfunction transformBranch(branch: SubmitBranch, ctx: NodeBuildContext): SubmitBranchAST {\n  const result: SubmitBranchAST = {}\n\n  if (Array.isArray(branch.effects)) {\n    result.effects = branch.effects.map(effect => ctx.createNode(effect))\n  }\n\n  if (Array.isArray(branch.next)) {\n    result.next = branch.next.map(next => ctx.createNode(next))\n  }\n\n  return result\n}\n","import { ASTNodeType } from '../../../contracts/ast/enums'\nimport { OutcomeType } from '../../../../../authoring/types/enums'\nimport { RedirectOutcomeASTNode, ThrowErrorOutcomeASTNode } from '../../../contracts/ast/expressions.type'\nimport type { ASTNode } from '../../../contracts/ast/engine.type'\nimport { RedirectOutcome, ThrowErrorOutcome } from '../../../../../authoring/types/expressions.type'\nimport type { NodeBuildContext } from './NodeFactory'\n\n/**\n * Redirect outcome: Navigation target within hooks\n * Contains optional condition and destination path.\n */\nexport function createRedirectOutcomeNode(json: RedirectOutcome, ctx: NodeBuildContext): RedirectOutcomeASTNode {\n  const properties: { when?: ASTNode; goto: ASTNode | string } = {\n    goto: ctx.transformValue(json.goto),\n  }\n\n  if (json.when) {\n    properties.when = ctx.createNode(json.when)\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.OUTCOME,\n    outcomeType: OutcomeType.REDIRECT,\n    properties,\n  }\n}\n\n/**\n * ThrowError outcome: HTTP error response within hooks\n * Contains optional condition, required status code, and message.\n */\nexport function createThrowErrorOutcomeNode(json: ThrowErrorOutcome, ctx: NodeBuildContext): ThrowErrorOutcomeASTNode {\n  const properties: { when?: ASTNode; status: number; message: ASTNode | string } = {\n    status: json.status,\n    message: typeof json.message === 'string' ? json.message : ctx.transformValue(json.message),\n  }\n\n  if (json.when) {\n    properties.when = ctx.createNode(json.when)\n  }\n\n  return {\n    id: ctx.nextId(),\n    type: ASTNodeType.OUTCOME,\n    outcomeType: OutcomeType.THROW_ERROR,\n    properties,\n  }\n}\n","import ForgeUnknownNodeTypeError from '../../../../errors/ForgeUnknownNodeTypeError'\nimport ForgeInvalidNodeError from '../../../../errors/ForgeInvalidNodeError'\nimport type { ASTNode, AstNodeId } from '../../../contracts/ast/engine.type'\nimport { NodeIDGenerator } from '../ast-state/NodeIDGenerator'\nimport type { TemplateValue } from '../../../contracts/ast/template.type'\nimport type { ASTNodeDiagnostics, DSLSourceLocation } from '../../../../../shared/diagnostics/sourceLocation.type'\nimport { compileTemplate } from './template'\nimport {\n  ConditionCombinatorType,\n  ExpressionType,\n  FunctionType,\n  HookType,\n  IteratorType,\n  OutcomeType,\n  PredicateType,\n  StructureType,\n} from '../../../../../authoring/types/enums'\nimport { createBlockNode, createJourneyNode, createStepNode } from './structures'\nimport {\n  createConditionalNode,\n  createFunctionNode,\n  createIterateNode,\n  createMatchNode,\n  createPipelineNode,\n  createNullishNode,\n  createReferenceNode,\n  createTieBreakerNode,\n  createValidationNode,\n} from './expressions'\nimport { createNotPredicateNode, createTestPredicateNode, naryPredicateCreator } from './predicates'\nimport { createAccessHookNode, createSubmitHookNode } from './hooks'\nimport { createRedirectOutcomeNode, createThrowErrorOutcomeNode } from './outcomes'\n\n/**\n * The services a node creator borrows from the walker: ID allocation,\n * recursion back into node creation, value transformation, iterator template\n * compilation, and source diagnostics lookup.\n *\n * Passed at call time rather than construction time, so creators are plain\n * functions and there is no circular wiring between the walker and the\n * creators it dispatches to.\n */\nexport interface NodeBuildContext {\n  nextId(): AstNodeId\n  createNode(json: unknown): ASTNode\n  transformValue<T = unknown>(value: unknown): T\n  compileTemplate(value: unknown): TemplateValue\n  diagnosticsFor(json: unknown): ASTNodeDiagnostics | undefined\n}\n\n/**\n * A node creator turns one authored definition into its AST node. Creators\n * are selected from the `creatorsByType` table below by the `type`\n * discriminant, so a creator can assume the input already carries its type.\n */\n\nexport type NodeCreator<TIn = any> = (json: TIn, ctx: NodeBuildContext) => ASTNode\n\n/**\n * Some authored objects carry a `type` discriminant but are not standalone AST\n * nodes - they're consumed inline by the creator of their parent node. A stray\n * one anywhere else is an authoring mistake, so its creator always throws,\n * saying where the object actually belongs.\n */\nconst notConstructible =\n  (reason: string): NodeCreator =>\n  (json: unknown, ctx: NodeBuildContext) => {\n    const diagnostics = ctx.diagnosticsFor(json)\n\n    throw new ForgeInvalidNodeError({\n      message: reason,\n      node: json,\n      actual: (json as { type?: string }).type,\n      formattedPath: diagnostics?.source.formattedPath,\n      callsite: diagnostics?.callsite,\n    })\n  }\n\nconst COMBINATOR_PLACEMENT = 'Condition combinators can only appear inside a match expression branch condition'\nconst ITERATOR_PLACEMENT = 'Iterator configurations can only appear inside the iterator of an Iterate expression'\n\n/**\n * The discriminants of the inline-only types. Anything carrying one of these\n * strings outside its one legal spot throws the placement error - even a\n * coincidental data object - but the valid-types list must not advertise them\n * as constructible.\n */\nconst INLINE_ONLY_TYPES: ReadonlySet<string> = new Set([\n  ...Object.values(ConditionCombinatorType),\n  ...Object.values(IteratorType),\n])\n\n/**\n * The complete registry of every `type` discriminant the DSL can emit - one\n * row per enum value. Discriminant values are namespaced strings\n * ('StructureType.Journey', 'PredicateType.And', ...), so they are globally\n * unique and one flat map covers every node family.\n *\n * This map is the single source for dispatch (`createNode`), node detection\n * (`isNode`), and the valid-types list in `ForgeUnknownNodeTypeError` - the list\n * minus the `INLINE_ONLY_TYPES` rows. Adding a node type means adding a\n * creator and a row here; the completeness test in `NodeFactory.test.ts`\n * fails if an enum value has no row.\n *\n * `ExpressionType.NEXT` is deliberately absent: nothing in the authoring\n * surface produces it and no factory ever created it.\n */\nexport const creatorsByType: ReadonlyMap<string, NodeCreator> = new Map<string, NodeCreator>([\n  // Structures\n  [StructureType.JOURNEY, createJourneyNode],\n  [StructureType.STEP, createStepNode],\n  [StructureType.BLOCK, createBlockNode],\n\n  // Expressions\n  [ExpressionType.REFERENCE, createReferenceNode],\n  [ExpressionType.PIPELINE, createPipelineNode],\n  [ExpressionType.NULLISH, createNullishNode],\n  [ExpressionType.CONDITIONAL, createConditionalNode],\n  [ExpressionType.MATCH, createMatchNode],\n  [ExpressionType.ITERATE, createIterateNode],\n  [ExpressionType.VALIDATION, createValidationNode],\n  [ExpressionType.TIE_BREAKER, createTieBreakerNode],\n\n  // Predicates\n  [PredicateType.TEST, createTestPredicateNode],\n  [PredicateType.NOT, createNotPredicateNode],\n  [PredicateType.AND, naryPredicateCreator(PredicateType.AND)],\n  [PredicateType.OR, naryPredicateCreator(PredicateType.OR)],\n  [PredicateType.XOR, naryPredicateCreator(PredicateType.XOR)],\n\n  // Registered function calls\n  [FunctionType.CONDITION, createFunctionNode],\n  [FunctionType.TRANSFORMER, createFunctionNode],\n  [FunctionType.GENERATOR, createFunctionNode],\n  [FunctionType.EFFECT, createFunctionNode],\n\n  // Hooks\n  [HookType.ACCESS, createAccessHookNode],\n  [HookType.SUBMIT, createSubmitHookNode],\n\n  // Hook outcomes\n  [OutcomeType.REDIRECT, createRedirectOutcomeNode],\n  [OutcomeType.THROW_ERROR, createThrowErrorOutcomeNode],\n\n  // Inline-only types - recognised, but never standalone AST nodes\n  [ConditionCombinatorType.AND, notConstructible(COMBINATOR_PLACEMENT)],\n  [ConditionCombinatorType.OR, notConstructible(COMBINATOR_PLACEMENT)],\n  [ConditionCombinatorType.XOR, notConstructible(COMBINATOR_PLACEMENT)],\n  [ConditionCombinatorType.NOT, notConstructible(COMBINATOR_PLACEMENT)],\n  [IteratorType.MAP, notConstructible(ITERATOR_PLACEMENT)],\n  [IteratorType.FILTER, notConstructible(ITERATOR_PLACEMENT)],\n  [IteratorType.FIND, notConstructible(ITERATOR_PLACEMENT)],\n  [IteratorType.SOME, notConstructible(ITERATOR_PLACEMENT)],\n  [IteratorType.EVERY, notConstructible(ITERATOR_PLACEMENT)],\n  [IteratorType.COUNT, notConstructible(ITERATOR_PLACEMENT)],\n])\n\n/**\n * NodeFactory: Main entry point for creating AST nodes\n *\n * A walker over authored definitions. Node creation dispatches through the\n * `creatorsByType` table keyed on the `type` discriminant; the creators call\n * back in through `NodeBuildContext` for IDs, recursion, and diagnostics.\n *\n * Source diagnostics are read off the non-enumerable `__source` (and\n * `__callsite`) stamps that finaliseBuilders attaches to every object node of\n * finalised configuration. Unstamped input compiles without diagnostics;\n * downstream consumers fall back to 'unknown'.\n */\nexport class NodeFactory {\n  /** The services creators borrow from the walker. Public so tests can call creators directly. */\n  readonly context: NodeBuildContext\n\n  constructor(private readonly nodeIDGenerator: NodeIDGenerator) {\n    this.context = {\n      nextId: () => this.nodeIDGenerator.nextAstNodeId(),\n      createNode: json => this.createNode(json),\n      transformValue: <T>(value: unknown): T => this.transformValue(value),\n      compileTemplate: value => compileTemplate(value, this.nodeIDGenerator),\n      diagnosticsFor: json => this.diagnosticsFor(json),\n    }\n  }\n\n  /**\n   * Main entry point for transformation\n   * Looks up the node's creator by its `type` discriminant and runs it\n   */\n  createNode(json: unknown): ASTNode {\n    if (!json || typeof json !== 'object') {\n      throw new ForgeInvalidNodeError({\n        message: `Invalid node: expected object, got ${typeof json}`,\n        node: json,\n        expected: 'object',\n        actual: typeof json,\n      })\n    }\n\n    const nodeType = this.getNodeType(json)\n    const create = nodeType === undefined ? undefined : creatorsByType.get(nodeType)\n\n    if (!create) {\n      const diagnostics = this.diagnosticsFor(json)\n\n      throw new ForgeUnknownNodeTypeError({\n        nodeType,\n        node: json,\n        validTypes: [...creatorsByType.keys()].filter(type => !INLINE_ONLY_TYPES.has(type)),\n        formattedPath: diagnostics?.source.formattedPath,\n        callsite: diagnostics?.callsite,\n      })\n    }\n\n    return this.withDiagnostics(create(json, this.context), json)\n  }\n\n  /**\n   * Transform value: Recursive processor for any JSON value\n   * Detects and transforms nested nodes while preserving primitives\n   */\n  transformValue<T = unknown>(value: unknown): T {\n    // Preserve null/undefined as-is\n    if (value === null || value === undefined) {\n      return value as T\n    }\n\n    // Primitives (string, number, boolean) pass through\n    if (typeof value !== 'object') {\n      return value as T\n    }\n\n    // Arrays: Transform each element recursively\n    if (Array.isArray(value)) {\n      return value.map(item => this.transformValue(item)) as T\n    }\n\n    // Detect AST nodes and transform them\n    if (this.isNode(value)) {\n      return this.createNode(value) as T\n    }\n\n    // Plain objects: Recursively check properties for nested nodes\n    // Critical for finding blocks inside component properties\n    const result: Record<string, unknown> = {}\n\n    Object.entries(value).forEach(([key, val]) => {\n      result[key] = this.transformValue(val)\n    })\n\n    return result as T\n  }\n\n  /**\n   * Derive AST node diagnostics from the source stamps on a JSON node.\n   * Returns undefined for unstamped input.\n   */\n  diagnosticsFor(json: unknown): ASTNodeDiagnostics | undefined {\n    if (json === null || typeof json !== 'object') {\n      return undefined\n    }\n\n    const source = Object.getOwnPropertyDescriptor(json, '__source')?.value as DSLSourceLocation | undefined\n\n    if (!source) {\n      return undefined\n    }\n\n    const callsite = Object.getOwnPropertyDescriptor(json, '__callsite')?.value as { stack?: string } | undefined\n\n    return {\n      source,\n      ...(callsite && { callsite }),\n    }\n  }\n\n  private withDiagnostics<TNode extends ASTNode>(node: TNode, json: unknown): TNode {\n    const diagnostics = this.diagnosticsFor(json)\n\n    if (!diagnostics) {\n      return node\n    }\n\n    return {\n      ...node,\n      diagnostics,\n    } as TNode\n  }\n\n  private getNodeType(value: object): string | undefined {\n    if (!('type' in value) || typeof value.type !== 'string') {\n      return undefined\n    }\n\n    return value.type\n  }\n\n  /**\n   * Node detection: Identifies objects that are AST nodes\n   * An object is a node when its `type` discriminant has a creator - the\n   * inline-only rows included, so a stray combinator or iterator config in a\n   * data position surfaces its placement error rather than passing as data.\n   */\n  private isNode(value: object): boolean {\n    const nodeType = this.getNodeType(value)\n\n    return nodeType !== undefined && creatorsByType.has(nodeType)\n  }\n}\n","import { ASTNode, NodeId } from '../../../contracts/ast/engine.type'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport {\n  BlockType,\n  ExpressionType,\n  FunctionType,\n  HookType,\n  OutcomeType,\n  PredicateType,\n} from '../../../../../authoring/types/enums'\nimport { ExpressionASTNode, OutcomeASTNode } from '../../../contracts/ast/expressions.type'\nimport { PredicateASTNode } from '../../../contracts/ast/predicates.type'\nimport { BlockASTNode } from '../../../contracts/ast/structures.type'\nimport ForgeInternalError from '../../../../errors/ForgeInternalError'\n\n/** Indexes include both structural AST types and authoring sub-types. */\nexport type IndexableNodeType =\n  | ASTNodeType\n  | ExpressionType\n  | FunctionType\n  | PredicateType\n  | HookType\n  | OutcomeType\n  | BlockType\n\n/**\n * Groups the shared compiled AST by node type.\n *\n * The type index is deliberately simple because compilers ask broad questions:\n * \"all FIELD blocks\", \"all ITERATE expressions\", \"all SUBMIT hooks\". Ownership and\n * ancestry live on the nodes themselves via `ASTNode.parent`.\n */\nexport default class ASTNodeIndex {\n  private readonly registeredIds: Set<NodeId> = new Set()\n\n  private readonly typeIndex: Map<string, ASTNode[]> = new Map()\n\n  /**\n   * Nodes are frozen on registration so every generated function sees the same\n   * shared AST shape for the lifetime of the compiled journey.\n   */\n  register(id: NodeId, node: ASTNode): void {\n    if (this.registeredIds.has(id)) {\n      throw new ForgeInternalError(`Node with ID \"${id}\" is already registered`)\n    }\n\n    this.registeredIds.add(id)\n\n    const frozen = Object.freeze(node)\n\n    this.addToTypeIndex(node.type, frozen)\n\n    const subType = this.getNodeSubType(node)\n\n    if (subType) {\n      this.addToTypeIndex(subType, frozen)\n    }\n  }\n\n  private addToTypeIndex(type: string, node: ASTNode): void {\n    let nodes = this.typeIndex.get(type)\n\n    if (!nodes) {\n      nodes = []\n      this.typeIndex.set(type, nodes)\n    }\n\n    nodes.push(node)\n  }\n\n  /** Sub-type indexing keeps compiler queries independent of AST wrapper type. */\n  private getNodeSubType(node: ASTNode): string | undefined {\n    if ('expressionType' in node) {\n      return (node as ExpressionASTNode).expressionType\n    }\n\n    if ('predicateType' in node) {\n      return (node as PredicateASTNode).predicateType\n    }\n\n    if ('hookType' in node) {\n      return (node as { hookType: HookType }).hookType\n    }\n\n    if ('outcomeType' in node) {\n      return (node as OutcomeASTNode).outcomeType\n    }\n\n    if ('blockType' in node) {\n      return (node as BlockASTNode).blockType\n    }\n\n    return undefined\n  }\n\n  findByType<T = ASTNode>(type: IndexableNodeType): T[] {\n    return [...(this.typeIndex.get(type) ?? [])] as T[]\n  }\n}\n","import type { ASTNode } from '../../../contracts/ast/engine.type'\nimport type { TemplateNode, TemplateValue } from '../../../contracts/ast/template.type'\nimport { isTemplateNode } from '../../../contracts/ast/nodes'\nimport type { IndexableNodeType } from './ASTNodeIndex'\n\nexport interface TemplateNodeEntry {\n  readonly node: TemplateNode\n  /** The registered node whose property carries the template — the iterate expression node today. */\n  readonly owningNode: ASTNode\n}\n\n/**\n * Groups template node contents by original type and sub-type — `ASTNodeIndex`'s\n * sibling for the unmaterialised side of the tree.\n *\n * Template contents never enter `ASTNodeIndex`: analysis and lowering must not\n * treat them as materialised nodes. Semantic analysis still has to check them,\n * so this index answers the same broad by-type questions over template contents\n * without each rule re-walking every iterator template.\n */\nexport default class TemplateNodeIndex {\n  private readonly typeIndex: Map<string, TemplateNodeEntry[]> = new Map()\n\n  /**\n   * Register every template node reachable from a template value, including\n   * the contents of nested iterator templates, against the registered node\n   * that owns the outermost template.\n   */\n  registerTree(template: TemplateValue, owningNode: ASTNode): void {\n    this.collect(template, owningNode)\n  }\n\n  findByType(type: IndexableNodeType): TemplateNodeEntry[] {\n    return [...(this.typeIndex.get(type) ?? [])]\n  }\n\n  private collect(value: TemplateValue, owningNode: ASTNode): void {\n    if (value === null || value === undefined || typeof value !== 'object') {\n      return\n    }\n\n    if (Array.isArray(value)) {\n      value.forEach(item => this.collect(item, owningNode))\n\n      return\n    }\n\n    if (isTemplateNode(value)) {\n      this.addEntry(value, owningNode)\n      this.collectTemplateNodeChildren(value, owningNode)\n\n      return\n    }\n\n    Object.values(value).forEach(child => this.collect(child, owningNode))\n  }\n\n  private collectTemplateNodeChildren(node: TemplateNode, owningNode: ASTNode): void {\n    Object.entries(node).forEach(([key, child]) => {\n      if (key === 'type' || key === 'originalType' || key === 'id' || key === 'diagnostics') {\n        return\n      }\n\n      this.collect(child as TemplateValue, owningNode)\n    })\n  }\n\n  private addEntry(node: TemplateNode, owningNode: ASTNode): void {\n    const entry: TemplateNodeEntry = { node, owningNode }\n\n    this.addToTypeIndex(node.originalType, entry)\n\n    const subType = this.templateNodeSubType(node)\n\n    if (subType !== undefined) {\n      this.addToTypeIndex(subType, entry)\n    }\n  }\n\n  private addToTypeIndex(type: string, entry: TemplateNodeEntry): void {\n    let entries = this.typeIndex.get(type)\n\n    if (!entries) {\n      entries = []\n      this.typeIndex.set(type, entries)\n    }\n\n    entries.push(entry)\n  }\n\n  /** Template nodes keep their family sub-type fields, so the same sub-type indexing as `ASTNodeIndex` applies. */\n  private templateNodeSubType(node: TemplateNode): string | undefined {\n    const subType = node.expressionType ?? node.predicateType ?? node.hookType ?? node.outcomeType ?? node.blockType\n\n    return typeof subType === 'string' ? subType : undefined\n  }\n}\n","import { ASTNode } from '../../../contracts/ast/engine.type'\nimport ASTNodeIndex from './ASTNodeIndex'\nimport TemplateNodeIndex from './TemplateNodeIndex'\nimport { isASTNode, isTemplateNode } from '../../../contracts/ast/nodes'\nimport ForgeInternalError from '../../../../errors/ForgeInternalError'\n\n/**\n * Indexes an AST subtree in one recursive descent.\n *\n * The walker registers nodes by ID and wires each node's direct `parent`.\n * Template nodes are not registered in `ASTNodeIndex` because generated\n * functions evaluate iterator templates inline instead of materialising\n * runtime AST nodes; their contents go into `TemplateNodeIndex` so semantic\n * analysis can query them without re-walking every template.\n */\nexport default class NodeRegistrationWalker {\n  constructor(\n    private readonly nodeIndex: ASTNodeIndex,\n    private readonly templateNodeIndex: TemplateNodeIndex = new TemplateNodeIndex(),\n  ) {}\n\n  /**\n   * Register a root AST node and every non-template descendant.\n   */\n  register(root: ASTNode): void {\n    this.walk(root, undefined)\n  }\n\n  private walk(value: unknown, parentNode: ASTNode | undefined): void {\n    if (value === null || value === undefined || typeof value !== 'object') {\n      return\n    }\n\n    if (Array.isArray(value)) {\n      value.forEach(item => this.walk(item, parentNode))\n\n      return\n    }\n\n    // Template contents stay out of the main registry but are indexed for\n    // semantic analysis, keyed to the registered node that carries them.\n    if (isTemplateNode(value)) {\n      if (parentNode === undefined) {\n        throw new ForgeInternalError('Template node reached with no registered parent to own it')\n      }\n\n      this.templateNodeIndex.registerTree(value, parentNode)\n\n      return\n    }\n\n    if (!isASTNode(value)) {\n      Object.values(value).forEach(v => this.walk(v, parentNode))\n\n      return\n    }\n\n    const node = value\n\n    // Non-enumerable so blind property walkers (template compilation) never\n    // recurse back up the tree. Assigned before register() freezes the node.\n    if (parentNode !== undefined) {\n      Object.defineProperty(node, 'parent', { value: parentNode, enumerable: false })\n    }\n\n    this.nodeIndex.register(node.id, node)\n\n    if (node.properties) {\n      Object.values(node.properties).forEach(propValue => this.walk(propValue, node))\n    }\n  }\n}\n","import type { WorkContextContract, WorkHandler } from '../../contracts/work/work.type'\nimport { createWorkTask } from '../../work/workTask'\nimport type { JourneyASTNode } from '../../contracts/ast/structures.type'\nimport type CompilationState from '../pipeline/CompilationState'\nimport { NodeIDGenerator } from './ast-state/NodeIDGenerator'\nimport { NodeFactory } from './nodes/NodeFactory'\nimport ASTNodeIndex from './ast-state/ASTNodeIndex'\nimport TemplateNodeIndex from './ast-state/TemplateNodeIndex'\nimport NodeRegistrationWalker from './ast-state/NodeRegistrationWalker'\n\nexport const COMPILATION_AST_WORK_HANDLER: WorkHandler<'compilation.ast', undefined> = {\n  kind: 'compilation.ast',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n    const nodeIdGenerator = new NodeIDGenerator()\n    const nodeFactory = new NodeFactory(nodeIdGenerator)\n    const nodeIndex = new ASTNodeIndex()\n    const templateNodeIndex = new TemplateNodeIndex()\n\n    const rootNode = nodeFactory.createNode(state.journeyDefinition) as JourneyASTNode\n\n    const walker = new NodeRegistrationWalker(nodeIndex, templateNodeIndex)\n\n    walker.register(rootNode)\n\n    state.recordAst({ rootNode, nodeIndex, templateNodeIndex })\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationAstTask() {\n  return createWorkTask('ast', COMPILATION_AST_WORK_HANDLER, undefined)\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeReferenceScopeErrorOptions {\n  /** Human-readable error message */\n  message: string\n  /** Human-readable path through the journey DSL */\n  formattedPath: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeReferenceScopeError extends ForgeBaseError {\n  constructor(options: ForgeReferenceScopeErrorOptions) {\n    super(options.message, options)\n  }\n}\n","import { ExpressionType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { IterateASTNode, ReferenceASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { TemplateNode, TemplateValue } from '../../../chassis/contracts/ast/template.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\n\ninterface TemplateVisitor {\n  /** Return false to skip walking this node's children. */\n  onTemplateNode(node: TemplateNode, diagnostics: ASTNodeDiagnostics | undefined): boolean | void\n}\n\n// The depth-tracking walk below is the one template check TemplateNodeIndex cannot\n// serve: the flat index erases iterator nesting, and Item()/Loop levels depend on it.\nfunction walkTemplateValue(value: TemplateValue, visitor: TemplateVisitor): void {\n  if (value === null || value === undefined || typeof value !== 'object') {\n    return\n  }\n\n  if (Array.isArray(value)) {\n    value.forEach(item => walkTemplateValue(item, visitor))\n\n    return\n  }\n\n  if (isTemplateNode(value)) {\n    const shouldWalkChildren = visitor.onTemplateNode(value, value.diagnostics)\n\n    if (shouldWalkChildren !== false) {\n      walkTemplateProperties(value, visitor)\n    }\n\n    return\n  }\n\n  Object.values(value as Record<string, TemplateValue>).forEach(child => {\n    walkTemplateValue(child, visitor)\n  })\n}\n\nfunction walkTemplateProperties(node: TemplateNode, visitor: TemplateVisitor): void {\n  if (!node.properties) {\n    return\n  }\n\n  Object.values(node.properties).forEach(propValue => {\n    walkTemplateValue(propValue, visitor)\n  })\n\n  Object.entries(node).forEach(([key, value]) => {\n    if (key === 'type' || key === 'originalType' || key === 'id' || key === 'diagnostics' || key === 'properties') {\n      return\n    }\n\n    walkTemplateValue(value as TemplateValue, visitor)\n  })\n}\n\nconst LOOP_PROPERTIES: ReadonlySet<string> = new Set([\n  'index',\n  'index0',\n  'revindex',\n  'revindex0',\n  'first',\n  'last',\n  'length',\n])\n\nfunction createError(diagnostics: ASTNodeDiagnostics | undefined, message: string): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message,\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction parseReferenceLevel(value: unknown): number | undefined {\n  if (typeof value !== 'number' && typeof value !== 'string') {\n    return undefined\n  }\n\n  const level = Number(value)\n\n  return Number.isInteger(level) && level >= 0 ? level : undefined\n}\n\nfunction validateItemReference(\n  path: (ASTNode | string | number)[],\n  iteratorDepth: number,\n  diagnostics: ASTNodeDiagnostics | undefined,\n): readonly Error[] {\n  const level = parseReferenceLevel(path[1])\n\n  if (level === undefined) {\n    return [createError(diagnostics, 'Item() reference level must be a non-negative integer')]\n  }\n\n  if (level >= iteratorDepth) {\n    const message =\n      iteratorDepth === 0\n        ? 'Item() can only be used inside an iterator'\n        : `Item().parent references level ${level}, but only ${iteratorDepth} iterator scope is available`\n\n    return [createError(diagnostics, message)]\n  }\n\n  return []\n}\n\nfunction validateLoopReference(\n  path: (ASTNode | string | number)[],\n  iteratorDepth: number,\n  diagnostics: ASTNodeDiagnostics | undefined,\n): readonly Error[] {\n  const errors: Error[] = []\n  const level = parseReferenceLevel(path[1])\n\n  if (level === undefined) {\n    return [createError(diagnostics, 'Loop reference level must be a non-negative integer')]\n  }\n\n  if (level >= iteratorDepth) {\n    const message =\n      iteratorDepth === 0\n        ? 'Loop can only be used inside an iterator'\n        : `Loop.Parent references level ${level}, but only ${iteratorDepth} iterator scope is available`\n\n    errors.push(createError(diagnostics, message))\n  }\n\n  const property = path[2]\n\n  if (typeof property !== 'string' || !LOOP_PROPERTIES.has(property)) {\n    errors.push(\n      createError(\n        diagnostics,\n        'Loop reference property must be one of index, index0, revindex, revindex0, first, last, length',\n      ),\n    )\n  }\n\n  return errors\n}\n\nfunction validateRegisteredReference(node: ReferenceASTNode): readonly Error[] {\n  const path = node.properties.path\n  const namespace = path[0]\n\n  // Iterator bodies are lifted into templates at AST build, so any reference still\n  // in the registered tree sits outside every iterator scope: its depth is always 0.\n  if (namespace === '@scope') {\n    return validateItemReference(path, 0, node.diagnostics)\n  }\n\n  if (namespace === '@loop') {\n    return validateLoopReference(path, 0, node.diagnostics)\n  }\n\n  return []\n}\n\nfunction walkIterateTemplateReferences(\n  iterator: IterateASTNode['properties']['iterator'],\n  currentDepth: number,\n  errors: Error[],\n): void {\n  const templates = [iterator.yieldTemplate, iterator.predicateTemplate].filter(\n    (t): t is NonNullable<typeof t> => t !== undefined,\n  )\n\n  templates.forEach(template => {\n    const visitor = {\n      onTemplateNode(templateNode: TemplateNode, templateMetadata: ASTNodeDiagnostics | undefined): boolean | void {\n        if (templateNode.originalType !== ASTNodeType.EXPRESSION) {\n          return undefined\n        }\n\n        const expressionType = (templateNode as Record<string, unknown>).expressionType as string | undefined\n\n        if (expressionType === ExpressionType.ITERATE) {\n          if (templateNode.properties?.input) {\n            walkTemplateValue(templateNode.properties.input, visitor)\n          }\n\n          const nestedIterator = templateNode.properties?.iterator as\n            | IterateASTNode['properties']['iterator']\n            | undefined\n\n          if (nestedIterator) {\n            walkIterateTemplateReferences(nestedIterator, currentDepth + 1, errors)\n          }\n\n          return false\n        }\n\n        if (expressionType !== ExpressionType.REFERENCE) {\n          return undefined\n        }\n\n        const refPath = templateNode.properties?.path\n\n        if (!Array.isArray(refPath)) {\n          return undefined\n        }\n\n        const templateRefPath = refPath as (string | number)[]\n        const namespace = templateRefPath[0]\n\n        if (namespace === '@scope') {\n          errors.push(...validateItemReference(templateRefPath, currentDepth, templateMetadata))\n        }\n\n        if (namespace === '@loop') {\n          errors.push(...validateLoopReference(templateRefPath, currentDepth, templateMetadata))\n        }\n\n        return undefined\n      },\n    }\n\n    walkTemplateValue(template, visitor)\n  })\n}\n\nfunction validateTemplateReferences(iterateNode: IterateASTNode): readonly Error[] {\n  const errors: Error[] = []\n\n  walkIterateTemplateReferences(iterateNode.properties.iterator, 1, errors)\n\n  return errors\n}\n\nexport const validateReferenceScopes: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  const referenceNodes = nodeIndex.findByType<ReferenceASTNode>(ExpressionType.REFERENCE)\n\n  referenceNodes.forEach(node => {\n    errors.push(...validateRegisteredReference(node))\n  })\n\n  const iterateNodes = nodeIndex.findByType<IterateASTNode>(ExpressionType.ITERATE)\n\n  iterateNodes.forEach(iterateNode => {\n    errors.push(...validateTemplateReferences(iterateNode))\n  })\n\n  return errors\n}\n","import { FieldBlockASTNode } from './structures.type'\nimport { ASTNodeType } from './enums'\nimport { BlockType } from '../../../../authoring/types/enums'\n\nexport function isFieldBlockStructNode(obj: any): obj is FieldBlockASTNode {\n  return obj != null && obj.type === ASTNodeType.BLOCK && obj.blockType === BlockType.FIELD\n}\n","import { BlockType, ExpressionType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { IterateASTNode, ReferenceASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport { isFieldBlockStructNode } from '../../../chassis/contracts/ast/structure-nodes'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { TemplateValue } from '../../../chassis/contracts/ast/template.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(message: string, diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message,\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\n/** Both authored spellings survive to the AST: `['answers', '@self', …]` from the `Self()` builder and bare `['@self', …]` from raw definitions. */\nfunction isSelfReferencePath(path: unknown): boolean {\n  if (!Array.isArray(path)) {\n    return false\n  }\n\n  return path[0] === '@self' || (path[0] === 'answers' && path[1] === '@self')\n}\n\ninterface SelfScope {\n  readonly insideFieldBlock: boolean\n  readonly insideFieldCode: boolean\n}\n\nconst UNSCOPED: SelfScope = { insideFieldBlock: false, insideFieldCode: false }\n\n/**\n * Walks `parent` links to the nearest field block. The chain remembers which\n * child it arrived through, so an identity check against the field's `code`\n * property detects a reference sitting inside the field's own code expression.\n */\nfunction scopeAt(node: ASTNode): SelfScope {\n  let child: ASTNode = node\n  let current = node.parent\n\n  while (current !== undefined) {\n    if (isFieldBlockStructNode(current)) {\n      return { insideFieldBlock: true, insideFieldCode: current.properties?.code === child }\n    }\n\n    child = current\n    current = current.parent\n  }\n\n  return UNSCOPED\n}\n\nfunction selfScopeError(scope: SelfScope, diagnostics: ASTNodeDiagnostics | undefined): Error | undefined {\n  if (!scope.insideFieldBlock) {\n    return buildError('Self() reference used outside of a field block', diagnostics)\n  }\n\n  if (scope.insideFieldCode) {\n    return buildError(\"Self() cannot be used within the field's code expression\", diagnostics)\n  }\n\n  return undefined\n}\n\nfunction walkTemplateForSelfScope(value: TemplateValue, scope: SelfScope, errors: Error[]): void {\n  if (value === null || value === undefined || typeof value !== 'object') {\n    return\n  }\n\n  if (Array.isArray(value)) {\n    value.forEach(item => walkTemplateForSelfScope(item, scope, errors))\n\n    return\n  }\n\n  if (isTemplateNode(value)) {\n    if (value.originalType === ASTNodeType.EXPRESSION) {\n      const expressionType = (value as Record<string, unknown>).expressionType as string | undefined\n\n      if (expressionType === ExpressionType.REFERENCE && isSelfReferencePath(value.properties?.path)) {\n        const error = selfScopeError(scope, value.diagnostics)\n\n        if (error !== undefined) {\n          errors.push(error)\n        }\n      }\n    }\n\n    const isFieldBlock =\n      value.originalType === ASTNodeType.BLOCK && (value as Record<string, unknown>).blockType === BlockType.FIELD\n\n    if (value.properties) {\n      Object.entries(value.properties).forEach(([key, propValue]) => {\n        const childScope = isFieldBlock ? { insideFieldBlock: true, insideFieldCode: key === 'code' } : scope\n\n        walkTemplateForSelfScope(propValue as TemplateValue, childScope, errors)\n      })\n    }\n\n    Object.entries(value).forEach(([key, val]) => {\n      if (key === 'type' || key === 'originalType' || key === 'id' || key === 'properties') {\n        return\n      }\n\n      walkTemplateForSelfScope(val as TemplateValue, scope, errors)\n    })\n\n    return\n  }\n\n  Object.values(value as Record<string, TemplateValue>).forEach(child => {\n    walkTemplateForSelfScope(child, scope, errors)\n  })\n}\n\nexport const validateSelfScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType<ReferenceASTNode>(ExpressionType.REFERENCE).forEach(node => {\n    if (!isSelfReferencePath(node.properties?.path)) {\n      return\n    }\n\n    const error = selfScopeError(scopeAt(node), node.diagnostics)\n\n    if (error !== undefined) {\n      errors.push(error)\n    }\n  })\n\n  const iterateNodes = nodeIndex.findByType<IterateASTNode>(ExpressionType.ITERATE)\n\n  iterateNodes.forEach(iterateNode => {\n    const scope = scopeAt(iterateNode)\n    const { iterator } = iterateNode.properties\n\n    const templates = [iterator.yieldTemplate, iterator.predicateTemplate].filter(\n      (t): t is NonNullable<typeof t> => t !== undefined,\n    )\n\n    templates.forEach(template => {\n      walkTemplateForSelfScope(template, scope, errors)\n    })\n  })\n\n  return errors\n}\n","import { ExpressionType, HookType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { ReferenceASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Answer() cannot be used in an onAccess hook: answer preparation runs after access hooks',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\n/** `@self` answer references are validateSelfScope's case — a hook is already outside every field block. */\nfunction isAnswerReferencePath(path: unknown): boolean {\n  if (!Array.isArray(path)) {\n    return false\n  }\n\n  return path[0] === 'answers' && path[1] !== '@self'\n}\n\nfunction hasAccessHookAncestor(node: ASTNode): boolean {\n  let current = node.parent\n\n  while (current !== undefined) {\n    if (current.type === ASTNodeType.HOOK) {\n      return (current as { hookType?: HookType }).hookType === HookType.ACCESS\n    }\n\n    current = current.parent\n  }\n\n  return false\n}\n\nexport const validateAnswerScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType<ReferenceASTNode>(ExpressionType.REFERENCE).forEach(node => {\n    if (isAnswerReferencePath(node.properties?.path) && hasAccessHookAncestor(node)) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(ExpressionType.REFERENCE).forEach(({ node, owningNode }) => {\n    if (isAnswerReferencePath(node.properties?.path) && hasAccessHookAncestor(owningNode)) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  return errors\n}\n","import { FunctionType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { FunctionASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(name: string, diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: `Effect \"${name}\" can only be used inside a hook (onAccess or onSubmission)`,\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction hasHookAncestor(node: ASTNode): boolean {\n  let current = node.parent\n\n  while (current !== undefined) {\n    if (current.type === ASTNodeType.HOOK) {\n      return true\n    }\n\n    current = current.parent\n  }\n\n  return false\n}\n\nexport const validateEffectScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  const effectNodes = nodeIndex.findByType<FunctionASTNode>(FunctionType.EFFECT)\n\n  effectNodes.forEach(node => {\n    if (!hasHookAncestor(node)) {\n      errors.push(buildError(node.properties.name, node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(FunctionType.EFFECT).forEach(({ node, owningNode }) => {\n    if (hasHookAncestor(owningNode)) {\n      return\n    }\n\n    const name = (node.properties?.name as string) ?? ''\n\n    errors.push(buildError(name, node.diagnostics))\n  })\n\n  return errors\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeUnregisteredFunctionErrorOptions {\n  /** Name of the unregistered function */\n  functionName: string\n  /** Type of the function (e.g. FunctionType.Effect) */\n  functionType: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeUnregisteredFunctionError extends ForgeBaseError {\n  readonly functionName: string\n\n  readonly functionType: string\n\n  constructor(options: ForgeUnregisteredFunctionErrorOptions) {\n    super(`Function \"${options.functionName}\" (${options.functionType}) is not registered`, options)\n    this.functionName = options.functionName\n    this.functionType = options.functionType\n  }\n}\n","import { FunctionType } from '../../../../authoring/types/enums'\nimport type { FunctionASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeUnregisteredFunctionError from '../../../errors/ForgeUnregisteredFunctionError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nconst FUNCTION_TYPES = Object.values(FunctionType)\n\nfunction buildError(\n  name: string,\n  functionType: string,\n  diagnostics: ASTNodeDiagnostics | undefined,\n): ForgeUnregisteredFunctionError {\n  const source = diagnostics?.source\n\n  return new ForgeUnregisteredFunctionError({\n    formattedPath: source?.formattedPath ?? 'unknown',\n    functionName: name,\n    functionType,\n    callsite: diagnostics?.callsite,\n  })\n}\n\nexport const validateRegisteredFunctions: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex, functionRegistry } = context\n  const errors: Error[] = []\n\n  FUNCTION_TYPES.forEach(functionType => {\n    nodeIndex.findByType<FunctionASTNode>(functionType).forEach(node => {\n      if (!functionRegistry.has(node.properties.name)) {\n        errors.push(buildError(node.properties.name, functionType, node.diagnostics))\n      }\n    })\n\n    templateNodeIndex.findByType(functionType).forEach(({ node }) => {\n      const name = (node.properties?.name as string) ?? ''\n\n      if (!functionRegistry.has(name)) {\n        errors.push(buildError(name, functionType, node.diagnostics))\n      }\n    })\n  })\n\n  return errors\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeFunctionArityErrorOptions {\n  /** Name of the function whose arity is wrong */\n  functionName: string\n  /** Type of the function (e.g. FunctionType.Condition) */\n  functionType: string\n  /** Human-readable description of the expected arity (e.g. \"2\", \"at least 2\", \"between 1 and 3\") */\n  expected: string\n  /** Number of arguments the author actually supplied */\n  received: number\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeFunctionArityError extends ForgeBaseError {\n  readonly functionName: string\n\n  readonly functionType: string\n\n  readonly expected: string\n\n  readonly received: number\n\n  constructor(options: ForgeFunctionArityErrorOptions) {\n    super(\n      `Function \"${options.functionName}\" expects ${options.expected} ${options.expected === '1' ? 'argument' : 'arguments'} but received ${options.received}`,\n      options,\n    )\n    this.functionName = options.functionName\n    this.functionType = options.functionType\n    this.expected = options.expected\n    this.received = options.received\n  }\n}\n","import { z, type ZodType } from 'zod'\nimport { FunctionType } from '../../../../authoring/types/enums'\nimport type { FunctionASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeFunctionArityError from '../../../errors/ForgeFunctionArityError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nconst FUNCTION_TYPES = Object.values(FunctionType)\n\ninterface TupleArity {\n  min: number\n  /** undefined means unbounded — the tuple has a `.rest(...)` variadic tail */\n  max: number | undefined\n}\n\nfunction tupleArity(schema: z.ZodTuple): TupleArity {\n  const { items } = schema.def\n  const hasRest = schema.def.rest !== null && schema.def.rest !== undefined\n\n  // Trailing optional items lower the minimum; a gap in the middle still counts as required.\n  const reversed = [...items].reverse()\n  const firstRequired = reversed.findIndex(item => !(item instanceof z.ZodOptional))\n  const trailingOptionals = firstRequired === -1 ? items.length : firstRequired\n\n  return { min: items.length - trailingOptionals, max: hasRest ? undefined : items.length }\n}\n\nfunction describeArity({ min, max }: TupleArity): string {\n  if (max === undefined) {\n    return `at least ${min}`\n  }\n\n  if (min === max) {\n    return `${min}`\n  }\n\n  return `between ${min} and ${max}`\n}\n\nfunction arityViolation(schema: ZodType, received: number): { expected: string } | undefined {\n  if (!(schema instanceof z.ZodTuple)) {\n    return undefined\n  }\n\n  const arity = tupleArity(schema)\n\n  if (received >= arity.min && (arity.max === undefined || received <= arity.max)) {\n    return undefined\n  }\n\n  return { expected: describeArity(arity) }\n}\n\nfunction buildError(\n  name: string,\n  functionType: string,\n  diagnostics: ASTNodeDiagnostics | undefined,\n  expected: string,\n  received: number,\n): ForgeFunctionArityError {\n  const source = diagnostics?.source\n\n  return new ForgeFunctionArityError({\n    formattedPath: source?.formattedPath ?? 'unknown',\n    functionName: name,\n    functionType,\n    expected,\n    received,\n    callsite: diagnostics?.callsite,\n  })\n}\n\nexport const validateFunctionArity: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex, functionRegistry } = context\n  const errors: Error[] = []\n\n  FUNCTION_TYPES.forEach(functionType => {\n    nodeIndex.findByType<FunctionASTNode>(functionType).forEach(node => {\n      const entry = functionRegistry.get(node.properties.name)\n\n      if (!entry?.argumentsSchema) {\n        return\n      }\n\n      const received = node.properties.arguments.length\n      const violation = arityViolation(entry.argumentsSchema, received)\n\n      if (violation) {\n        errors.push(buildError(node.properties.name, functionType, node.diagnostics, violation.expected, received))\n      }\n    })\n\n    templateNodeIndex.findByType(functionType).forEach(({ node }) => {\n      const name = (node.properties?.name as string) ?? ''\n      const entry = functionRegistry.get(name)\n\n      if (!entry?.argumentsSchema) {\n        return\n      }\n\n      const received = (node.properties?.arguments as unknown[] | undefined)?.length ?? 0\n      const violation = arityViolation(entry.argumentsSchema, received)\n\n      if (violation) {\n        errors.push(buildError(name, functionType, node.diagnostics, violation.expected, received))\n      }\n    })\n  })\n\n  return errors\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeUnregisteredComponentErrorOptions {\n  /** Variant name of the unregistered component */\n  variant: string\n  /** Human-readable path through the journey DSL */\n  formattedPath?: string\n  /** Author callsite captured where the offending node was defined */\n  callsite?: { readonly stack?: string }\n}\n\nexport default class ForgeUnregisteredComponentError extends ForgeBaseError {\n  readonly variant: string\n\n  constructor(options: ForgeUnregisteredComponentErrorOptions) {\n    super(`Component variant \"${options.variant}\" is not registered`, options)\n    this.variant = options.variant\n  }\n}\n","import { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { BlockASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport ForgeUnregisteredComponentError from '../../../errors/ForgeUnregisteredComponentError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(variant: string, diagnostics: ASTNodeDiagnostics | undefined): ForgeUnregisteredComponentError {\n  const source = diagnostics?.source\n\n  return new ForgeUnregisteredComponentError({\n    formattedPath: source?.formattedPath ?? 'unknown',\n    variant,\n    callsite: diagnostics?.callsite,\n  })\n}\n\nexport const validateRegisteredComponents: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex, componentRegistry } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType<BlockASTNode>(ASTNodeType.BLOCK).forEach(node => {\n    if (componentRegistry.has(node.variant)) {\n      return\n    }\n\n    errors.push(buildError(node.variant, node.diagnostics))\n  })\n\n  templateNodeIndex.findByType(ASTNodeType.BLOCK).forEach(({ node }) => {\n    const variant = node.variant\n\n    if (typeof variant !== 'string') {\n      return\n    }\n\n    if (!componentRegistry.has(variant)) {\n      errors.push(buildError(variant, node.diagnostics))\n    }\n  })\n\n  return errors\n}\n","import { ExpressionType, BlockType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { ValidationASTNode, IterateASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport type { FieldBlockASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { TemplateValue } from '../../../chassis/contracts/ast/template.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Validation rules can only be used inside validWhen on a field block or step',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction collectNodeIdsFromValidWhen(validWhen: unknown): string[] {\n  const entries = Array.isArray(validWhen) ? validWhen : [validWhen]\n  const ids: string[] = []\n\n  entries.forEach((entry: unknown) => {\n    if (\n      entry != null &&\n      typeof entry === 'object' &&\n      'id' in entry &&\n      typeof (entry as { id: unknown }).id === 'string'\n    ) {\n      ids.push((entry as { id: string }).id)\n    }\n  })\n\n  return ids\n}\n\nfunction walkTemplateForValidationScope(value: TemplateValue, insideValidWhen: boolean, errors: Error[]): void {\n  if (value === null || value === undefined || typeof value !== 'object') {\n    return\n  }\n\n  if (Array.isArray(value)) {\n    value.forEach(item => walkTemplateForValidationScope(item, insideValidWhen, errors))\n\n    return\n  }\n\n  if (isTemplateNode(value)) {\n    if (value.originalType === ASTNodeType.EXPRESSION) {\n      const expressionType = (value as Record<string, unknown>).expressionType as string | undefined\n\n      if (expressionType === ExpressionType.VALIDATION && !insideValidWhen) {\n        errors.push(buildError(value.diagnostics))\n      }\n    }\n\n    const canHaveValidWhen =\n      (value.originalType === ASTNodeType.BLOCK && (value as Record<string, unknown>).blockType === BlockType.FIELD) ||\n      value.originalType === ASTNodeType.STEP\n\n    if (value.properties) {\n      Object.entries(value.properties).forEach(([key, propValue]) => {\n        const childScope = canHaveValidWhen && key === 'validWhen'\n\n        walkTemplateForValidationScope(propValue as TemplateValue, childScope, errors)\n      })\n    }\n\n    Object.entries(value).forEach(([key, val]) => {\n      if (key === 'type' || key === 'originalType' || key === 'id' || key === 'properties') {\n        return\n      }\n\n      walkTemplateForValidationScope(val as TemplateValue, false, errors)\n    })\n\n    return\n  }\n\n  Object.values(value as Record<string, TemplateValue>).forEach(child => {\n    walkTemplateForValidationScope(child, insideValidWhen, errors)\n  })\n}\n\nfunction hasValidWhenAncestor(node: ASTNode, validWhenEntryIds: Set<string>): boolean {\n  let current: ASTNode | undefined = node\n\n  while (current !== undefined) {\n    if (validWhenEntryIds.has(current.id)) {\n      return true\n    }\n\n    current = current.parent\n  }\n\n  return false\n}\n\nexport const validateValidationScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  const validWhenEntryIds = new Set<string>()\n\n  nodeIndex.findByType<FieldBlockASTNode>(BlockType.FIELD).forEach(block => {\n    collectNodeIdsFromValidWhen(block.properties.validWhen).forEach(id => {\n      validWhenEntryIds.add(id)\n    })\n  })\n\n  nodeIndex.findByType<StepASTNode>(ASTNodeType.STEP).forEach(step => {\n    collectNodeIdsFromValidWhen(step.properties.validWhen).forEach(id => {\n      validWhenEntryIds.add(id)\n    })\n  })\n\n  nodeIndex.findByType<ValidationASTNode>(ExpressionType.VALIDATION).forEach(node => {\n    if (!validWhenEntryIds.has(node.id)) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  const iterateNodes = nodeIndex.findByType<IterateASTNode>(ExpressionType.ITERATE)\n\n  iterateNodes.forEach(iterateNode => {\n    const insideValidWhen = hasValidWhenAncestor(iterateNode, validWhenEntryIds)\n    const { iterator } = iterateNode.properties\n\n    const templates = [iterator.yieldTemplate, iterator.predicateTemplate].filter(\n      (t): t is NonNullable<typeof t> => t !== undefined,\n    )\n\n    templates.forEach(template => {\n      walkTemplateForValidationScope(template, insideValidWhen, errors)\n    })\n  })\n\n  return errors\n}\n","import { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { NodeId, ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Outcomes can only be used inside a hook (onAccess or onSubmission)',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction containsNode(container: unknown, nodeId: NodeId): boolean {\n  return Array.isArray(container) && container.some(entry => entry?.id === nodeId)\n}\n\nfunction hasHookAncestor(node: ASTNode): boolean {\n  let current = node.parent\n\n  while (current !== undefined) {\n    if (current.type === ASTNodeType.HOOK) {\n      return true\n    }\n\n    current = current.parent\n  }\n\n  return false\n}\n\nexport const validateOutcomeScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType(ASTNodeType.OUTCOME).forEach(node => {\n    const parent = node.parent\n\n    if (!parent || parent.type !== ASTNodeType.HOOK) {\n      errors.push(buildError(node.diagnostics))\n\n      return\n    }\n\n    // Access hooks carry outcomes in `next`; submit hooks split them across the\n    // onAlways/onValid/onInvalid branch objects, which are plain objects and so\n    // parent their outcomes to the hook itself.\n    const inHookNext =\n      containsNode(parent.properties?.next, node.id) ||\n      containsNode(parent.properties?.onAlways?.next, node.id) ||\n      containsNode(parent.properties?.onValid?.next, node.id) ||\n      containsNode(parent.properties?.onInvalid?.next, node.id)\n\n    if (!inHookNext) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(ASTNodeType.OUTCOME).forEach(({ node, owningNode }) => {\n    if (hasHookAncestor(owningNode)) {\n      return\n    }\n\n    errors.push(buildError(node.diagnostics))\n  })\n\n  return errors\n}\n","import { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { NodeId } from '../../../chassis/contracts/ast/engine.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Hooks can only be defined in onAccess (steps, journeys) or onSubmission (steps) arrays',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction containsNode(container: unknown, nodeId: NodeId): boolean {\n  return Array.isArray(container) && container.some(entry => entry?.id === nodeId)\n}\n\nexport const validateHookScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType(ASTNodeType.HOOK).forEach(node => {\n    const parent = node.parent\n\n    if (!parent || (parent.type !== ASTNodeType.JOURNEY && parent.type !== ASTNodeType.STEP)) {\n      errors.push(buildError(node.diagnostics))\n\n      return\n    }\n\n    const inAccess = containsNode(parent.properties?.onAccess, node.id)\n    const inSubmission = parent.type === ASTNodeType.STEP && containsNode(parent.properties?.onSubmission, node.id)\n\n    if (!inAccess && !inSubmission) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(ASTNodeType.HOOK).forEach(({ node }) => {\n    errors.push(buildError(node.diagnostics))\n  })\n\n  return errors\n}\n","import { ExpressionType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { NodeId } from '../../../chassis/contracts/ast/engine.type'\nimport type { TieBreakerASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: \"Tie-breakers can only be used in a step's reachability configuration\",\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction containsNode(container: unknown, nodeId: NodeId): boolean {\n  return Array.isArray(container) && container.some(entry => entry?.id === nodeId)\n}\n\nexport const validateTieBreakerScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType<TieBreakerASTNode>(ExpressionType.TIE_BREAKER).forEach(node => {\n    const parent = node.parent\n\n    if (!parent || parent.type !== ASTNodeType.STEP) {\n      errors.push(buildError(node.diagnostics))\n\n      return\n    }\n\n    if (!containsNode(parent.properties?.reachability?.tieBreakers, node.id)) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(ExpressionType.TIE_BREAKER).forEach(({ node }) => {\n    errors.push(buildError(node.diagnostics))\n  })\n\n  return errors\n}\n","import { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { AstNodeId } from '../../../chassis/contracts/ast/engine.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildStepError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Steps can only be defined in a journey steps array',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction buildJourneyError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Journeys can only be defined at the root or in a journey children array',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction containsNode(entries: unknown, nodeId: AstNodeId): boolean {\n  return Array.isArray(entries) && entries.some(entry => entry?.id === nodeId)\n}\n\nexport const validateStructureScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex, templateNodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType(ASTNodeType.STEP).forEach(node => {\n    const parent = node.parent\n\n    if (!parent || parent.type !== ASTNodeType.JOURNEY || !containsNode(parent.properties?.steps, node.id)) {\n      errors.push(buildStepError(node.diagnostics))\n    }\n  })\n\n  nodeIndex.findByType(ASTNodeType.JOURNEY).forEach(node => {\n    const parent = node.parent\n\n    if (!parent) {\n      return\n    }\n\n    if (parent.type !== ASTNodeType.JOURNEY || !containsNode(parent.properties?.children, node.id)) {\n      errors.push(buildJourneyError(node.diagnostics))\n    }\n  })\n\n  templateNodeIndex.findByType(ASTNodeType.STEP).forEach(({ node }) => {\n    errors.push(buildStepError(node.diagnostics))\n  })\n\n  templateNodeIndex.findByType(ASTNodeType.JOURNEY).forEach(({ node }) => {\n    errors.push(buildJourneyError(node.diagnostics))\n  })\n\n  return errors\n}\n","import { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { NodeId } from '../../../chassis/contracts/ast/engine.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Blocks can only be defined in a step blocks array or nested within another block',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction containsNode(container: unknown, nodeId: NodeId): boolean {\n  return Array.isArray(container) && container.some(entry => entry?.id === nodeId)\n}\n\nexport const validateBlockScope: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType(ASTNodeType.BLOCK).forEach(node => {\n    const parent = node.parent\n\n    // Composite component wrappers legitimately hold child blocks in arbitrary\n    // properties (slots, content, rows, columns); those child blocks parent to\n    // the wrapper block, so any block-parented block is in scope.\n    if (parent?.type === ASTNodeType.BLOCK) {\n      return\n    }\n\n    if (parent?.type === ASTNodeType.STEP && containsNode(parent.properties?.blocks, node.id)) {\n      return\n    }\n\n    errors.push(buildError(node.diagnostics))\n  })\n\n  return errors\n}\n","import { BlockType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { ASTNode, NodeId } from '../../../chassis/contracts/ast/engine.type'\nimport type { FieldBlockASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction buildError(code: string, diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: `Field code '${code}' is shared by multiple blocks on the same step, so every one of them must declare dependentWhen to mark which variant is active`,\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction owningStepId(node: ASTNode): NodeId | undefined {\n  let ancestor = node.parent\n\n  while (ancestor !== undefined) {\n    if (ancestor.type === ASTNodeType.STEP) {\n      return ancestor.id\n    }\n\n    ancestor = ancestor.parent\n  }\n\n  return undefined\n}\n\n/**\n * Same-code field blocks on one step are variants of one logical field: at\n * runtime the first copy whose `dependentWhen` holds owns answer preparation\n * and validation. Copies without a `dependentWhen` would always be active, so\n * duplicates are only legal when every copy declares one. Runtime-resolved\n * codes (iterator template fields) cannot be checked statically and are\n * exempt.\n */\nexport const validateFieldCodeUniqueness: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n  const fieldBlocksByStepAndCode = new Map<string, FieldBlockASTNode[]>()\n\n  nodeIndex.findByType<FieldBlockASTNode>(BlockType.FIELD).forEach(fieldBlock => {\n    const code = fieldBlock.properties.code\n    const stepId = owningStepId(fieldBlock)\n\n    if (typeof code !== 'string' || stepId === undefined) {\n      return\n    }\n\n    const key = `${stepId}:${code}`\n    const group = fieldBlocksByStepAndCode.get(key) ?? []\n\n    group.push(fieldBlock)\n    fieldBlocksByStepAndCode.set(key, group)\n  })\n\n  fieldBlocksByStepAndCode.forEach(fieldBlocks => {\n    if (fieldBlocks.length < 2) {\n      return\n    }\n\n    fieldBlocks\n      .filter(fieldBlock => fieldBlock.properties.dependentWhen === undefined)\n      .forEach(fieldBlock => {\n        errors.push(buildError(fieldBlock.properties.code as string, fieldBlock.diagnostics))\n      })\n  })\n\n  return errors\n}\n","import { FunctionType, ExpressionType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { IterateASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { TemplateNode, TemplateValue } from '../../../chassis/contracts/ast/template.type'\nimport type { ASTNode } from '../../../chassis/contracts/ast/engine.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nconst FUNCTION_TYPES: readonly string[] = Object.values(FunctionType)\n\nfunction buildError(diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: 'Block definitions cannot be used as function arguments',\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction hasFunctionAncestor(node: ASTNode): boolean {\n  let current = node.parent\n\n  while (current !== undefined) {\n    if (\n      'expressionType' in current &&\n      FUNCTION_TYPES.includes((current as { expressionType: string }).expressionType)\n    ) {\n      return true\n    }\n\n    current = current.parent\n  }\n\n  return false\n}\n\nfunction isFunctionTemplateNode(node: TemplateNode): boolean {\n  if (node.originalType !== ASTNodeType.EXPRESSION) {\n    return false\n  }\n\n  const expressionType = (node as Record<string, unknown>).expressionType as string | undefined\n\n  return expressionType !== undefined && FUNCTION_TYPES.includes(expressionType)\n}\n\nfunction walkTemplateForBlocks(value: TemplateValue, insideFunction: boolean, errors: Error[]): void {\n  if (value === null || value === undefined || typeof value !== 'object') {\n    return\n  }\n\n  if (Array.isArray(value)) {\n    value.forEach(item => walkTemplateForBlocks(item, insideFunction, errors))\n\n    return\n  }\n\n  if (isTemplateNode(value)) {\n    const nextInsideFunction = insideFunction || isFunctionTemplateNode(value)\n\n    if (insideFunction && value.originalType === ASTNodeType.BLOCK) {\n      errors.push(buildError(value.diagnostics))\n    }\n\n    if (value.properties) {\n      Object.values(value.properties).forEach(propValue => {\n        walkTemplateForBlocks(propValue as TemplateValue, nextInsideFunction, errors)\n      })\n    }\n\n    Object.entries(value).forEach(([key, val]) => {\n      if (key === 'type' || key === 'originalType' || key === 'id' || key === 'properties') {\n        return\n      }\n\n      walkTemplateForBlocks(val as TemplateValue, nextInsideFunction, errors)\n    })\n\n    return\n  }\n\n  Object.values(value as Record<string, TemplateValue>).forEach(child => {\n    walkTemplateForBlocks(child, insideFunction, errors)\n  })\n}\n\nexport const validateFunctionArguments: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType(ASTNodeType.BLOCK).forEach(node => {\n    if (hasFunctionAncestor(node)) {\n      errors.push(buildError(node.diagnostics))\n    }\n  })\n\n  const iterateNodes = nodeIndex.findByType<IterateASTNode>(ExpressionType.ITERATE)\n\n  iterateNodes.forEach(iterateNode => {\n    const { iterator } = iterateNode.properties\n\n    const templates = [iterator.yieldTemplate, iterator.predicateTemplate].filter(\n      (t): t is NonNullable<typeof t> => t !== undefined,\n    )\n\n    templates.forEach(template => {\n      walkTemplateForBlocks(template, false, errors)\n    })\n  })\n\n  return errors\n}\n","import { FunctionType, HookType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { AccessHookASTNode, SubmitHookASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport type { StepASTNode, JourneyASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport ForgeReferenceScopeError from '../../../errors/ForgeReferenceScopeError'\nimport type { ASTNodeDiagnostics } from '../../../../shared/diagnostics/sourceLocation.type'\nimport type { ASTValidationContext, ASTValidationRule } from './types'\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return value != null && typeof value === 'object'\n}\n\nfunction getDiagnostics(value: unknown): ASTNodeDiagnostics | undefined {\n  if (!isObject(value) || !isObject(value.diagnostics) || !isObject(value.diagnostics.source)) {\n    return undefined\n  }\n\n  const { path, formattedPath } = value.diagnostics.source\n\n  if (\n    !Array.isArray(path) ||\n    !path.every(segment => typeof segment === 'string' || typeof segment === 'number') ||\n    typeof formattedPath !== 'string'\n  ) {\n    return undefined\n  }\n\n  const callsite = isObject(value.diagnostics.callsite)\n    ? (value.diagnostics.callsite as { readonly stack?: string })\n    : undefined\n\n  return { source: { path, formattedPath }, callsite }\n}\n\ninterface ContainerCheck {\n  message: string\n  isValid: (value: unknown) => boolean\n}\n\nfunction buildError(check: ContainerCheck, diagnostics: ASTNodeDiagnostics | undefined): ForgeReferenceScopeError {\n  const source = diagnostics?.source\n\n  return new ForgeReferenceScopeError({\n    message: check.message,\n    formattedPath: source?.formattedPath ?? 'unknown',\n    callsite: diagnostics?.callsite,\n  })\n}\n\nfunction checkEntries(\n  entries: unknown,\n  check: ContainerCheck,\n  containerDiagnostics: ASTNodeDiagnostics | undefined,\n  errors: Error[],\n): void {\n  if (!Array.isArray(entries)) {\n    return\n  }\n\n  entries.forEach((entry: unknown) => {\n    if (check.isValid(entry)) {\n      return\n    }\n\n    errors.push(buildError(check, getDiagnostics(entry) ?? containerDiagnostics))\n  })\n}\n\nfunction isAccessHook(value: unknown): boolean {\n  return isObject(value) && value.type === ASTNodeType.HOOK && value.hookType === HookType.ACCESS\n}\n\nfunction isSubmitHook(value: unknown): boolean {\n  return isObject(value) && value.type === ASTNodeType.HOOK && value.hookType === HookType.SUBMIT\n}\n\nfunction isBlock(value: unknown): boolean {\n  return isObject(value) && value.type === ASTNodeType.BLOCK\n}\n\nfunction isEffect(value: unknown): boolean {\n  return isObject(value) && value.expressionType === FunctionType.EFFECT\n}\n\nfunction isOutcome(value: unknown): boolean {\n  return isObject(value) && value.type === ASTNodeType.OUTCOME\n}\n\nconst ON_ACCESS: ContainerCheck = {\n  message: 'onAccess can only contain access hooks',\n  isValid: isAccessHook,\n}\n\nconst ON_SUBMISSION: ContainerCheck = {\n  message: 'onSubmission can only contain submit hooks',\n  isValid: isSubmitHook,\n}\n\nconst BLOCKS: ContainerCheck = {\n  message: 'blocks can only contain block definitions',\n  isValid: isBlock,\n}\n\nconst EFFECTS: ContainerCheck = {\n  message: 'effects can only contain effect functions',\n  isValid: isEffect,\n}\n\nconst NEXT: ContainerCheck = {\n  message: 'next can only contain outcomes',\n  isValid: isOutcome,\n}\n\nfunction checkHookBranch(\n  branch: { effects?: unknown[]; next?: unknown[] } | undefined,\n  containerDiagnostics: ASTNodeDiagnostics | undefined,\n  errors: Error[],\n): void {\n  if (!branch) {\n    return\n  }\n\n  checkEntries(branch.effects, EFFECTS, containerDiagnostics, errors)\n  checkEntries(branch.next, NEXT, containerDiagnostics, errors)\n}\n\nexport const validateContainerTypes: ASTValidationRule = (context: ASTValidationContext): readonly Error[] => {\n  const { nodeIndex } = context\n  const errors: Error[] = []\n\n  nodeIndex.findByType<StepASTNode>(ASTNodeType.STEP).forEach(step => {\n    const diagnostics = step.diagnostics\n\n    checkEntries(step.properties.onAccess, ON_ACCESS, diagnostics, errors)\n    checkEntries(step.properties.onSubmission, ON_SUBMISSION, diagnostics, errors)\n    checkEntries(step.properties.blocks, BLOCKS, diagnostics, errors)\n  })\n\n  nodeIndex.findByType<JourneyASTNode>(ASTNodeType.JOURNEY).forEach(journey => {\n    checkEntries(journey.properties.onAccess, ON_ACCESS, journey.diagnostics, errors)\n  })\n\n  nodeIndex.findByType<AccessHookASTNode>(HookType.ACCESS).forEach(hook => {\n    const diagnostics = hook.diagnostics\n\n    checkEntries(hook.properties.effects, EFFECTS, diagnostics, errors)\n    checkEntries(hook.properties.next, NEXT, diagnostics, errors)\n  })\n\n  nodeIndex.findByType<SubmitHookASTNode>(HookType.SUBMIT).forEach(hook => {\n    const diagnostics = hook.diagnostics\n\n    checkHookBranch(hook.properties.onAlways, diagnostics, errors)\n    checkHookBranch(hook.properties.onValid, diagnostics, errors)\n    checkHookBranch(hook.properties.onInvalid, diagnostics, errors)\n  })\n\n  return errors\n}\n","import type { ASTValidationContext, ASTValidationRule } from './rules/types'\nimport { validateReferenceScopes } from './rules/validateReferenceScopes'\nimport { validateSelfScope } from './rules/validateSelfScope'\nimport { validateAnswerScope } from './rules/validateAnswerScope'\nimport { validateEffectScope } from './rules/validateEffectScope'\nimport { validateRegisteredFunctions } from './rules/validateRegisteredFunctions'\nimport { validateFunctionArity } from './rules/validateFunctionArity'\nimport { validateRegisteredComponents } from './rules/validateRegisteredComponents'\nimport { validateValidationScope } from './rules/validateValidationScope'\nimport { validateOutcomeScope } from './rules/validateOutcomeScope'\nimport { validateHookScope } from './rules/validateHookScope'\nimport { validateTieBreakerScope } from './rules/validateTieBreakerScope'\nimport { validateStructureScope } from './rules/validateStructureScope'\nimport { validateBlockScope } from './rules/validateBlockScope'\nimport { validateFieldCodeUniqueness } from './rules/validateFieldCodeUniqueness'\nimport { validateFunctionArguments } from './rules/validateFunctionArguments'\nimport { validateContainerTypes } from './rules/validateContainerTypes'\n\nconst RULES: readonly ASTValidationRule[] = [\n  validateReferenceScopes,\n  validateSelfScope,\n  validateAnswerScope,\n  validateEffectScope,\n  validateRegisteredFunctions,\n  validateFunctionArity,\n  validateRegisteredComponents,\n  validateValidationScope,\n  validateOutcomeScope,\n  validateHookScope,\n  validateTieBreakerScope,\n  validateStructureScope,\n  validateBlockScope,\n  validateFieldCodeUniqueness,\n  validateFunctionArguments,\n  validateContainerTypes,\n]\n\nexport default class ASTSemanticValidator {\n  constructor(private readonly context: ASTValidationContext) {}\n\n  validate(): void {\n    const errors: Error[] = []\n\n    RULES.forEach(rule => {\n      errors.push(...rule(this.context))\n    })\n\n    if (errors.length > 0) {\n      throw new AggregateError(errors, 'AST semantic validation failed')\n    }\n  }\n}\n","import type { WorkContextContract, WorkHandler } from '../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../chassis/work/workTask'\nimport type CompilationState from '../../chassis/compilation/pipeline/CompilationState'\nimport ASTSemanticValidator from './ASTSemanticValidator'\n\nexport const COMPILATION_SEMANTIC_ANALYSIS_WORK_HANDLER: WorkHandler<'compilation.semantic-analysis', undefined> = {\n  kind: 'compilation.semantic-analysis',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n    const validator = new ASTSemanticValidator({\n      nodeIndex: state.ast.nodeIndex,\n      templateNodeIndex: state.ast.templateNodeIndex,\n      functionRegistry: state.dependencies.functionRegistry,\n      componentRegistry: state.dependencies.componentRegistry,\n    })\n\n    validator.validate()\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationSemanticAnalysisTask() {\n  return createWorkTask('semantic-analysis', COMPILATION_SEMANTIC_ANALYSIS_WORK_HANDLER, undefined)\n}\n","import type { ASTNode } from '../../../contracts/ast/ast.type'\n\n/**\n * Provides three ways to walk the `parent` chain of an AST node (the tree\n * of journey/step/block nodes built during parsing). Every ancestor lookup\n * in analysis goes through one of these methods — no analyzer walks the\n * chain manually.\n */\nexport default class Ancestry {\n  /**\n   * Walks from the root ancestor down to `node` (inclusive), calling `extract`\n   * on each. Returns the non-`undefined` results in root-first order, so a\n   * descendant's value appears after (and can override) its ancestors'.\n   */\n  valuesRootFirst<TValue>(node: ASTNode, extract: (ancestor: ASTNode) => TValue | undefined): TValue[] {\n    return this.chainRootFirst(node).flatMap(ancestor => {\n      const value = extract(ancestor)\n\n      return value === undefined ? [] : [value]\n    })\n  }\n\n  /**\n   * The nearest configured setting, starting at the node itself and walking\n   * outward. `undefined` when nothing along the chain sets one.\n   */\n  nearestAncestorSetting<TValue>(\n    node: ASTNode,\n    extract: (ancestor: ASTNode) => TValue | undefined,\n  ): TValue | undefined {\n    let current: ASTNode | undefined = node\n\n    while (current !== undefined) {\n      const value = extract(current)\n\n      if (value !== undefined) {\n        return value\n      }\n\n      current = current.parent\n    }\n\n    return undefined\n  }\n\n  /** Ancestors matching the type-guard predicate, root-first, excluding the node itself. */\n  ancestorsOfType<TNode extends ASTNode>(node: ASTNode, predicate: (ancestor: ASTNode) => ancestor is TNode): TNode[] {\n    return this.chainRootFirst(node).slice(0, -1).filter(predicate)\n  }\n\n  private chainRootFirst(node: ASTNode): ASTNode[] {\n    const chain: ASTNode[] = []\n    let current: ASTNode | undefined = node\n\n    while (current !== undefined) {\n      chain.unshift(current)\n      current = current.parent\n    }\n\n    return chain\n  }\n}\n","import type { IteratorType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from '../ast/enums'\nimport type { ASTNode } from '../ast/ast.type'\nimport { isASTNode, isTemplateNode } from '../ast/nodes'\nimport type { TemplateNode } from '../ast/template.type'\n\n/**\n * The classified forms an authored value can take once analysis has finished\n * with it. Built by `AuthoredValueClassifier` in the analysis stage, consumed\n * by `RuntimeValueCompiler` and the phase compilers. Past analysis there is no\n * structural AST querying: AST nodes survive only as expression leaves (handed\n * to the expression dispatcher) and diagnostic tokens.\n */\nexport enum AuthoredValueKind {\n  STATIC = 'static',\n  EXPRESSION = 'expression',\n  CONDITIONAL = 'conditional',\n  MATCH = 'match',\n  ITERATION = 'iteration',\n  RECORD = 'record',\n  LIST = 'list',\n  BLOCK = 'block',\n}\n\nexport type AuthoredValue =\n  | StaticValue\n  | ExpressionValue\n  | ConditionalValue\n  | MatchValue\n  | IterationValue\n  | RecordValue\n  | ListValue\n  | BlockValue\n\n/** A deeply static value, emitted as a literal. */\nexport interface StaticValue {\n  readonly kind: AuthoredValueKind.STATIC\n  readonly value: unknown\n}\n\n/** An authored value that must be evaluated at request time. */\nexport interface ExpressionValue {\n  readonly kind: AuthoredValueKind.EXPRESSION\n  readonly node: ASTNode | TemplateNode\n}\n\n/** A predicate choosing between two authored values. */\nexport interface ConditionalValue {\n  readonly kind: AuthoredValueKind.CONDITIONAL\n  /** The conditional node itself — expression leaf and diagnostic token. */\n  readonly source: ASTNode | TemplateNode\n  readonly predicate: AuthoredValue\n  readonly thenValue: AuthoredValue\n  readonly elseValue: AuthoredValue\n}\n\n/** First-matching-predicate selection over authored branch values. */\nexport interface MatchValue {\n  readonly kind: AuthoredValueKind.MATCH\n  /** The match node itself — expression leaf and diagnostic token. */\n  readonly source: ASTNode | TemplateNode\n  readonly subject: AuthoredValue\n  readonly branches: readonly MatchBranchValue[]\n  /** Present only when the author supplied an otherwise value. */\n  readonly otherwise?: AuthoredValue\n}\n\nexport type MatchBranchValue =\n  | { readonly predicate: AuthoredValue; readonly value: AuthoredValue }\n  | { readonly expected: AuthoredValue; readonly value: AuthoredValue }\n\n/** A MAP/FILTER/FIND iteration producing a value from an input collection. */\nexport interface IterationValue {\n  readonly kind: AuthoredValueKind.ITERATION\n  /** The iterate node itself — expression leaf and diagnostic token. */\n  readonly source: ASTNode | TemplateNode\n  /** `undefined` for unrecognised iterator kinds, which materialise as `undefined`. */\n  readonly iterator?: IteratorType\n  readonly input: AuthoredValue\n  /** MAP only; a MAP without a yield template materialises `undefined` items. */\n  readonly yieldTemplate?: AuthoredValue\n  /** FILTER and FIND predicates. */\n  readonly predicate?: AuthoredValue\n}\n\n/** A record with at least one non-static entry, materialised key by key. */\nexport interface RecordValue {\n  readonly kind: AuthoredValueKind.RECORD\n  readonly entries: readonly RecordEntryValue[]\n}\n\nexport interface RecordEntryValue {\n  readonly key: string\n  readonly value: AuthoredValue\n}\n\n/** An array with at least one non-static item, materialised item by item. */\nexport interface ListValue {\n  readonly kind: AuthoredValueKind.LIST\n  readonly items: readonly AuthoredValue[]\n}\n\n/**\n * A nested block — a template block node or a block-shaped plain object.\n * Classification is generic AST knowledge, but only the resolve concern knows\n * how to emit one (its runtime-value policy supplies the block compiler);\n * every other concern treats a block value as an impossible state.\n */\nexport interface BlockValue {\n  readonly kind: AuthoredValueKind.BLOCK\n  /** The block node or block-shaped object — diagnostic and identity token. */\n  readonly source: TemplateNode | Record<string, unknown>\n  readonly variant: string\n  readonly blockType: string\n  /** Registered block id; template blocks derive an instance id at runtime. */\n  readonly id?: string\n  /** The block's classified properties, in authored order. */\n  readonly entries: readonly RecordEntryValue[]\n}\n\n/** A node the expression dispatcher can compile — AST or template. */\nexport function isExpressionLeaf(value: unknown): value is ASTNode | TemplateNode {\n  return isASTNode(value) || isTemplateNode(value)\n}\n\nexport function expressionValue(node: ASTNode | TemplateNode): ExpressionValue {\n  return { kind: AuthoredValueKind.EXPRESSION, node }\n}\n\nexport function staticValue(value: unknown): StaticValue {\n  return { kind: AuthoredValueKind.STATIC, value }\n}\n\n/**\n * Whether a value contains no expression, template, or block nodes anywhere,\n * so it can be emitted as one literal. The single definition of \"static\"\n * shared by the classifier and the expression dispatcher.\n */\nexport function isDeepStaticValue(value: unknown): boolean {\n  if (value === null || value === undefined || typeof value !== 'object') {\n    return true\n  }\n\n  if (isExpressionLeaf(value) || isBlockShapedValue(value)) {\n    return false\n  }\n\n  if (Array.isArray(value)) {\n    return value.every(item => isDeepStaticValue(item))\n  }\n\n  return Object.values(value).every(item => isDeepStaticValue(item))\n}\n\n/** A template block node or a block-shaped plain object. */\nexport function isBlockShapedValue(value: unknown): boolean {\n  if (isTemplateNode(value)) {\n    return value.originalType === ASTNodeType.BLOCK\n  }\n\n  if (value === null || value === undefined || typeof value !== 'object' || Array.isArray(value)) {\n    return false\n  }\n\n  const record = value as Record<string, unknown>\n\n  return record.type === ASTNodeType.BLOCK && typeof record.variant === 'string' && typeof record.blockType === 'string'\n}\n\n/**\n * Reconstructs the raw authored value for operand positions — the expression\n * dispatcher's `compileOperandCode` owns static/node dispatch there, so the\n * classified tree hands back exactly what the author wrote. Node-backed arms\n * return their source node; classification is lossless.\n */\nexport function toRawOperand(value: AuthoredValue): unknown {\n  switch (value.kind) {\n    case AuthoredValueKind.STATIC:\n      return value.value\n    case AuthoredValueKind.EXPRESSION:\n      return value.node\n    case AuthoredValueKind.CONDITIONAL:\n    case AuthoredValueKind.MATCH:\n    case AuthoredValueKind.ITERATION:\n      return value.source\n    case AuthoredValueKind.BLOCK:\n      return value.source\n    case AuthoredValueKind.LIST:\n      return value.items.map(item => toRawOperand(item))\n    case AuthoredValueKind.RECORD:\n      return Object.fromEntries(value.entries.map(entry => [entry.key, toRawOperand(entry.value)]))\n    default:\n      return undefined\n  }\n}\n","import { ExpressionType, IteratorType } from '../../../../../authoring/types/enums'\nimport type { ASTNode } from '../../../contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport { isASTNode, isTemplateNode } from '../../../contracts/ast/nodes'\nimport type { TemplateNode } from '../../../contracts/ast/template.type'\nimport {\n  AuthoredValueKind,\n  expressionValue,\n  isBlockShapedValue,\n  isDeepStaticValue,\n  staticValue,\n  type AuthoredValue,\n  type BlockValue,\n  type MatchBranchValue,\n  type RecordEntryValue,\n} from '../../../contracts/models/authoredValue.type'\n\n/**\n * Classifies every authored value (the raw values journey authors write) into\n * the `AuthoredValue` union — the analysis stage's single answer to \"what kind\n * of value is this?\". Lowering (the stage that turns analysis models into\n * generated JavaScript) reads the classified tree and never re-derives value\n * kinds during code generation. Classification is lossless: branches backed by\n * AST or template nodes keep their source node, so the code generator receives\n * exactly what the author wrote.\n */\nexport default class AuthoredValueClassifier {\n  classify(value: unknown): AuthoredValue {\n    if (isDeepStaticValue(value)) {\n      return staticValue(value)\n    }\n\n    if (isTemplateNode(value)) {\n      return this.classifyTemplateNode(value)\n    }\n\n    if (isBlockShapedValue(value)) {\n      return this.classifyBlockObject(value as Record<string, unknown>)\n    }\n\n    if (this.isCompilableNode(value)) {\n      return this.classifyExpressionNode(value)\n    }\n\n    if (Array.isArray(value)) {\n      return { kind: AuthoredValueKind.LIST, items: value.map(item => this.classify(item)) }\n    }\n\n    return { kind: AuthoredValueKind.RECORD, entries: this.classifyEntries(value as Record<string, unknown>) }\n  }\n\n  private classifyTemplateNode(node: TemplateNode): AuthoredValue {\n    if (node.originalType === ASTNodeType.BLOCK) {\n      return this.classifyBlockTemplate(node)\n    }\n\n    const expressionType =\n      node.originalType === ASTNodeType.EXPRESSION && typeof node.expressionType === 'string'\n        ? node.expressionType\n        : undefined\n\n    return this.classifyByExpressionType(node, expressionType)\n  }\n\n  private classifyExpressionNode(node: ASTNode): AuthoredValue {\n    const expressionType = (node as { expressionType?: unknown }).expressionType\n    const resolvedType =\n      node.type === ASTNodeType.EXPRESSION && typeof expressionType === 'string' ? expressionType : undefined\n\n    return this.classifyByExpressionType(node, resolvedType)\n  }\n\n  private classifyByExpressionType(node: ASTNode | TemplateNode, expressionType: string | undefined): AuthoredValue {\n    if (expressionType === ExpressionType.CONDITIONAL) {\n      const properties = this.propertiesOf(node)\n\n      return {\n        kind: AuthoredValueKind.CONDITIONAL,\n        source: node,\n        predicate: this.classify(properties.predicate),\n        thenValue: this.classify(properties.thenValue),\n        elseValue: this.classify(properties.elseValue),\n      }\n    }\n\n    if (expressionType === ExpressionType.MATCH) {\n      const properties = this.propertiesOf(node)\n\n      return {\n        kind: AuthoredValueKind.MATCH,\n        source: node,\n        subject: this.classify(properties.subject),\n        branches: this.classifyMatchBranches(properties.branches),\n        otherwise: properties.otherwise === undefined ? undefined : this.classify(properties.otherwise),\n      }\n    }\n\n    if (expressionType === ExpressionType.ITERATE) {\n      return this.classifyIteration(node)\n    }\n\n    return expressionValue(node)\n  }\n\n  private classifyIteration(node: ASTNode | TemplateNode): AuthoredValue {\n    const properties = this.propertiesOf(node)\n    const iterator = this.isRecord(properties.iterator) ? properties.iterator : undefined\n    const iteratorType = this.resolveIteratorType(iterator?.type)\n\n    return {\n      kind: AuthoredValueKind.ITERATION,\n      source: node,\n      iterator: iteratorType,\n      input: this.classify(properties.input),\n      yieldTemplate:\n        iteratorType === IteratorType.MAP && iterator?.yieldTemplate !== undefined\n          ? this.classify(iterator.yieldTemplate)\n          : undefined,\n      predicate:\n        iteratorType !== undefined && iteratorType !== IteratorType.MAP\n          ? this.classify(iterator?.predicateTemplate)\n          : undefined,\n    }\n  }\n\n  private classifyBlockTemplate(node: TemplateNode): BlockValue {\n    return {\n      kind: AuthoredValueKind.BLOCK,\n      source: node,\n      variant: String(node.variant),\n      blockType: String(node.blockType),\n      id: undefined,\n      entries: this.classifyEntries(this.propertiesOf(node)),\n    }\n  }\n\n  private classifyBlockObject(block: Record<string, unknown>): BlockValue {\n    return {\n      kind: AuthoredValueKind.BLOCK,\n      source: block,\n      variant: block.variant as string,\n      blockType: block.blockType as string,\n      id: typeof block.id === 'string' ? block.id : undefined,\n      entries: this.classifyEntries(this.isRecord(block.properties) ? block.properties : {}),\n    }\n  }\n\n  private classifyMatchBranches(value: unknown): MatchBranchValue[] {\n    if (!Array.isArray(value)) {\n      return []\n    }\n\n    return value\n      .filter((item): item is Record<string, unknown> => this.isRecord(item))\n      .map(branch => ({\n        ...('expected' in branch\n          ? { expected: this.classify(branch.expected) }\n          : { predicate: this.classify(branch.predicate) }),\n        value: this.classify(branch.value),\n      }))\n  }\n\n  private classifyEntries(record: Record<string, unknown>): RecordEntryValue[] {\n    return Object.entries(record).map(([key, entry]) => ({ key, value: this.classify(entry) }))\n  }\n\n  private resolveIteratorType(value: unknown): IteratorType | undefined {\n    return value === IteratorType.MAP ||\n      value === IteratorType.FILTER ||\n      value === IteratorType.FIND ||\n      value === IteratorType.SOME ||\n      value === IteratorType.EVERY ||\n      value === IteratorType.COUNT\n      ? value\n      : undefined\n  }\n\n  private propertiesOf(node: ASTNode | TemplateNode): Record<string, unknown> {\n    return (node.properties ?? {}) as Record<string, unknown>\n  }\n\n  private isCompilableNode(value: unknown): value is ASTNode {\n    return isASTNode(value) && 'id' in value\n  }\n\n  private isRecord(value: unknown): value is Record<string, unknown> {\n    return value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value)\n  }\n}\n","import { ExpressionType } from '../../../../authoring/types/enums'\nimport type { ASTNode } from '../ast/ast.type'\nimport { ASTNodeType } from '../ast/enums'\nimport { isASTNode, isTemplateNode } from '../ast/nodes'\nimport type { TemplateNode } from '../ast/template.type'\nimport { AuthoredValueKind, type AuthoredValue, type ExpressionValue } from './authoredValue.type'\nimport { ValidationRulesKind, type ValidationRulesModel } from './fieldModel.type'\n\n/**\n * Classifiers for authored validation values, kept beside the model types (the\n * `contracts/ast/nodes.ts` precedent) so analysis and lowering share one\n * definition of \"configured\" and \"direct rule\".\n */\n\n/** `undefined` and empty arrays are absent; any other value counts as configured. */\nexport function hasConfiguredValue(value: unknown): boolean {\n  if (value === undefined) {\n    return false\n  }\n\n  if (Array.isArray(value)) {\n    return value.length > 0\n  }\n\n  return true\n}\n\n/**\n * An authored array of validation expressions compiles rule-by-rule; any other\n * shape is materialised through the runtime value compiler.\n */\nexport function classifyValidationRules(\n  value: unknown,\n  classify: (value: unknown) => AuthoredValue,\n): ValidationRulesModel {\n  if (Array.isArray(value)) {\n    const directRules = value.filter(isDirectValidationRule)\n\n    if (directRules.length === value.length) {\n      return {\n        kind: ValidationRulesKind.DIRECT,\n        rules: directRules.map((rule): ExpressionValue => ({ kind: AuthoredValueKind.EXPRESSION, node: rule })),\n      }\n    }\n  }\n\n  return { kind: ValidationRulesKind.DYNAMIC, value: classify(value) }\n}\n\nfunction isDirectValidationRule(value: unknown): value is ASTNode | TemplateNode {\n  if (isTemplateNode(value)) {\n    return value.originalType === ASTNodeType.EXPRESSION && value.expressionType === ExpressionType.VALIDATION\n  }\n\n  if (!isASTNode(value) || !('id' in value) || value.type !== ASTNodeType.EXPRESSION) {\n    return false\n  }\n\n  return 'expressionType' in value && value.expressionType === ExpressionType.VALIDATION\n}\n","import { BlockType, ExpressionType, FunctionType, IteratorType } from '../../../../../authoring/types/enums'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport type { IterateASTNode } from '../../../contracts/ast/expressions.type'\nimport { isTemplateNode } from '../../../contracts/ast/nodes'\nimport type { FieldBlockASTNode } from '../../../contracts/ast/structures.type'\nimport type { TemplateNode, TemplateValue } from '../../../contracts/ast/template.type'\nimport { expressionValue, isExpressionLeaf, type AuthoredValue } from '../../../contracts/models/authoredValue.type'\nimport {\n  FieldCodeKind,\n  type DynamicFieldCode,\n  type FieldComponentModel,\n  type FieldModel,\n  type FieldValidationModel,\n  type IterateRef,\n  type StaticFieldCode,\n  type TransformerPipeline,\n} from '../../../contracts/models/fieldModel.type'\nimport { classifyValidationRules, hasConfiguredValue } from '../../../contracts/models/validationRules'\nimport ForgeInternalError from '../../../../errors/ForgeInternalError'\nimport AuthoredValueClassifier from './AuthoredValueClassifier'\nimport type ComponentRegistry from '../../../registries/ComponentRegistry'\n\ninterface TemplateMapIteratorProperties {\n  readonly input?: unknown\n  readonly iterator?: {\n    readonly type?: unknown\n    readonly yieldTemplate?: TemplateValue\n  }\n}\n\n/**\n * Builds a `FieldModel` for every field a step can produce — registered field\n * blocks first, then fields inside MAP iterator templates, in document order.\n * This is the analysis stage's single walk over template structure: the\n * lowering compilers (which turn analysis models into generated JavaScript)\n * iterate the resulting flat list and never re-walk the template tree.\n */\nexport default class FieldModelBuilder {\n  constructor(\n    private readonly componentRegistry: ComponentRegistry,\n    private readonly classifier: AuthoredValueClassifier = new AuthoredValueClassifier(),\n  ) {}\n\n  buildStepFields(fieldBlocks: readonly FieldBlockASTNode[], mapIterateNodes: readonly IterateASTNode[]): FieldModel[] {\n    const fields: FieldModel[] = []\n\n    fieldBlocks.forEach(block => {\n      fields.push(this.buildRegisteredField(block))\n    })\n    mapIterateNodes.forEach(iterateNode => {\n      this.collectIterateFields(iterateNode, fields)\n    })\n\n    return fields\n  }\n\n  private buildRegisteredField(block: FieldBlockASTNode): FieldModel {\n    const fieldCode = this.classifyFieldCode(block.properties.code)\n    const component = this.resolveComponent(block.variant)\n\n    return {\n      source: block,\n      iteratorPath: [],\n      code: fieldCode,\n      component,\n      formatters: this.classifyTransformers(block.properties.formatters),\n      parsers: this.classifyTransformers(block.properties.parsers),\n      defaultValue: this.classifyDefaultValue(block.properties.defaultValue),\n      dependentWhen: this.classifyDependentWhen(block.properties.dependentWhen),\n      validation: this.classifyValidation(block.properties.validWhen),\n      label: this.deriveFieldLabel(component.variant, fieldCode),\n    }\n  }\n\n  private collectIterateFields(iterateNode: IterateASTNode, fields: FieldModel[]): void {\n    const { iterator } = iterateNode.properties\n\n    if (iterator.type !== IteratorType.MAP || iterator.yieldTemplate === undefined) {\n      return\n    }\n\n    this.collectTemplateFields(iterator.yieldTemplate, [{ node: iterateNode }], fields)\n  }\n\n  private collectTemplateFields(template: TemplateValue, iteratorPath: IterateRef[], fields: FieldModel[]): void {\n    if (template === null || template === undefined || typeof template !== 'object') {\n      return\n    }\n\n    if (isTemplateNode(template)) {\n      if (template.originalType === ASTNodeType.EXPRESSION && template.expressionType === ExpressionType.ITERATE) {\n        this.collectNestedIterateFields(template, iteratorPath, fields)\n\n        return\n      }\n\n      if (template.originalType === ASTNodeType.BLOCK && template.blockType === BlockType.FIELD) {\n        fields.push(this.buildTemplateField(template, iteratorPath))\n      }\n\n      Object.values(template.properties ?? {}).forEach(child => {\n        this.collectTemplateFields(child as TemplateValue, iteratorPath, fields)\n      })\n\n      return\n    }\n\n    if (Array.isArray(template)) {\n      template.forEach(item => {\n        this.collectTemplateFields(item, iteratorPath, fields)\n      })\n\n      return\n    }\n\n    Object.values(template as Record<string, TemplateValue>).forEach(item => {\n      this.collectTemplateFields(item, iteratorPath, fields)\n    })\n  }\n\n  private collectNestedIterateFields(template: TemplateNode, iteratorPath: IterateRef[], fields: FieldModel[]): void {\n    const properties = (template.properties ?? {}) as TemplateMapIteratorProperties\n    const iterator = properties.iterator\n\n    if (iterator?.type !== IteratorType.MAP || iterator.yieldTemplate === undefined) {\n      return\n    }\n\n    this.collectTemplateFields(iterator.yieldTemplate, [...iteratorPath, { node: template }], fields)\n  }\n\n  private buildTemplateField(template: TemplateNode, iteratorPath: IterateRef[]): FieldModel {\n    const properties = template.properties ?? {}\n    const variant = typeof template.variant === 'string' ? template.variant : ''\n    const fieldCode = this.classifyTemplateFieldCode(properties.code)\n    const component = this.resolveComponent(variant)\n\n    return {\n      source: template,\n      iteratorPath: [...iteratorPath],\n      code: fieldCode,\n      component,\n      formatters: this.classifyTransformers(properties.formatters),\n      parsers: this.classifyTransformers(properties.parsers),\n      defaultValue: this.classifyDefaultValue(properties.defaultValue),\n      dependentWhen: this.classifyDependentWhen(properties.dependentWhen),\n      validation: this.classifyValidation(properties.validWhen),\n      label: this.deriveFieldLabel(component.variant, fieldCode),\n    }\n  }\n\n  private classifyFieldCode(fieldCode: unknown): StaticFieldCode | DynamicFieldCode | undefined {\n    if (typeof fieldCode === 'string') {\n      return { kind: FieldCodeKind.STATIC, value: fieldCode }\n    }\n\n    if (isExpressionLeaf(fieldCode)) {\n      return { kind: FieldCodeKind.DYNAMIC, node: expressionValue(fieldCode) }\n    }\n\n    return undefined\n  }\n\n  /** Template field codes are only ever static strings or template expressions. */\n  private classifyTemplateFieldCode(fieldCode: unknown): StaticFieldCode | DynamicFieldCode | undefined {\n    if (typeof fieldCode === 'string') {\n      return { kind: FieldCodeKind.STATIC, value: fieldCode }\n    }\n\n    if (isTemplateNode(fieldCode)) {\n      return { kind: FieldCodeKind.DYNAMIC, node: expressionValue(fieldCode) }\n    }\n\n    return undefined\n  }\n\n  /**\n   * A missing variant is impossible for authored components — semantic analysis\n   * has already rejected unregistered variants. The empty variant covers\n   * template fields whose variant is not a static string; those resolve to a\n   * component with no input schema, matching the registry's absent-entry shape.\n   */\n  private resolveComponent(variant: string): FieldComponentModel {\n    if (variant === '') {\n      return { variant, acceptsMultipleValues: false, validatesInput: false }\n    }\n\n    const component = this.componentRegistry.get(variant)\n\n    if (component === undefined) {\n      throw new ForgeInternalError(`Component \"${variant}\" is not registered`)\n    }\n\n    return {\n      variant,\n      acceptsMultipleValues: component.multiple === true,\n      validatesInput: component.inputSchema !== undefined,\n    }\n  }\n\n  /** Entries that aren't AST nodes are skipped. A node that isn't a transformer call can't happen in valid authored code. */\n  private classifyTransformers(transformers: unknown): TransformerPipeline | undefined {\n    if (!Array.isArray(transformers)) {\n      return undefined\n    }\n\n    const calls = transformers.filter(isExpressionLeaf).map(transformerNode => {\n      const name = readTransformerName(transformerNode)\n\n      if (name === undefined) {\n        throw new ForgeInternalError('Formatter entry is not a transformer function call')\n      }\n\n      return {\n        name,\n        arguments: readTransformerArguments(transformerNode).map(argument => this.classifier.classify(argument)),\n        node: expressionValue(transformerNode),\n      }\n    })\n\n    return calls.length > 0 ? calls : undefined\n  }\n\n  private classifyDefaultValue(defaultValue: unknown): AuthoredValue | undefined {\n    return defaultValue === undefined ? undefined : this.classifier.classify(defaultValue)\n  }\n\n  private classifyDependentWhen(dependentWhen: unknown): AuthoredValue | undefined {\n    if (!dependentWhen || !isExpressionLeaf(dependentWhen)) {\n      return undefined\n    }\n\n    return this.classifier.classify(dependentWhen)\n  }\n\n  private classifyValidation(validWhen: unknown): FieldValidationModel | undefined {\n    if (!hasConfiguredValue(validWhen)) {\n      return undefined\n    }\n\n    return { rules: classifyValidationRules(validWhen, value => this.classifier.classify(value)) }\n  }\n\n  private deriveFieldLabel(variant: string, fieldCode: StaticFieldCode | DynamicFieldCode | undefined): string {\n    const variantLabel = variant === '' ? 'unknown component' : variant\n\n    if (fieldCode === undefined) {\n      return variantLabel\n    }\n\n    return fieldCode.kind === FieldCodeKind.STATIC\n      ? `${variantLabel} \"${fieldCode.value}\"`\n      : `${variantLabel} (dynamic code)`\n  }\n}\n\nfunction readTransformerName(value: object): string | undefined {\n  if (readExpressionType(value) !== FunctionType.TRANSFORMER) {\n    return undefined\n  }\n\n  const name = readTransformerProperties(value).name\n\n  return typeof name === 'string' ? name : undefined\n}\n\nfunction readTransformerArguments(value: object): unknown[] {\n  const argumentsValue = readTransformerProperties(value).arguments\n\n  return Array.isArray(argumentsValue) ? argumentsValue : []\n}\n\n// A transformer call carries name/arguments on `properties`; loosely authored\n// shapes may carry them on the value itself.\nfunction readTransformerProperties(value: object): Record<string, unknown> {\n  return readProperties(value) ?? (value as Record<string, unknown>)\n}\n\nfunction readExpressionType(value: object): unknown {\n  const record = value as Record<string, unknown>\n\n  return record.expressionType ?? record.type\n}\n\nfunction readProperties(value: object): Record<string, unknown> | undefined {\n  const properties = (value as Record<string, unknown>).properties\n\n  return properties !== null && typeof properties === 'object' && !Array.isArray(properties)\n    ? (properties as Record<string, unknown>)\n    : undefined\n}\n","/** Any node that carries diagnostic info (both AST nodes and template nodes qualify). */\nexport interface LabelSource {\n  readonly diagnostics?: {\n    readonly source: { readonly formattedPath: string }\n  }\n}\n\n/**\n * Turns a node's diagnostic path into a short dot-separated label used to\n * identify compiled output (e.g. in generated script URLs). Takes the leading\n * journey/step name segments from a formatted path like\n * `\"dump > form > blocks[1] (govukInsetText) > hidden\"` and produces\n * `dump.form`. Segments containing `[` or `(` (like `blocks[1]` or\n * `(govukInsetText)`) mark positions inside a step rather than its identity,\n * so they stop the walk. Nested journeys keep every ancestor name segment.\n * `maxDepth` caps the segment count for labels that only need journey-level\n * granularity (e.g. the field inventory).\n */\nexport default class NodeLabeller {\n  labelFrom(nodes: readonly (LabelSource | undefined)[], options: { maxDepth?: number } = {}): string | undefined {\n    const formattedPath = nodes.find(node => node?.diagnostics !== undefined)?.diagnostics?.source.formattedPath\n\n    if (formattedPath === undefined) {\n      return undefined\n    }\n\n    const identitySegments: string[] = []\n\n    formattedPath\n      .split(' > ')\n      .slice(0, options.maxDepth ?? Number.POSITIVE_INFINITY)\n      .some(segment => {\n        if (segment.includes('[') || segment.includes('(')) {\n          return true\n        }\n\n        identitySegments.push(segment.replace(/[^\\w.-]+/g, '-'))\n\n        return false\n      })\n\n    return identitySegments.length > 0 ? identitySegments.join('.') : undefined\n  }\n}\n","import { BlockType, ExpressionType, IteratorType } from '../../../../../authoring/types/enums'\nimport type { ASTNode, NodeId } from '../../../contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport type { IterateASTNode } from '../../../contracts/ast/expressions.type'\nimport type { FieldBlockASTNode, JourneyASTNode, StepASTNode } from '../../../contracts/ast/structures.type'\nimport type ASTNodeIndex from '../../ast/ast-state/ASTNodeIndex'\nimport Ancestry from './Ancestry'\n\nexport interface StepOwnership {\n  readonly stepNode: StepASTNode\n  readonly fieldBlocks: FieldBlockASTNode[]\n  readonly mapIterateNodes: IterateASTNode[]\n  readonly allIterateNodes: IterateASTNode[]\n}\n\nexport interface JourneyOwnership {\n  readonly journeyNode: JourneyASTNode\n  readonly stepNodes: StepASTNode[]\n}\n\n/**\n * Groups every AST node by its owning step and journey in a single pass.\n *\n * Nodes are registered in top-down depth-first order (by\n * `NodeRegistrationWalker`), so grouping by nearest owner preserves document\n * order within each bucket. This replaces the old approach of re-scanning\n * parent chains per step, which was O(steps x nodes).\n */\nexport default class OwnershipIndex {\n  private readonly stepBuckets = new Map<NodeId, StepOwnership>()\n\n  private readonly journeyBuckets = new Map<NodeId, JourneyOwnership>()\n\n  constructor(\n    nodeIndex: ASTNodeIndex,\n    private readonly ancestry: Ancestry = new Ancestry(),\n  ) {\n    nodeIndex.findByType<JourneyASTNode>(ASTNodeType.JOURNEY).forEach(journeyNode => {\n      this.journeyBuckets.set(journeyNode.id, { journeyNode, stepNodes: [] })\n    })\n    nodeIndex.findByType<StepASTNode>(ASTNodeType.STEP).forEach(stepNode => {\n      this.stepBuckets.set(stepNode.id, {\n        stepNode,\n        fieldBlocks: [],\n        mapIterateNodes: [],\n        allIterateNodes: [],\n      })\n      this.journeyBucketFor(stepNode)?.stepNodes.push(stepNode)\n    })\n    nodeIndex.findByType<FieldBlockASTNode>(BlockType.FIELD).forEach(fieldBlock => {\n      this.nearestStepBucket(fieldBlock)?.fieldBlocks.push(fieldBlock)\n    })\n    nodeIndex.findByType<IterateASTNode>(ExpressionType.ITERATE).forEach(iterateNode => {\n      const stepBucket = this.nearestStepBucket(iterateNode)\n\n      if (stepBucket === undefined) {\n        return\n      }\n\n      stepBucket.allIterateNodes.push(iterateNode)\n\n      if (iterateNode.properties.iterator.type === IteratorType.MAP) {\n        stepBucket.mapIterateNodes.push(iterateNode)\n      }\n    })\n  }\n\n  /** Every registered journey with its directly owned steps, in document order. */\n  journeys(): JourneyOwnership[] {\n    return [...this.journeyBuckets.values()]\n  }\n\n  // Accessors return a copy of the bucket (like `ASTNodeIndex.findByType`) so\n  // callers can't mutate the index's internal lists.\n  fieldBlocksOf(stepId: NodeId): FieldBlockASTNode[] {\n    return [...(this.stepBuckets.get(stepId)?.fieldBlocks ?? [])]\n  }\n\n  mapIterateNodesOf(stepId: NodeId): IterateASTNode[] {\n    return [...(this.stepBuckets.get(stepId)?.mapIterateNodes ?? [])]\n  }\n\n  allIterateNodesOf(stepId: NodeId): IterateASTNode[] {\n    return [...(this.stepBuckets.get(stepId)?.allIterateNodes ?? [])]\n  }\n\n  // A step without a registered parent journey stays unattached. The\n  // compilation model builder rejects that state, so partial test registries\n  // can still work here without errors.\n  private journeyBucketFor(stepNode: StepASTNode): JourneyOwnership | undefined {\n    const parentJourney = stepNode.parent\n\n    return this.isJourneyNode(parentJourney) ? this.journeyBuckets.get(parentJourney.id) : undefined\n  }\n\n  // Steps never nest, so the nearest step ancestor is the unique owning step.\n  private nearestStepBucket(node: ASTNode): StepOwnership | undefined {\n    const owningStep = this.ancestry.nearestAncestorSetting(node, ancestor =>\n      this.isStepNode(ancestor) ? ancestor : undefined,\n    )\n\n    return owningStep === undefined ? undefined : this.stepBuckets.get(owningStep.id)\n  }\n\n  private isJourneyNode(node: ASTNode | undefined): node is JourneyASTNode {\n    return node?.type === ASTNodeType.JOURNEY\n  }\n\n  private isStepNode(node: ASTNode): node is StepASTNode {\n    return node.type === ASTNodeType.STEP\n  }\n}\n","/**\n * Normalize an application base path to either '' or '/segment[/child]'.\n */\nexport function normalizeBasePath(basePath?: string): string {\n  if (!basePath) {\n    return ''\n  }\n\n  let normalized = basePath\n\n  if (!normalized.startsWith('/')) {\n    normalized = `/${normalized}`\n  }\n\n  if (normalized.endsWith('/')) {\n    normalized = normalized.slice(0, -1)\n  }\n\n  return normalized\n}\n\n/**\n * Normalize a relative journey path key for runtime comparisons.\n *\n * Keeps external URLs untouched apart from dropping query/hash fragments so\n * they never collide with internal step keys.\n */\nexport function normalizeRelativePath(path: string): string {\n  const normalizedPath = path.startsWith('/') ? path.slice(1) : path\n\n  return normalizedPath.split(/[?#]/)[0] ?? normalizedPath\n}\n\n/**\n * Resolve route params embedded in a path template.\n */\nexport function resolvePathParams(path: string, params: Record<string, string>): string {\n  return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (match, name) => params[name] ?? match)\n}\n\n/**\n * Join path segments, collapsing consecutive slashes.\n */\nexport function joinPaths(...segments: string[]): string {\n  return `/${segments.join('/').split('/').filter(Boolean).join('/')}`\n}\n","import { normalizeRelativePath } from '../../../../../shared/routePath'\nimport type { JourneyASTNode, StepASTNode } from '../../../contracts/ast/structures.type'\nimport type { JourneyMountInfo, StepMountInfo } from '../../../contracts/plans/mountInfo.type'\nimport Ancestry from './Ancestry'\n\nexport default class MountInfoAnalyzer {\n  constructor(private readonly ancestry: Ancestry = new Ancestry()) {}\n\n  buildStepMountInfo(stepNode: StepASTNode): StepMountInfo {\n    return {\n      stepId: stepNode.id,\n      path: normalizeRelativePath(stepNode.properties.path),\n    }\n  }\n\n  buildJourneyMountInfo(journeyNode: JourneyASTNode): JourneyMountInfo {\n    return {\n      journeyId: journeyNode.id,\n      path: normalizeRelativePath(journeyNode.properties.path),\n    }\n  }\n\n  // Ancestor static data merges root-first so a descendant's `data` overrides its ancestors'.\n  resolveStaticData(node: JourneyASTNode | StepASTNode): Record<string, unknown> {\n    return this.ancestry.valuesRootFirst<Record<string, unknown>>(node, ancestor => ancestor.properties?.data)\n      .reduce((data, staticData) => ({ ...data, ...staticData }), {})\n  }\n}\n","import { OutcomeType } from '../../../../authoring/types/enums'\nimport { ASTNodeType } from './enums'\nimport { OutcomeASTNode, RedirectOutcomeASTNode, ThrowErrorOutcomeASTNode } from './expressions.type'\n\n/**\n * Check if an AST node is any type of Outcome node\n */\nfunction isOutcomeNode(obj: any): obj is OutcomeASTNode {\n  return obj != null && obj.type === ASTNodeType.OUTCOME\n}\n\n/**\n * Check if an AST node is a Redirect Outcome node\n */\nexport function isRedirectOutcomeNode(obj: any): obj is RedirectOutcomeASTNode {\n  return isOutcomeNode(obj) && obj.outcomeType === OutcomeType.REDIRECT\n}\n\n/**\n * Check if an AST node is a ThrowError Outcome node\n */\nexport function isThrowErrorOutcomeNode(obj: any): obj is ThrowErrorOutcomeASTNode {\n  return isOutcomeNode(obj) && obj.outcomeType === OutcomeType.THROW_ERROR\n}\n","import { ExpressionType } from '../../../../authoring/types/enums'\nimport type { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { ReferenceASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport { isASTNode } from '../../../chassis/contracts/ast/nodes'\n\nexport default class RequestTimeReferenceAnalyzer {\n  private static readonly REQUEST_TIME_NAMESPACES: ReadonlySet<string> = new Set(['post', 'params', 'query', 'request'])\n\n  containsRequestTimeReference(node: ASTNode): boolean {\n    if (this.isRequestTimeReference(node)) {\n      return true\n    }\n\n    return Object.values(node.properties ?? {}).some(value => this.containsRequestTimeReferenceInValue(value))\n  }\n\n  private containsRequestTimeReferenceInValue(value: unknown): boolean {\n    if (Array.isArray(value)) {\n      return value.some(item => this.containsRequestTimeReferenceInValue(item))\n    }\n\n    if (isASTNode(value)) {\n      return this.containsRequestTimeReference(value)\n    }\n\n    if (this.isPlainRecord(value)) {\n      return Object.values(value).some(item => this.containsRequestTimeReferenceInValue(item))\n    }\n\n    return false\n  }\n\n  private isRequestTimeReference(node: ASTNode): boolean {\n    if (!this.isReferenceNode(node)) {\n      return false\n    }\n\n    const root = node.properties.path[0]\n\n    return typeof root === 'string' && RequestTimeReferenceAnalyzer.REQUEST_TIME_NAMESPACES.has(root)\n  }\n\n  private isReferenceNode(node: ASTNode): node is ReferenceASTNode {\n    return node.type === ASTNodeType.EXPRESSION &&\n      'expressionType' in node &&\n      node.expressionType === ExpressionType.REFERENCE\n  }\n\n  private isPlainRecord(value: unknown): value is Record<string, unknown> {\n    return value !== null && typeof value === 'object'\n  }\n}\n","import type { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport type { RedirectOutcomeASTNode, SubmitHookASTNode } from '../../../chassis/contracts/ast/expressions.type'\nimport type { StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport { isASTNode } from '../../../chassis/contracts/ast/nodes'\nimport { isRedirectOutcomeNode } from '../../../chassis/contracts/ast/outcome-nodes'\nimport type { ForwardOutcomeGroup } from '../contracts/reachabilityModel.type'\nimport RequestTimeReferenceAnalyzer from './RequestTimeReferenceAnalyzer'\n\nexport interface ForwardNavigationAnalysis {\n  readonly forwardOutcomeGroups: ForwardOutcomeGroup[]\n}\n\nexport default class ForwardNavigationAnalyzer {\n  constructor(private readonly requestTimeReferenceAnalyzer = new RequestTimeReferenceAnalyzer()) {}\n\n  analyze(stepNode: StepASTNode): ForwardNavigationAnalysis {\n    const submitHooks = stepNode.properties.onSubmission ?? []\n\n    return {\n      forwardOutcomeGroups: submitHooks\n        .map(hook => this.buildForwardOutcomeGroup(hook))\n        .filter(group => group.redirectOutcomes.length > 0),\n    }\n  }\n\n  private buildForwardOutcomeGroup(hook: SubmitHookASTNode): ForwardOutcomeGroup {\n    const redirectOutcomes = this.forwardRedirectOutcomes(hook).map(node => ({\n      node,\n      overApproximatesWhen: this.overApproximatesOutcomeWhen(node.properties.when),\n    }))\n\n    return {\n      hookWhen: this.resolveReachabilityCompilableHookWhen(hook.properties.when),\n      redirectOutcomes,\n    }\n  }\n\n  private resolveReachabilityCompilableHookWhen(when: ASTNode | undefined): ASTNode | undefined {\n    if (when === undefined || !isASTNode(when)) {\n      return undefined\n    }\n\n    if (this.requestTimeReferenceAnalyzer.containsRequestTimeReference(when)) {\n      return undefined\n    }\n\n    return when\n  }\n\n  private forwardRedirectOutcomes(hook: SubmitHookASTNode): RedirectOutcomeASTNode[] {\n    const alwaysOutcomes = (hook.properties.onAlways?.next ?? []).filter(isRedirectOutcomeNode)\n    const validOutcomes = hook.properties.validate\n      ? (hook.properties.onValid?.next ?? []).filter(isRedirectOutcomeNode)\n      : []\n\n    return [...alwaysOutcomes, ...validOutcomes]\n  }\n\n  private overApproximatesOutcomeWhen(when: ASTNode | undefined): boolean {\n    return when !== undefined && isASTNode(when) && this.requestTimeReferenceAnalyzer.containsRequestTimeReference(when)\n  }\n}\n","import type { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type { JourneyASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport type {\n  ReachabilityStateTable,\n  ReachabilityEntryModel,\n  ReachabilityModel,\n} from '../contracts/reachabilityModel.type'\nimport type {\n  JourneyAnalysisContext,\n  JourneyModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport ForwardNavigationAnalyzer from './ForwardNavigationAnalyzer'\n\nexport default class ReachabilityAnalyzer implements JourneyModelAnalyzer<ReachabilityModel> {\n  private readonly forwardNavigationAnalyzer = new ForwardNavigationAnalyzer()\n\n  analyzeJourney(context: JourneyAnalysisContext): ReachabilityModel {\n    const { journeyNode } = context\n    const entries = context.stepNodes.map(stepNode => this.buildReachabilityEntry(stepNode))\n    const resumeWhen = journeyNode.properties.reachability?.resumeWhen\n    const resumeAlways = resumeWhen === true\n    const resumeWhenNode = resumeWhen !== undefined && resumeWhen !== true ? resumeWhen : undefined\n    const stateTable: ReachabilityStateTable = {\n      entries: entries.map(entry => ({\n        stepId: entry.stepId,\n        code: entry.code,\n        isEntryPoint: entry.isEntryPoint,\n      })),\n      unreachableRedirect: journeyNode.properties.reachability?.unreachableRedirect ?? 'entry',\n      reachabilityDisabled: this.resolveReachabilityDisabled(context),\n    }\n\n    return {\n      label: this.deriveLabel(context, entries, resumeWhenNode),\n      stateTable,\n      entries,\n      resumeAlways,\n      resumeWhen: resumeWhenNode,\n    }\n  }\n\n  private buildReachabilityEntry(stepNode: StepASTNode): ReachabilityEntryModel {\n    const stepId = stepNode.id\n    const { forwardOutcomeGroups } = this.forwardNavigationAnalyzer.analyze(stepNode)\n\n    const reachability = stepNode.properties.reachability\n    const entryWhen = reachability?.entryWhen\n\n    return {\n      stepId,\n      code: stepNode.properties.code,\n      isEntryPoint: entryWhen === true,\n      entryWhen: entryWhen !== undefined && entryWhen !== true ? entryWhen : undefined,\n      forwardOutcomeGroups,\n      cleardownFieldCodes: stepNode.properties.cleardownFieldCodes ?? [],\n      reachabilityTieBreakers: (reachability?.tieBreakers ?? []).map(entry => ({\n        priority: entry.properties.priority,\n        when: entry.properties.when,\n      })),\n    }\n  }\n\n  // The disable flag inherits from the nearest journey that sets one, starting\n  // with the journey itself.\n  private resolveReachabilityDisabled(context: JourneyAnalysisContext): boolean {\n    return context.ancestry.nearestAncestorSetting(context.journeyNode, ancestor =>\n        this.isJourneyNode(ancestor) ? ancestor.properties.reachability?.disableReachabilityChecks : undefined,\n      ) ?? false\n  }\n\n  // The label is derived from any reachability-related expression nodes (resume\n  // conditions, entry conditions, redirect targets). It names the journey\n  // segment of the generated function's URL for debugging.\n  private deriveLabel(\n    context: JourneyAnalysisContext,\n    entries: readonly ReachabilityEntryModel[],\n    resumeWhen: ASTNode | undefined,\n  ): string | undefined {\n    const dynamicNodes = [\n      resumeWhen,\n      ...entries.flatMap(entry => [\n        entry.entryWhen,\n        ...entry.forwardOutcomeGroups.flatMap(group => group.redirectOutcomes.map(outcome => outcome.node)),\n      ]),\n    ]\n\n    return context.labels.labelFrom(dynamicNodes, { maxDepth: 1 })\n  }\n\n  private isJourneyNode(node: ASTNode): node is JourneyASTNode {\n    return node.type === ASTNodeType.JOURNEY\n  }\n}\n","import type {\n  JourneyAnalysisContext,\n  JourneyModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport type { CleardownModel } from '../contracts/cleardownModel.type'\n\nexport default class AnswerCleardownAnalyzer implements JourneyModelAnalyzer<CleardownModel> {\n  analyzeJourney(context: JourneyAnalysisContext): CleardownModel {\n    const { stepNodes, ownership, labels } = context\n    const inventoryNodes = stepNodes.flatMap(stepNode => [\n      ...ownership.fieldBlocksOf(stepNode.id),\n      ...ownership.mapIterateNodesOf(stepNode.id),\n    ])\n\n    return {\n      label: labels.labelFrom(inventoryNodes, { maxDepth: 1 }),\n      steps: stepNodes.map(stepNode => ({\n        stepId: stepNode.id,\n        fields: context.stepFields.get(stepNode.id) ?? [],\n        cleardownFieldCodes: stepNode.properties.cleardownFieldCodes ?? [],\n      })),\n    }\n  }\n}\n","import type {\n  JourneyAnalysisContext,\n  JourneyModelAnalyzer,\n  StepAnalysisContext,\n  StepModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport type { FieldModel } from '../../../chassis/contracts/models/fieldModel.type'\nimport type { AnswerPreparationModel } from '../contracts/answerPreparationModel.type'\n\nexport default class AnswerPreparationAnalyzer\n  implements StepModelAnalyzer<AnswerPreparationModel>, JourneyModelAnalyzer<AnswerPreparationModel>\n{\n  analyzeStep(context: StepAnalysisContext): AnswerPreparationModel {\n    const { stepNode, ownership, labels } = context\n\n    return {\n      label: labels.labelFrom([\n        stepNode,\n        ...ownership.fieldBlocksOf(stepNode.id),\n        ...ownership.mapIterateNodesOf(stepNode.id),\n      ]),\n      fields: context.fields,\n    }\n  }\n\n  /** The journey model combines fields from all owned steps, preserving step order. */\n  analyzeJourney(context: JourneyAnalysisContext): AnswerPreparationModel {\n    const { stepNodes, ownership, labels } = context\n    const inventoryNodes = stepNodes.flatMap(stepNode => [\n      ...ownership.fieldBlocksOf(stepNode.id),\n      ...ownership.mapIterateNodesOf(stepNode.id),\n    ])\n    const fields = stepNodes.flatMap((stepNode): readonly FieldModel[] => context.stepFields.get(stepNode.id) ?? [])\n\n    return {\n      label: labels.labelFrom(inventoryNodes),\n      fields,\n    }\n  }\n}\n","import { FunctionType } from '../../../../authoring/types/enums'\nimport type {\n  JourneyAnalysisContext,\n  JourneyModelAnalyzer,\n  StepAnalysisContext,\n  StepModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport type Ancestry from '../../../chassis/compilation/analysis/shared/Ancestry'\nimport type AuthoredValueClassifier from '../../../chassis/compilation/analysis/shared/AuthoredValueClassifier'\nimport type { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type {\n  AccessHookASTNode,\n  FunctionASTNode,\n  RedirectOutcomeASTNode,\n  SubmitHookASTNode,\n  ThrowErrorOutcomeASTNode,\n} from '../../../chassis/contracts/ast/expressions.type'\nimport { isRedirectOutcomeNode, isThrowErrorOutcomeNode } from '../../../chassis/contracts/ast/outcome-nodes'\nimport type { JourneyASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport { expressionValue, type ExpressionValue } from '../../../chassis/contracts/models/authoredValue.type'\nimport type {\n  AccessHookModel,\n  AccessLifecycleModel,\n  EffectCall,\n  HookOutcomeModel,\n  JourneyHookModel,\n  StepHookModel,\n  SubmitBranchModel,\n  SubmitHookModel,\n} from '../contracts/hookModel.type'\nimport { HookOutcomeKind } from '../contracts/hookModel.type'\n\ntype SubmitBranchAST = { effects?: ASTNode[]; next?: ASTNode[] } | undefined\n\nexport default class HookAnalyzer implements StepModelAnalyzer<StepHookModel>, JourneyModelAnalyzer<JourneyHookModel> {\n  analyzeStep(context: StepAnalysisContext): StepHookModel {\n    const { stepNode, labels } = context\n    const accessHookNodes = this.resolveAccessHooks(stepNode, context.ancestry)\n    const submitHookNodes = stepNode.properties.onSubmission ?? []\n\n    return {\n      access: this.buildAccessLifecycle(\n        accessHookNodes,\n        labels.labelFrom([stepNode, ...accessHookNodes]),\n        context.classifier,\n      ),\n      submit: {\n        label: labels.labelFrom([stepNode, ...submitHookNodes]),\n        hooks: submitHookNodes.map((hook, hookIndex) => this.buildSubmitHook(hook, hookIndex, context.classifier)),\n      },\n    }\n  }\n\n  analyzeJourney(context: JourneyAnalysisContext): JourneyHookModel {\n    const accessHookNodes = this.resolveAccessHooks(context.journeyNode, context.ancestry)\n\n    return {\n      access: this.buildAccessLifecycle(accessHookNodes, context.labels.labelFrom(accessHookNodes), context.classifier),\n    }\n  }\n\n  private buildAccessLifecycle(\n    hookNodes: readonly AccessHookASTNode[],\n    label: string | undefined,\n    classifier: AuthoredValueClassifier,\n  ): AccessLifecycleModel {\n    return {\n      label,\n      hooks: hookNodes.map((hook, hookIndex) => this.buildAccessHook(hook, hookIndex, classifier)),\n    }\n  }\n\n  // Access hooks flatten root-first, so an outer journey's hooks run before an inner node's.\n  private resolveAccessHooks(node: JourneyASTNode | StepASTNode, ancestry: Ancestry): AccessHookASTNode[] {\n    return ancestry\n      .valuesRootFirst<AccessHookASTNode[]>(node, ancestor =>\n        this.isAccessAncestor(ancestor) ? ancestor.properties.onAccess : undefined,\n      )\n      .flat()\n  }\n\n  private buildAccessHook(\n    hook: AccessHookASTNode,\n    hookIndex: number,\n    classifier: AuthoredValueClassifier,\n  ): AccessHookModel {\n    const key = `access-hook-${hookIndex}`\n\n    return {\n      key,\n      label: this.describeHookNode(hook, key),\n      when: this.classifyExpression(hook.properties.when),\n      effects: this.classifyEffects(hook.properties.effects, key, classifier),\n      outcomes: this.classifyOutcomes(hook.properties.next),\n    }\n  }\n\n  private buildSubmitHook(\n    hook: SubmitHookASTNode,\n    hookIndex: number,\n    classifier: AuthoredValueClassifier,\n  ): SubmitHookModel {\n    const key = `submit-hook-${hookIndex}`\n    const validationGroups = hook.properties.validationGroups ?? []\n\n    return {\n      key,\n      label: this.describeHookNode(hook, key),\n      when: this.classifyExpression(hook.properties.when),\n      guards: this.classifyExpression(hook.properties.guards),\n      validate: hook.properties.validate,\n      validationGroups: validationGroups.length > 0 ? validationGroups : ['default'],\n      branches: {\n        // Even if the author didn't write an `onAlways` branch, we still compile an empty one.\n        onAlways: this.buildSubmitBranch(hook.properties.onAlways, `${key}-onAlways`, classifier),\n        onValid:\n          hook.properties.onValid !== undefined\n            ? this.buildSubmitBranch(hook.properties.onValid, `${key}-onValid`, classifier)\n            : undefined,\n        onInvalid:\n          hook.properties.onInvalid !== undefined\n            ? this.buildSubmitBranch(hook.properties.onInvalid, `${key}-onInvalid`, classifier)\n            : undefined,\n      },\n    }\n  }\n\n  private buildSubmitBranch(\n    branch: SubmitBranchAST,\n    branchKey: string,\n    classifier: AuthoredValueClassifier,\n  ): SubmitBranchModel {\n    return {\n      effects: this.classifyEffects(branch?.effects, branchKey, classifier),\n      outcomes: this.classifyOutcomes(branch?.next),\n    }\n  }\n\n  private classifyEffects(\n    effects: ASTNode[] | undefined,\n    keyPrefix: string,\n    classifier: AuthoredValueClassifier,\n  ): EffectCall[] {\n    return (effects ?? [])\n      .filter(node => this.isEffectNode(node))\n      .map((effect, effectIndex) => ({\n        key: `${keyPrefix}-effect-${effectIndex}`,\n        name: effect.properties.name,\n        arguments: (effect.properties.arguments ?? []).map(argument => classifier.classify(argument)),\n        node: expressionValue(effect),\n      }))\n  }\n\n  private classifyOutcomes(next: ASTNode[] | undefined): HookOutcomeModel[] {\n    return (next ?? [])\n      .filter(node => this.isOutcomeNode(node))\n      .map(outcomeNode =>\n        isRedirectOutcomeNode(outcomeNode)\n          ? this.classifyRedirectOutcome(outcomeNode)\n          : this.classifyThrowErrorOutcome(outcomeNode),\n      )\n  }\n\n  private classifyRedirectOutcome(redirect: RedirectOutcomeASTNode): HookOutcomeModel {\n    const { goto } = redirect.properties\n\n    return {\n      kind: HookOutcomeKind.REDIRECT,\n      when: this.classifyExpression(redirect.properties.when),\n      goto: typeof goto === 'string' ? goto : expressionValue(goto),\n    }\n  }\n\n  private classifyThrowErrorOutcome(errorOutcome: ThrowErrorOutcomeASTNode): HookOutcomeModel {\n    const { message } = errorOutcome.properties\n\n    return {\n      kind: HookOutcomeKind.THROW_ERROR,\n      when: this.classifyExpression(errorOutcome.properties.when),\n      status: errorOutcome.properties.status,\n      message: typeof message === 'string' ? message : expressionValue(message),\n    }\n  }\n\n  private classifyExpression(node: ASTNode | undefined): ExpressionValue | undefined {\n    return node === undefined ? undefined : expressionValue(node)\n  }\n\n  private describeHookNode(hook: AccessHookASTNode | SubmitHookASTNode, hookKey: string): string {\n    return hook.diagnostics?.source.formattedPath ?? hookKey\n  }\n\n  private isAccessAncestor(node: ASTNode): node is JourneyASTNode | StepASTNode {\n    return node.type === ASTNodeType.JOURNEY || node.type === ASTNodeType.STEP\n  }\n\n  private isEffectNode(node: ASTNode): node is FunctionASTNode {\n    return node.type === ASTNodeType.EXPRESSION &&\n      (node as { expressionType?: unknown }).expressionType === FunctionType.EFFECT\n  }\n\n  private isOutcomeNode(node: ASTNode): node is RedirectOutcomeASTNode | ThrowErrorOutcomeASTNode {\n    return isRedirectOutcomeNode(node) || isThrowErrorOutcomeNode(node)\n  }\n}\n","import type {\n  StepAnalysisContext,\n  StepModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport { classifyValidationRules, hasConfiguredValue } from '../../../chassis/contracts/models/validationRules'\nimport type { ValidationModel } from '../contracts/validationModel.type'\n\nexport default class ValidationAnalyzer implements StepModelAnalyzer<ValidationModel> {\n  analyzeStep(context: StepAnalysisContext): ValidationModel {\n    const { stepNode, labels } = context\n    const validatingFields = context.fields.filter(field => field.validation !== undefined)\n    const domainValidWhen = stepNode.properties.validWhen\n    const hasDomainValidation = hasConfiguredValue(domainValidWhen)\n\n    return {\n      label: labels.labelFrom([stepNode]),\n      // Fields inside iterator templates don't count towards eager validity checks\n      // (pre-reachability validation). Only top-level registered fields with\n      // validation and a step-level `validWhen` condition count.\n      hasValidation: validatingFields.some(field => field.iteratorPath.length === 0) || hasDomainValidation,\n      fields: validatingFields,\n      domainRules: hasDomainValidation\n        ? classifyValidationRules(domainValidWhen, value => context.classifier.classify(value))\n        : undefined,\n      entryValidation: stepNode.properties.validateOnEntry ?? [],\n    }\n  }\n}\n","import { BlockType, IteratorType } from '../../../../authoring/types/enums'\nimport type { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { BlockASTNode, JourneyASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport type { TemplateNode, TemplateValue } from '../../../chassis/contracts/ast/template.type'\nimport { AuthoredValueKind, type AuthoredValue } from '../../../chassis/contracts/models/authoredValue.type'\nimport type {\n  StepAnalysisContext,\n  StepModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport type {\n  ResolveAncestorModel,\n  ResolveBlockModel,\n  ResolveModel,\n  ResolvePropertyModel,\n  StandaloneIterateModel,\n} from '../contracts/resolveModel.type'\n\n/**\n * Builds the analysis model for the resolve concern (the stage that prepares\n * data for rendering). Decides which authored properties are render-facing,\n * how ancestor journey paths compose, which blocks the step renders, and which\n * MAP iterators stand alone as block producers rather than property values.\n * All decisions happen here so `StepResolveCompiler` only turns model fields\n * into generated code.\n */\nexport default class ResolveAnalyzer implements StepModelAnalyzer<ResolveModel> {\n  /** Properties owned by other concerns (validation, hooks, etc.) — excluded from the render context. */\n  private static readonly BLOCK_SKIP_PROPS = new Set(['formatters', 'parsers', 'validWhen', 'dependentWhen'])\n\n  private static readonly STEP_SKIP_PROPS = new Set(['onAccess', 'onSubmission', 'blocks', 'reachability'])\n\n  private static readonly JOURNEY_SKIP_PROPS = new Set(['onAccess', 'children', 'steps', 'reachability'])\n\n  analyzeStep(context: StepAnalysisContext): ResolveModel {\n    const step = this.classifyProperties(\n      context,\n      context.stepNode.properties as Record<string, unknown>,\n      ResolveAnalyzer.STEP_SKIP_PROPS,\n    )\n    const ancestors = this.buildAncestors(context)\n    const blocks = (context.stepNode.properties.blocks ?? []).map(block => this.buildRegisteredBlock(context, block))\n    const inlineIterateIds = this.collectInlineIterateIds(step, ancestors, blocks)\n\n    return {\n      label: context.labels.labelFrom([context.stepNode]),\n      step,\n      ancestors,\n      blocks,\n      standaloneIterateBlocks: this.buildStandaloneIterateBlocks(context, inlineIterateIds),\n    }\n  }\n\n  private buildAncestors(context: StepAnalysisContext): ResolveAncestorModel[] {\n    const ancestorNodes = context.ancestry.ancestorsOfType(context.stepNode, isJourneyNode)\n    let runningPath: string | undefined = ''\n\n    return ancestorNodes.map(ancestorNode => {\n      const properties = this.classifyProperties(\n        context,\n        ancestorNode.properties as Record<string, unknown>,\n        ResolveAnalyzer.JOURNEY_SKIP_PROPS,\n      )\n      const ownPath = (ancestorNode.properties as Record<string, unknown>).path\n\n      // One dynamic segment poisons the rest of the chain: the generated code\n      // then composes every ancestor's path at request time, exactly as before.\n      runningPath =\n        runningPath !== undefined && typeof ownPath === 'string' ? composePath(runningPath, ownPath) : undefined\n\n      return { properties, composedPath: runningPath }\n    })\n  }\n\n  private buildRegisteredBlock(context: StepAnalysisContext, block: BlockASTNode): ResolveBlockModel {\n    const rawProperties = block.properties as Record<string, unknown>\n\n    return {\n      source: block,\n      id: block.id,\n      variant: block.variant,\n      blockType: block.blockType,\n      label: this.deriveBlockLabel(block),\n      properties: this.classifyProperties(context, rawProperties, ResolveAnalyzer.BLOCK_SKIP_PROPS),\n      resolvesFieldValue: block.blockType === BlockType.FIELD && rawProperties.value === undefined,\n    }\n  }\n\n  private buildTemplateBlock(context: StepAnalysisContext, block: TemplateNode): ResolveBlockModel {\n    const rawProperties = (block.properties ?? {}) as Record<string, unknown>\n    const blockType = String(block.blockType)\n\n    return {\n      source: block,\n      id: undefined,\n      variant: String(block.variant),\n      blockType,\n      label: String(block.variant),\n      properties: this.classifyProperties(context, rawProperties, ResolveAnalyzer.BLOCK_SKIP_PROPS),\n      resolvesFieldValue: blockType === BlockType.FIELD && rawProperties.value === undefined,\n    }\n  }\n\n  private buildStandaloneIterateBlocks(\n    context: StepAnalysisContext,\n    inlineIterateIds: ReadonlySet<string>,\n  ): StandaloneIterateModel[] {\n    return (\n      context.ownership\n        .allIterateNodesOf(context.stepNode.id)\n        .filter(iterateNode => !inlineIterateIds.has(iterateNode.id))\n        .filter(iterateNode => iterateNode.properties.iterator.type === IteratorType.MAP)\n        .flatMap(iterateNode => {\n          const template = iterateNode.properties.iterator.yieldTemplate\n\n          if (template === undefined) {\n            return []\n          }\n\n          const templateBlocks = this.findTemplateBlocks(template)\n\n          if (templateBlocks.length === 0) {\n            return []\n          }\n\n          return [\n            {\n              node: iterateNode,\n              templateBlocks: templateBlocks.map(templateBlock => this.buildTemplateBlock(context, templateBlock)),\n            },\n          ]\n        })\n    )\n  }\n\n  /**\n   * Classifies authored properties (the raw values journey authors write) into\n   * ordered render-facing entries. Drops the skipped properties (those owned by\n   * other concerns) and recursively removes them from nested block values too.\n   */\n  private classifyProperties(\n    context: StepAnalysisContext,\n    properties: Record<string, unknown>,\n    skipProps: ReadonlySet<string>,\n  ): ResolvePropertyModel[] {\n    return Object.entries(properties)\n      .filter(([key]) => !skipProps.has(key))\n      .map(([key, value]) => ({ key, value: this.pruneNestedBlockProps(context.classifier.classify(value)) }))\n  }\n\n  /** Recursively strips block-level skip properties from nested `BlockValue` branches. */\n  private pruneNestedBlockProps(value: AuthoredValue): AuthoredValue {\n    switch (value.kind) {\n      case AuthoredValueKind.BLOCK:\n        return {\n          ...value,\n          entries: value.entries\n            .filter(entry => !ResolveAnalyzer.BLOCK_SKIP_PROPS.has(entry.key))\n            .map(entry => ({ key: entry.key, value: this.pruneNestedBlockProps(entry.value) })),\n        }\n      case AuthoredValueKind.RECORD:\n        return {\n          ...value,\n          entries: value.entries.map(entry => ({ key: entry.key, value: this.pruneNestedBlockProps(entry.value) })),\n        }\n      case AuthoredValueKind.LIST:\n        return { ...value, items: value.items.map(item => this.pruneNestedBlockProps(item)) }\n      case AuthoredValueKind.CONDITIONAL:\n        return {\n          ...value,\n          predicate: this.pruneNestedBlockProps(value.predicate),\n          thenValue: this.pruneNestedBlockProps(value.thenValue),\n          elseValue: this.pruneNestedBlockProps(value.elseValue),\n        }\n      case AuthoredValueKind.MATCH:\n        return {\n          ...value,\n          subject: this.pruneNestedBlockProps(value.subject),\n          branches: value.branches.map(branch => ({\n            ...('expected' in branch\n              ? { expected: this.pruneNestedBlockProps(branch.expected) }\n              : { predicate: this.pruneNestedBlockProps(branch.predicate) }),\n            value: this.pruneNestedBlockProps(branch.value),\n          })),\n          otherwise: value.otherwise === undefined ? undefined : this.pruneNestedBlockProps(value.otherwise),\n        }\n      case AuthoredValueKind.ITERATION:\n        return {\n          ...value,\n          input: this.pruneNestedBlockProps(value.input),\n          yieldTemplate:\n            value.yieldTemplate === undefined ? undefined : this.pruneNestedBlockProps(value.yieldTemplate),\n          predicate: value.predicate === undefined ? undefined : this.pruneNestedBlockProps(value.predicate),\n        }\n      default:\n        return value\n    }\n  }\n\n  /**\n   * Iterators that appear inside a property value are \"inline\" — their loops\n   * are generated at the point the property is evaluated, so they must not\n   * also appear as standalone block producers.\n   */\n  private collectInlineIterateIds(\n    step: readonly ResolvePropertyModel[],\n    ancestors: readonly ResolveAncestorModel[],\n    blocks: readonly ResolveBlockModel[],\n  ): Set<string> {\n    const inlineIterateIds = new Set<string>()\n    const collectFrom = (properties: readonly ResolvePropertyModel[]) => {\n      properties.forEach(property => this.collectIterationIds(property.value, inlineIterateIds))\n    }\n\n    collectFrom(step)\n    ancestors.forEach(ancestor => collectFrom(ancestor.properties))\n    blocks.forEach(block => collectFrom(block.properties))\n\n    return inlineIterateIds\n  }\n\n  private collectIterationIds(value: AuthoredValue, ids: Set<string>): void {\n    switch (value.kind) {\n      case AuthoredValueKind.ITERATION:\n        ids.add(String((value.source as { id?: unknown }).id))\n        this.collectIterationIds(value.input, ids)\n\n        if (value.yieldTemplate !== undefined) {\n          this.collectIterationIds(value.yieldTemplate, ids)\n        }\n\n        if (value.predicate !== undefined) {\n          this.collectIterationIds(value.predicate, ids)\n        }\n\n        return\n      case AuthoredValueKind.CONDITIONAL:\n        this.collectIterationIds(value.predicate, ids)\n        this.collectIterationIds(value.thenValue, ids)\n        this.collectIterationIds(value.elseValue, ids)\n\n        return\n      case AuthoredValueKind.MATCH:\n        this.collectIterationIds(value.subject, ids)\n        value.branches.forEach(branch => {\n          this.collectIterationIds('expected' in branch ? branch.expected : branch.predicate, ids)\n          this.collectIterationIds(branch.value, ids)\n        })\n\n        if (value.otherwise !== undefined) {\n          this.collectIterationIds(value.otherwise, ids)\n        }\n\n        return\n      case AuthoredValueKind.RECORD:\n      case AuthoredValueKind.BLOCK:\n        value.entries.forEach(entry => this.collectIterationIds(entry.value, ids))\n\n        return\n      case AuthoredValueKind.LIST:\n        value.items.forEach(item => this.collectIterationIds(item, ids))\n\n        break\n      default:\n        break\n    }\n  }\n\n  /** Finds block nodes inside a standalone iterator's yield template, collecting only the outermost matches. */\n  private findTemplateBlocks(template: TemplateValue): TemplateNode[] {\n    const results: TemplateNode[] = []\n\n    this.walkTemplateForBlocks(template, results)\n\n    return results\n  }\n\n  private walkTemplateForBlocks(value: TemplateValue, results: TemplateNode[]): void {\n    if (value === null || value === undefined || typeof value !== 'object') {\n      return\n    }\n\n    if (isTemplateNode(value)) {\n      if (value.originalType === ASTNodeType.BLOCK) {\n        results.push(value)\n\n        return\n      }\n\n      Object.values(value.properties ?? {}).forEach(child => {\n        this.walkTemplateForBlocks(child as TemplateValue, results)\n      })\n\n      return\n    }\n\n    if (Array.isArray(value)) {\n      value.forEach(item => {\n        this.walkTemplateForBlocks(item, results)\n      })\n\n      return\n    }\n\n    Object.values(value).forEach(item => {\n      this.walkTemplateForBlocks(item as TemplateValue, results)\n    })\n  }\n\n  private deriveBlockLabel(block: BlockASTNode): string {\n    const pathTail = block.diagnostics?.source.formattedPath.split(' > ').at(-1)\n\n    return pathTail?.replace(/ \\(.*\\)$/, '') ?? String(block.id)\n  }\n}\n\nfunction isJourneyNode(node: ASTNode): node is JourneyASTNode {\n  return node.type === ASTNodeType.JOURNEY\n}\n\nfunction composePath(runningPath: string, ownPath: string): string {\n  return `/${`${runningPath}/${ownPath}`.split('/').filter(Boolean).join('/')}`\n}\n","import type { JourneyASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport type AuthoredValueClassifier from '../../../chassis/compilation/analysis/shared/AuthoredValueClassifier'\nimport type {\n  JourneyAnalysisContext,\n  JourneyModelAnalyzer,\n  StepAnalysisContext,\n  StepModelAnalyzer,\n} from '../../../chassis/compilation/analysis/concernAnalyzers.type'\nimport type { RouteMetadataModel } from '../contracts/routeMetadataModel.type'\n\n/**\n * Collects the authored route metadata (title/description/metadata) from a step\n * or journey node. Steps and journeys share the same metadata shape, so both\n * `analyzeStep` and `analyzeJourney` delegate to one builder. The package-level\n * route-metadata function later compiles every collected entry into one\n * generated function.\n */\nexport default class RouteAnalyzer\n  implements StepModelAnalyzer<RouteMetadataModel>, JourneyModelAnalyzer<RouteMetadataModel>\n{\n  analyzeStep(context: StepAnalysisContext): RouteMetadataModel {\n    return this.buildForNode(context.stepNode, context.classifier)\n  }\n\n  analyzeJourney(context: JourneyAnalysisContext): RouteMetadataModel {\n    return this.buildForNode(context.journeyNode, context.classifier)\n  }\n\n  private buildForNode(node: StepASTNode | JourneyASTNode, classifier: AuthoredValueClassifier): RouteMetadataModel {\n    return {\n      nodeId: node.id,\n      title: classifier.classify(node.properties.title),\n      description:\n        node.properties.description === undefined ? undefined : classifier.classify(node.properties.description),\n      metadata: node.properties.metadata === undefined ? undefined : classifier.classify(node.properties.metadata),\n    }\n  }\n}\n","import type { ASTNode, NodeId } from '../../contracts/ast/ast.type'\nimport { ASTNodeType } from '../../contracts/ast/enums'\nimport type { JourneyASTNode, StepASTNode } from '../../contracts/ast/structures.type'\nimport type { FieldModel } from '../../contracts/models/fieldModel.type'\nimport type { CompilationModel, JourneyModel, StepModel } from '../../contracts/models/compilationModel.type'\nimport type { RouteMetadataModel } from '../../../concerns/route/contracts/routeMetadataModel.type'\nimport type ASTNodeIndex from '../ast/ast-state/ASTNodeIndex'\nimport type { AnalysisRegistries, JourneyAnalysisContext, StepAnalysisContext } from './concernAnalyzers.type'\nimport Ancestry from './shared/Ancestry'\nimport AuthoredValueClassifier from './shared/AuthoredValueClassifier'\nimport FieldModelBuilder from './shared/FieldModelBuilder'\nimport NodeLabeller from './shared/NodeLabeller'\nimport OwnershipIndex from './shared/OwnershipIndex'\nimport MountInfoAnalyzer from './shared/MountInfoAnalyzer'\nimport ReachabilityAnalyzer from '../../../concerns/reachability/analysis/ReachabilityAnalyzer'\nimport AnswerCleardownAnalyzer from '../../../concerns/answer-cleardown/analysis/AnswerCleardownAnalyzer'\nimport AnswerPreparationAnalyzer from '../../../concerns/answer-preparation/analysis/AnswerPreparationAnalyzer'\nimport HookAnalyzer from '../../../concerns/hooks/analysis/HookAnalyzer'\nimport ValidationAnalyzer from '../../../concerns/validation/analysis/ValidationAnalyzer'\nimport ResolveAnalyzer from '../../../concerns/resolve/analysis/ResolveAnalyzer'\nimport RouteAnalyzer from '../../../concerns/route/analysis/RouteAnalyzer'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\ntype StepIndex = Map<NodeId, StepASTNode>\n\nexport default class CompilationModelBuilder {\n  private readonly ancestry = new Ancestry()\n\n  private readonly classifier = new AuthoredValueClassifier()\n\n  private readonly labels = new NodeLabeller()\n\n  private readonly ownershipIndex: OwnershipIndex\n\n  private readonly fieldModelBuilder: FieldModelBuilder\n\n  private readonly mountInfoAnalyzer: MountInfoAnalyzer\n\n  private readonly reachabilityAnalyzer = new ReachabilityAnalyzer()\n\n  private readonly answerCleardownAnalyzer = new AnswerCleardownAnalyzer()\n\n  private readonly answerPreparationAnalyzer = new AnswerPreparationAnalyzer()\n\n  private readonly hookAnalyzer = new HookAnalyzer()\n\n  private readonly validationAnalyzer = new ValidationAnalyzer()\n\n  private readonly resolveAnalyzer = new ResolveAnalyzer()\n\n  private readonly routeAnalyzer = new RouteAnalyzer()\n\n  constructor(\n    nodeIndex: ASTNodeIndex,\n    private readonly registries: AnalysisRegistries,\n  ) {\n    this.ownershipIndex = new OwnershipIndex(nodeIndex, this.ancestry)\n    this.fieldModelBuilder = new FieldModelBuilder(registries.componentRegistry)\n    this.mountInfoAnalyzer = new MountInfoAnalyzer(this.ancestry)\n  }\n\n  build(stepIndex: StepIndex): CompilationModel {\n    const routeMetadata = new Map<NodeId, RouteMetadataModel>()\n    const journeys = new Map<NodeId, JourneyModel>()\n    const stepFields = this.buildStepFields(stepIndex)\n\n    stepIndex.forEach((stepNode, stepId) => {\n      if (!this.isJourneyNode(stepNode.parent)) {\n        throw new ForgeInternalError(`Step \"${stepId}\" was not registered under a journey`)\n      }\n    })\n\n    // One walk covers every journey — including container-only journeys that\n    // have no steps — so route metadata is collected in the same pass and steps\n    // stay in document order (which the reachability state table depends on).\n    this.ownershipIndex.journeys().forEach(({ journeyNode, stepNodes }) => {\n      const journeyContext = this.createJourneyContext(journeyNode, stepNodes, stepFields)\n\n      journeys.set(journeyNode.id, this.buildJourneyModel(journeyContext, stepFields))\n      routeMetadata.set(journeyNode.id, this.routeAnalyzer.analyzeJourney(journeyContext))\n      stepNodes.forEach(stepNode => {\n        routeMetadata.set(stepNode.id, this.routeAnalyzer.analyzeStep(this.createStepContext(stepNode, stepFields)))\n      })\n    })\n\n    return { routeMetadata, journeys }\n  }\n\n  private buildStepFields(stepIndex: StepIndex): Map<NodeId, readonly FieldModel[]> {\n    const stepFields = new Map<NodeId, readonly FieldModel[]>()\n\n    ;[...stepIndex.keys()].forEach(stepId => {\n      stepFields.set(\n        stepId,\n        this.fieldModelBuilder.buildStepFields(\n          this.ownershipIndex.fieldBlocksOf(stepId),\n          this.ownershipIndex.mapIterateNodesOf(stepId),\n        ),\n      )\n    })\n\n    return stepFields\n  }\n\n  private buildJourneyModel(\n    context: JourneyAnalysisContext,\n    stepFields: Map<NodeId, readonly FieldModel[]>,\n  ): JourneyModel {\n    const steps = new Map<NodeId, StepModel>()\n\n    context.stepNodes.forEach(stepNode => {\n      steps.set(stepNode.id, this.buildStepModel(stepNode, stepFields))\n    })\n\n    const reachability = this.reachabilityAnalyzer.analyzeJourney(context)\n\n    return {\n      journeyId: context.journeyNode.id,\n      label: reachability.label,\n      mountInfo: this.mountInfoAnalyzer.buildJourneyMountInfo(context.journeyNode),\n      staticData: this.mountInfoAnalyzer.resolveStaticData(context.journeyNode),\n      hooks: this.hookAnalyzer.analyzeJourney(context),\n      reachability,\n      cleardown: this.answerCleardownAnalyzer.analyzeJourney(context),\n      answerPreparation: this.answerPreparationAnalyzer.analyzeJourney(context),\n      steps,\n    }\n  }\n\n  private buildStepModel(stepNode: StepASTNode, stepFields: Map<NodeId, readonly FieldModel[]>): StepModel {\n    const context = this.createStepContext(stepNode, stepFields)\n\n    return {\n      stepId: stepNode.id,\n      label: this.labels.labelFrom([stepNode]),\n      mountInfo: this.mountInfoAnalyzer.buildStepMountInfo(stepNode),\n      staticData: this.mountInfoAnalyzer.resolveStaticData(stepNode),\n      fields: context.fields,\n      answerPreparation: this.answerPreparationAnalyzer.analyzeStep(context),\n      hooks: this.hookAnalyzer.analyzeStep(context),\n      validation: this.validationAnalyzer.analyzeStep(context),\n      resolve: this.resolveAnalyzer.analyzeStep(context),\n    }\n  }\n\n  private createStepContext(\n    stepNode: StepASTNode,\n    stepFields: Map<NodeId, readonly FieldModel[]>,\n  ): StepAnalysisContext {\n    return {\n      stepNode,\n      ownership: this.ownershipIndex,\n      ancestry: this.ancestry,\n      registries: this.registries,\n      classifier: this.classifier,\n      fields: stepFields.get(stepNode.id) ?? [],\n      labels: this.labels,\n    }\n  }\n\n  private createJourneyContext(\n    journeyNode: JourneyASTNode,\n    stepNodes: readonly StepASTNode[],\n    stepFields: Map<NodeId, readonly FieldModel[]>,\n  ): JourneyAnalysisContext {\n    return {\n      journeyNode,\n      stepNodes,\n      ownership: this.ownershipIndex,\n      ancestry: this.ancestry,\n      registries: this.registries,\n      classifier: this.classifier,\n      labels: this.labels,\n      stepFields,\n    }\n  }\n\n  private isJourneyNode(node: ASTNode | undefined): node is JourneyASTNode {\n    return node?.type === ASTNodeType.JOURNEY\n  }\n}\n","import type { WorkContextContract, WorkHandler } from '../../contracts/work/work.type'\nimport { createWorkTask } from '../../work/workTask'\nimport type { StepASTNode } from '../../contracts/ast/structures.type'\nimport { ASTNodeType } from '../../contracts/ast/enums'\nimport type CompilationState from '../pipeline/CompilationState'\nimport CompilationModelBuilder from './CompilationModelBuilder'\n\nexport const COMPILATION_ANALYSIS_WORK_HANDLER: WorkHandler<'compilation.analysis', undefined> = {\n  kind: 'compilation.analysis',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n    const stepNodes = state.ast.nodeIndex.findByType<StepASTNode>(ASTNodeType.STEP)\n    const stepIndex = new Map(stepNodes.map(stepNode => [stepNode.id, stepNode]))\n\n    const modelBuilder = new CompilationModelBuilder(state.ast.nodeIndex, {\n      componentRegistry: state.dependencies.componentRegistry,\n      functionRegistry: state.dependencies.functionRegistry,\n    })\n\n    state.recordModel(modelBuilder.build(stepIndex))\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationAnalysisTask() {\n  return createWorkTask('analysis', COMPILATION_ANALYSIS_WORK_HANDLER, undefined)\n}\n","import type { CodeFragment } from './CodeFragment'\n\n/** Holds a generated array literal as separate `CodeFragment` elements, so `SourceRenderer` can format it across multiple lines if needed. */\nexport default class ArrayExpressionToken {\n  private readonly arrayValues: readonly CodeFragment[]\n\n  constructor(values: readonly CodeFragment[]) {\n    this.arrayValues = Object.freeze([...values])\n    Object.freeze(this)\n  }\n\n  get values(): readonly CodeFragment[] {\n    return this.arrayValues\n  }\n}\n","import type { CodeFragment } from './CodeFragment'\n\n/** Holds a generated function call as a target and separate arguments, so `SourceRenderer` can break long calls across multiple lines. */\nexport default class CallExpressionToken {\n  private readonly callArguments: readonly CodeFragment[]\n\n  constructor(\n    private readonly callTarget: CodeFragment,\n    args: readonly CodeFragment[],\n  ) {\n    this.callArguments = Object.freeze([...args])\n    Object.freeze(this)\n  }\n\n  get target(): CodeFragment {\n    return this.callTarget\n  }\n\n  get args(): readonly CodeFragment[] {\n    return this.callArguments\n  }\n}\n","import ForgeInternalError from '../../../../../errors/ForgeInternalError'\n\n/** A validated JavaScript identifier, safe to interpolate as executable code. */\nexport default class IdentifierName {\n  constructor(private readonly identifier: string) {\n    if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier) || FORBIDDEN_BINDING_NAMES.has(identifier)) {\n      throw new ForgeInternalError(`Code: \"${identifier}\" is not a valid JavaScript identifier`)\n    }\n  }\n\n  get value(): string {\n    return this.identifier\n  }\n}\n\nconst FORBIDDEN_BINDING_NAMES = new Set([\n  'arguments',\n  'await',\n  'break',\n  'case',\n  'catch',\n  'class',\n  'const',\n  'continue',\n  'debugger',\n  'default',\n  'delete',\n  'do',\n  'else',\n  'enum',\n  'eval',\n  'export',\n  'extends',\n  'false',\n  'finally',\n  'for',\n  'function',\n  'if',\n  'implements',\n  'import',\n  'in',\n  'instanceof',\n  'interface',\n  'let',\n  'new',\n  'null',\n  'package',\n  'private',\n  'protected',\n  'public',\n  'return',\n  'static',\n  'super',\n  'switch',\n  'this',\n  'throw',\n  'true',\n  'try',\n  'typeof',\n  'var',\n  'void',\n  'while',\n  'with',\n  'yield',\n])\n","import type { CodeFragment } from './CodeFragment'\n\nexport interface ObjectExpressionProperty {\n  readonly key: CodeFragment\n  readonly value: CodeFragment\n}\n\n/** Holds a generated object literal as separate key-value pairs, so `SourceRenderer` can format it across multiple lines if needed. */\nexport default class ObjectExpressionToken {\n  private readonly objectProperties: readonly ObjectExpressionProperty[]\n\n  constructor(properties: readonly ObjectExpressionProperty[]) {\n    this.objectProperties = Object.freeze(properties.map(property => Object.freeze({ ...property })))\n    Object.freeze(this)\n  }\n\n  get properties(): readonly ObjectExpressionProperty[] {\n    return this.objectProperties\n  }\n}\n","import { CodeFragment } from './CodeFragment'\nimport { SourcePosition } from '../SourcePosition.type'\n\n/** Pairs a `CodeFragment` fragment with source positions (file/line/column from the authored definition), so source maps can trace generated code back to the definition that produced it. */\nexport default class PositionedCodeToken {\n  private readonly sourcePositions: readonly SourcePosition[]\n\n  constructor(\n    private readonly sourceCode: CodeFragment,\n    positions: readonly SourcePosition[],\n  ) {\n    this.sourcePositions = Object.freeze([...positions])\n    Object.freeze(this)\n  }\n\n  get value(): CodeFragment {\n    return this.sourceCode\n  }\n\n  get positions(): readonly SourcePosition[] {\n    return this.sourcePositions\n  }\n}\n","import ForgeInternalError from '../../../../../errors/ForgeInternalError'\nimport ArrayExpressionToken from './ArrayExpressionToken'\nimport CallExpressionToken from './CallExpressionToken'\nimport FunctionExpressionToken from './FunctionExpressionToken'\nimport IdentifierName from './IdentifierName'\nimport ObjectExpressionToken from './ObjectExpressionToken'\nimport PositionedCodeToken from './PositionedCodeToken'\nimport { SourcePosition } from '../SourcePosition.type'\n\nexport type CodeItem =\n  | string\n  | ArrayExpressionToken\n  | CallExpressionToken\n  | FunctionExpressionToken\n  | ObjectExpressionToken\n  | PositionedCodeToken\n\nexport type SafeCode = CodeFragment | IdentifierName\n\nexport type CodeInterpolation = SafeCode | string | number | boolean | null | undefined\n\nexport interface ObjectCodeProperty {\n  readonly key: string\n  readonly value: SafeCode\n}\n\n/**\n * A fragment of trusted JavaScript source.\n *\n * Use `code` to compose fragments: interpolated CodeFragment values remain executable,\n * while ordinary JavaScript values are emitted as literals.\n */\nexport class CodeFragment {\n  private constructor(private readonly codeItems: readonly CodeItem[]) {\n    this.codeItems = Object.freeze([...codeItems])\n  }\n\n  static trusted(source: string): CodeFragment {\n    return new CodeFragment([source])\n  }\n\n  static compose(strings: TemplateStringsArray, values: readonly CodeInterpolation[]): CodeFragment {\n    const items: CodeItem[] = []\n\n    strings.forEach((part, index) => {\n      items.push(part)\n\n      if (index >= values.length) {\n        return\n      }\n\n      items.push(...CodeFragment.fromInterpolation(values[index]).items)\n    })\n\n    return new CodeFragment(items)\n  }\n\n  static literal(value: unknown): CodeFragment {\n    if (value === undefined) {\n      return CodeFragment.trusted('undefined')\n    }\n\n    const serialised = JSON.stringify(value)\n\n    if (serialised === undefined) {\n      throw new ForgeInternalError(`CodeFragment: value of type \"${typeof value}\" cannot be emitted as a literal`)\n    }\n\n    return CodeFragment.trusted(serialised.replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029'))\n  }\n\n  static join(values: readonly SafeCode[], separator: CodeFragment): CodeFragment {\n    const items: CodeItem[] = []\n\n    values.forEach((value, index) => {\n      if (index > 0) {\n        items.push(...separator.items)\n      }\n\n      items.push(...CodeFragment.fromSafeCode(value).items)\n    })\n\n    return new CodeFragment(items)\n  }\n\n  static positioned(value: CodeFragment, positions: readonly SourcePosition[]): CodeFragment {\n    return positions.length === 0 ? value : new CodeFragment([new PositionedCodeToken(value, positions)])\n  }\n\n  static functionExpression(token: FunctionExpressionToken): CodeFragment {\n    return new CodeFragment([token])\n  }\n\n  static call(target: SafeCode, args: readonly SafeCode[]): CodeFragment {\n    return new CodeFragment([\n      new CallExpressionToken(\n        CodeFragment.fromSafeCode(target),\n        args.map(arg => CodeFragment.fromSafeCode(arg)),\n      ),\n    ])\n  }\n\n  static array(values: readonly SafeCode[]): CodeFragment {\n    return new CodeFragment([new ArrayExpressionToken(values.map(value => CodeFragment.fromSafeCode(value)))])\n  }\n\n  static object(properties: readonly ObjectCodeProperty[]): CodeFragment {\n    return new CodeFragment([\n      new ObjectExpressionToken(\n        properties.map(property => ({\n          key: CodeFragment.objectKey(property.key),\n          value: CodeFragment.fromSafeCode(property.value),\n        })),\n      ),\n    ])\n  }\n\n  /**\n   * Emits a deeply static value as a structured literal: plain objects and\n   * arrays become expression tokens (so the renderer can format them across\n   * lines), everything else is serialised by `literal`. Matches\n   * `JSON.stringify` semantics for unserialisable values: object entries are\n   * dropped, array items become `null`.\n   */\n  static structuredLiteral(value: unknown): CodeFragment {\n    if (Array.isArray(value)) {\n      return CodeFragment.array(\n        value.map(item => (isSerialisable(item) ? CodeFragment.structuredLiteral(item) : CodeFragment.literal(null))),\n      )\n    }\n\n    if (isPlainObject(value)) {\n      return new CodeFragment([\n        new ObjectExpressionToken(\n          Object.entries(value)\n            .filter(([, entryValue]) => isSerialisable(entryValue))\n            .map(([key, entryValue]) => ({\n              key: CodeFragment.objectKey(key),\n              value: CodeFragment.structuredLiteral(entryValue),\n            })),\n        ),\n      ])\n    }\n\n    return CodeFragment.literal(value)\n  }\n\n  private static objectKey(key: string): CodeFragment {\n    return isIdentifier(key) ? CodeFragment.trusted(key) : CodeFragment.literal(key)\n  }\n\n  get items(): readonly CodeItem[] {\n    return this.codeItems\n  }\n\n  get isEmpty(): boolean {\n    return this.codeItems.length === 0\n  }\n\n  /**\n   * True when the fragment contains a structured call or function-expression\n   * token. A fragment without either is a plain read (property chains,\n   * literals, arithmetic) that cannot invoke authored code.\n   */\n  get containsInvocation(): boolean {\n    return this.codeItems.some(item => {\n      if (typeof item === 'string') {\n        return false\n      }\n\n      if (item instanceof PositionedCodeToken) {\n        return item.value.containsInvocation\n      }\n\n      if (item instanceof ArrayExpressionToken) {\n        return item.values.some(value => value.containsInvocation)\n      }\n\n      if (item instanceof ObjectExpressionToken) {\n        return item.properties.some(property => property.value.containsInvocation)\n      }\n\n      return true\n    })\n  }\n\n  toString(): string {\n    return (\n      this.codeItems\n        .map(item => {\n          if (typeof item === 'string') {\n            return item\n          }\n\n          if (item instanceof PositionedCodeToken) {\n            return item.value.toString()\n          }\n\n          if (item instanceof ArrayExpressionToken) {\n            return `[${item.values.map(value => value.toString()).join(', ')}]`\n          }\n\n          if (item instanceof CallExpressionToken) {\n            return `${item.target.toString()}(${item.args.map(arg => arg.toString()).join(', ')})`\n          }\n\n          if (item instanceof ObjectExpressionToken) {\n            const properties = item.properties.map(\n              property => `${property.key.toString()}: ${property.value.toString()}`,\n            )\n\n            return properties.length === 0 ? '{}' : `{ ${properties.join(', ')} }`\n          }\n\n          throw new ForgeInternalError(\n            'CodeFragment: structured function expressions must be rendered by SourceRenderer',\n          )\n        })\n        .join('')\n    )\n  }\n\n  private static fromInterpolation(value: CodeInterpolation): CodeFragment {\n    if (value instanceof CodeFragment || value instanceof IdentifierName) {\n      return CodeFragment.fromSafeCode(value)\n    }\n\n    return CodeFragment.literal(value)\n  }\n\n  private static fromSafeCode(value: SafeCode): CodeFragment {\n    return value instanceof CodeFragment ? value : CodeFragment.trusted(value.value)\n  }\n}\n\nexport const nil = CodeFragment.trusted('')\n\n/**\n * Safely composes JavaScript source. Only CodeFragment and IdentifierName values are executable;\n * every other interpolation is encoded as a JavaScript literal.\n */\nexport const code = (strings: TemplateStringsArray, ...values: CodeInterpolation[]): CodeFragment =>\n  CodeFragment.compose(strings, values)\n\nexport const literal = (value: unknown): CodeFragment => CodeFragment.literal(value)\n\nexport const callCode = (target: SafeCode, args: readonly SafeCode[]): CodeFragment => CodeFragment.call(target, args)\n\nexport const joinCode = (values: readonly SafeCode[], separator: CodeFragment = code`, `): CodeFragment =>\n  CodeFragment.join(values, separator)\n\nexport const propertyCode = (property: string): CodeFragment => {\n  if (isIdentifier(property)) {\n    return CodeFragment.trusted(`.${property}`)\n  }\n\n  return code`[${property}]`\n}\n\nexport const optionalPropertyCode = (property: string): CodeFragment => {\n  if (isIdentifier(property)) {\n    return CodeFragment.trusted(`?.${property}`)\n  }\n\n  return code`?.[${property}]`\n}\n\nexport const positionedCode = (value: CodeFragment, positions: readonly SourcePosition[]): CodeFragment =>\n  CodeFragment.positioned(value, positions)\n\nexport const arrayCode = (values: readonly SafeCode[]): CodeFragment => CodeFragment.array(values)\n\nexport const objectCode = (properties: readonly ObjectCodeProperty[]): CodeFragment => CodeFragment.object(properties)\n\nexport const structuredLiteralCode = (value: unknown): CodeFragment => CodeFragment.structuredLiteral(value)\n\nconst isIdentifier = (value: string): boolean => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value)\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const prototype = Object.getPrototypeOf(value) as unknown\n\n  return prototype === Object.prototype || prototype === null\n}\n\nconst isSerialisable = (value: unknown): boolean =>\n  value !== undefined && typeof value !== 'function' && typeof value !== 'symbol'\n","export default abstract class CodeNode {}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport default class AssignmentCodeNode extends CodeNode {\n  constructor(\n    private readonly assignmentTarget: SafeCode,\n    private readonly assignmentValue: SafeCode,\n  ) {\n    super()\n  }\n\n  get target(): SafeCode {\n    return this.assignmentTarget\n  }\n\n  get value(): SafeCode {\n    return this.assignmentValue\n  }\n}\n","import CodeNode from './CodeNode'\n\nexport default class BlankLineCodeNode extends CodeNode {}\n","import CodeNode from './CodeNode'\n\nexport default class BreakCodeNode extends CodeNode {}\n","import CodeNode from './CodeNode'\n\nexport default class CommentCodeNode extends CodeNode {\n  constructor(\n    private readonly commentText: string,\n    private readonly bannerComment: boolean,\n  ) {\n    super()\n  }\n\n  get text(): string {\n    return this.commentText\n  }\n\n  get banner(): boolean {\n    return this.bannerComment\n  }\n}\n","import CodeNode from './CodeNode'\n\nexport default class ContinueCodeNode extends CodeNode {}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\nimport IdentifierName from '../fragments/IdentifierName'\n\nexport enum DeclarationKind {\n  CONST = 'const',\n  LET = 'let',\n  VAR = 'var',\n}\n\nexport default class DeclarationCodeNode extends CodeNode {\n  constructor(\n    private readonly declaration: DeclarationKind,\n    private readonly declarationName: IdentifierName,\n    private readonly declarationValue?: SafeCode,\n  ) {\n    super()\n  }\n\n  get declarationKind(): DeclarationKind {\n    return this.declaration\n  }\n\n  get name(): IdentifierName {\n    return this.declarationName\n  }\n\n  get value(): SafeCode | undefined {\n    return this.declarationValue\n  }\n}\n","import CodeNode from './CodeNode'\n\nexport default class DirectiveCodeNode extends CodeNode {\n  constructor(private readonly directiveValue: string) {\n    super()\n  }\n\n  get value(): string {\n    return this.directiveValue\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport default class ExpressionCodeNode extends CodeNode {\n  constructor(private readonly sourceExpression: SafeCode) {\n    super()\n  }\n\n  get expression(): SafeCode {\n    return this.sourceExpression\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\nimport IdentifierName from '../fragments/IdentifierName'\n\nexport default class ForRangeCodeNode extends CodeNode {\n  constructor(\n    private readonly indexName: IdentifierName,\n    private readonly start: SafeCode,\n    private readonly end: SafeCode,\n    private readonly loopBody: CodeNode[],\n  ) {\n    super()\n  }\n\n  get index(): IdentifierName {\n    return this.indexName\n  }\n\n  get from(): SafeCode {\n    return this.start\n  }\n\n  get to(): SafeCode {\n    return this.end\n  }\n\n  get body(): readonly CodeNode[] {\n    return this.loopBody\n  }\n}\n","import CodeNode from './CodeNode'\nimport IdentifierName from '../fragments/IdentifierName'\n\nexport default class FunctionCodeNode extends CodeNode {\n  constructor(\n    private readonly functionName: IdentifierName,\n    private readonly functionParameters: readonly IdentifierName[],\n    private readonly functionBody: CodeNode[],\n    private readonly asyncFunction: boolean,\n  ) {\n    super()\n  }\n\n  get name(): IdentifierName {\n    return this.functionName\n  }\n\n  get parameters(): readonly IdentifierName[] {\n    return this.functionParameters\n  }\n\n  get body(): readonly CodeNode[] {\n    return this.functionBody\n  }\n\n  get async(): boolean {\n    return this.asyncFunction\n  }\n}\n","import CodeNode from '../statements/CodeNode'\nimport IdentifierName from './IdentifierName'\n\nexport default class FunctionExpressionToken {\n  constructor(\n    private readonly functionName: IdentifierName | undefined,\n    private readonly functionParameters: readonly IdentifierName[],\n    private readonly functionBody: readonly CodeNode[],\n    private readonly asyncFunction: boolean,\n  ) {}\n\n  get name(): IdentifierName | undefined {\n    return this.functionName\n  }\n\n  get parameters(): readonly IdentifierName[] {\n    return this.functionParameters\n  }\n\n  get body(): readonly CodeNode[] {\n    return this.functionBody\n  }\n\n  get async(): boolean {\n    return this.asyncFunction\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport interface IfCodeBranch {\n  readonly condition: SafeCode\n  readonly body: CodeNode[]\n}\n\nexport default class IfCodeNode extends CodeNode {\n  constructor(\n    private readonly ifBranches: readonly IfCodeBranch[],\n    private readonly fallbackBody?: CodeNode[],\n  ) {\n    super()\n  }\n\n  get branches(): readonly IfCodeBranch[] {\n    return this.ifBranches\n  }\n\n  get elseBody(): readonly CodeNode[] | undefined {\n    return this.fallbackBody\n  }\n}\n","import CodeNode from './CodeNode'\nimport { SourcePosition } from '../SourcePosition.type'\n\nexport default class PositionedCodeNode extends CodeNode {\n  private readonly authoredPositions: readonly SourcePosition[]\n\n  constructor(\n    private readonly positionedNode: CodeNode,\n    positions: readonly SourcePosition[],\n  ) {\n    super()\n\n    this.authoredPositions = Object.freeze(positions.map(position => Object.freeze({ ...position })))\n  }\n\n  get node(): CodeNode {\n    return this.positionedNode\n  }\n\n  get positions(): readonly SourcePosition[] {\n    return this.authoredPositions\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport default class ReturnCodeNode extends CodeNode {\n  constructor(private readonly returnValue?: SafeCode) {\n    super()\n  }\n\n  get value(): SafeCode | undefined {\n    return this.returnValue\n  }\n}\n","import CodeNode from './CodeNode'\n\nexport default class ScopeCodeNode extends CodeNode {\n  constructor(private readonly scopeBody: CodeNode[]) {\n    super()\n  }\n\n  get body(): readonly CodeNode[] {\n    return this.scopeBody\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport default class ThrowCodeNode extends CodeNode {\n  constructor(private readonly thrownValue: SafeCode) {\n    super()\n  }\n\n  get value(): SafeCode {\n    return this.thrownValue\n  }\n}\n","import CodeNode from './CodeNode'\nimport IdentifierName from '../fragments/IdentifierName'\n\nexport default class TryCatchCodeNode extends CodeNode {\n  constructor(\n    private readonly attemptedBody: CodeNode[],\n    private readonly caughtErrorName: IdentifierName,\n    private readonly recoveryBody: CodeNode[],\n  ) {\n    super()\n  }\n\n  get tryBody(): readonly CodeNode[] {\n    return this.attemptedBody\n  }\n\n  get errorName(): IdentifierName {\n    return this.caughtErrorName\n  }\n\n  get catchBody(): readonly CodeNode[] {\n    return this.recoveryBody\n  }\n}\n","import { SafeCode } from '../fragments/CodeFragment'\nimport CodeNode from './CodeNode'\n\nexport default class WhileCodeNode extends CodeNode {\n  constructor(\n    private readonly loopCondition: SafeCode,\n    private readonly loopBody: CodeNode[],\n  ) {\n    super()\n  }\n\n  get condition(): SafeCode {\n    return this.loopCondition\n  }\n\n  get body(): readonly CodeNode[] {\n    return this.loopBody\n  }\n}\n","import ForgeInternalError from '../../../../errors/ForgeInternalError'\nimport AssignmentCodeNode from './statements/AssignmentCodeNode'\nimport BlankLineCodeNode from './statements/BlankLineCodeNode'\nimport BreakCodeNode from './statements/BreakCodeNode'\nimport { CodeFragment, SafeCode } from './fragments/CodeFragment'\nimport CommentCodeNode from './statements/CommentCodeNode'\nimport ContinueCodeNode from './statements/ContinueCodeNode'\nimport DeclarationCodeNode, { DeclarationKind } from './statements/DeclarationCodeNode'\nimport DirectiveCodeNode from './statements/DirectiveCodeNode'\nimport ExpressionCodeNode from './statements/ExpressionCodeNode'\nimport ForRangeCodeNode from './statements/ForRangeCodeNode'\nimport FunctionCodeNode from './statements/FunctionCodeNode'\nimport FunctionExpressionToken from './fragments/FunctionExpressionToken'\nimport CodeNode from './statements/CodeNode'\nimport IfCodeNode, { IfCodeBranch } from './statements/IfCodeNode'\nimport IdentifierName from './fragments/IdentifierName'\nimport PositionedCodeNode from './statements/PositionedCodeNode'\nimport ReturnCodeNode from './statements/ReturnCodeNode'\nimport ScopeCodeNode from './statements/ScopeCodeNode'\nimport { SourcePosition } from './SourcePosition.type'\nimport ThrowCodeNode from './statements/ThrowCodeNode'\nimport TryCatchCodeNode from './statements/TryCatchCodeNode'\nimport WhileCodeNode from './statements/WhileCodeNode'\n\ninterface ScopeFrame {\n  readonly names: Set<string>\n}\n\ninterface NodeFrame {\n  readonly body: CodeNode[]\n}\n\nexport interface CodeGeneratorIfBranch {\n  readonly condition: SafeCode\n  readonly body: () => void\n}\n\nexport interface FunctionOptions {\n  readonly async?: boolean | (() => boolean)\n}\n\n/** Builds a tree of code nodes (statements, declarations, control flow)\n * that `SourceRenderer` later prints as JavaScript. Tracks variable names\n * and lexical scopes to avoid collisions in the generated output. */\nexport default class CodeGenerator {\n  private readonly rootNodes: CodeNode[] = []\n\n  private readonly nodeFrames: NodeFrame[] = [{ body: this.rootNodes }]\n\n  private readonly functionNames: Set<string>\n\n  private readonly scopeStack: ScopeFrame[]\n\n  private variableCounter: number\n\n  private readonly inheritedNames: ReadonlySet<string>\n\n  constructor(\n    variableCounter = 0,\n    functionNames: Set<string> = new Set(),\n    scopeStack: ScopeFrame[] = [createScopeFrame()],\n    inheritedNames: ReadonlySet<string> = new Set(),\n  ) {\n    this.variableCounter = variableCounter\n    this.functionNames = functionNames\n    this.scopeStack = scopeStack\n    this.inheritedNames = inheritedNames\n  }\n\n  static forFunction(parameterPrefixes: readonly string[]): CodeGenerator {\n    const parameters = parameterPrefixes.map(parameter => new IdentifierName(parameter))\n    const parameterNames = new Set(parameters.map(parameter => parameter.value))\n\n    return new CodeGenerator(0, parameterNames, [createScopeFrame(parameterNames)])\n  }\n\n  fork(): CodeGenerator {\n    return new CodeGenerator(\n      this.variableCounter,\n      new Set(this.functionNames),\n      this.scopeStack.map(frame => createScopeFrame(frame.names)),\n      this.inheritedNames,\n    )\n  }\n\n  syncVariablesFrom(other: CodeGenerator): void {\n    this.variableCounter = Math.max(this.variableCounter, other.variableCounter)\n  }\n\n  nextName(prefix = '_value'): IdentifierName {\n    return new IdentifierName(`${prefix}${this.variableCounter++}`)\n  }\n\n  directive(value: string): void {\n    this.currentBody.push(new DirectiveCodeNode(value))\n  }\n\n  var(prefix: string, value?: SafeCode): IdentifierName {\n    const name = this.allocateFunctionName(prefix)\n\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.VAR, name, value))\n\n    return name\n  }\n\n  declareVar(name: IdentifierName, value?: SafeCode): void {\n    if (this.inheritedNames.has(name.value)) {\n      throw new ForgeInternalError(`CodeGenerator: name \"${name.value}\" is already declared in an enclosing function`)\n    }\n\n    this.reserveFunctionName(name)\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.VAR, name, value))\n  }\n\n  let(prefix: string, value?: SafeCode): IdentifierName {\n    const name = this.allocateLexicalName(prefix)\n\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.LET, name, value))\n\n    return name\n  }\n\n  declareLet(name: IdentifierName, value?: SafeCode): void {\n    this.reserveLexicalName(name)\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.LET, name, value))\n  }\n\n  const(prefix: string, value: SafeCode): IdentifierName {\n    const name = this.allocateLexicalName(prefix)\n\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.CONST, name, value))\n\n    return name\n  }\n\n  declareConst(name: IdentifierName, value: SafeCode): void {\n    this.reserveLexicalName(name)\n    this.currentBody.push(new DeclarationCodeNode(DeclarationKind.CONST, name, value))\n  }\n\n  assign(target: SafeCode, value: SafeCode): void {\n    this.currentBody.push(new AssignmentCodeNode(target, value))\n  }\n\n  statement(expression: SafeCode): void {\n    this.currentBody.push(new ExpressionCodeNode(expression))\n  }\n\n  return(value?: SafeCode): void {\n    this.currentBody.push(new ReturnCodeNode(value))\n  }\n\n  throw(value: SafeCode): void {\n    this.currentBody.push(new ThrowCodeNode(value))\n  }\n\n  break(): void {\n    this.currentBody.push(new BreakCodeNode())\n  }\n\n  continue(): void {\n    this.currentBody.push(new ContinueCodeNode())\n  }\n\n  if(condition: SafeCode, thenBody: () => void, elseBody?: () => void): void {\n    this.ifChain([{ condition, body: thenBody }], elseBody)\n  }\n\n  ifChain(branches: readonly CodeGeneratorIfBranch[], elseBody?: () => void): void {\n    if (branches.length === 0) {\n      elseBody?.()\n\n      return\n    }\n\n    const compiledBranches: IfCodeBranch[] = branches.map(branch => ({\n      condition: branch.condition,\n      body: this.captureLexicalBody(branch.body),\n    }))\n    const compiledElseBody = elseBody === undefined ? undefined : this.captureLexicalBody(elseBody)\n\n    this.currentBody.push(new IfCodeNode(compiledBranches, compiledElseBody))\n  }\n\n  scope(body: () => void): void {\n    this.currentBody.push(new ScopeCodeNode(this.captureLexicalBody(body)))\n  }\n\n  while(condition: SafeCode, body: () => void): void {\n    this.currentBody.push(new WhileCodeNode(condition, this.captureLexicalBody(body)))\n  }\n\n  forRange(prefix: string, from: SafeCode, to: SafeCode, body: (index: IdentifierName) => void): IdentifierName {\n    const loopBody: CodeNode[] = []\n\n    this.scopeStack.push(createScopeFrame())\n    this.nodeFrames.push({ body: loopBody })\n\n    const index = this.allocateLexicalName(prefix)\n\n    try {\n      body(index)\n    } finally {\n      this.nodeFrames.pop()\n      this.scopeStack.pop()\n    }\n\n    this.currentBody.push(new ForRangeCodeNode(index, from, to, loopBody))\n\n    return index\n  }\n\n  tryCatch(tryBody: () => void, catchPrefix: string, catchBody: (error: IdentifierName) => void): IdentifierName {\n    const compiledTryBody = this.captureLexicalBody(tryBody)\n    const compiledCatchBody: CodeNode[] = []\n\n    this.scopeStack.push(createScopeFrame())\n    this.nodeFrames.push({ body: compiledCatchBody })\n\n    const error = this.allocateLexicalName(catchPrefix)\n\n    try {\n      catchBody(error)\n    } finally {\n      this.nodeFrames.pop()\n      this.scopeStack.pop()\n    }\n\n    this.currentBody.push(new TryCatchCodeNode(compiledTryBody, error, compiledCatchBody))\n\n    return error\n  }\n\n  function(\n    prefix: string,\n    parameterPrefixes: readonly string[],\n    buildBody: (generator: CodeGenerator, parameters: readonly IdentifierName[]) => void,\n    options: FunctionOptions = {},\n  ): IdentifierName {\n    const name = this.allocateLexicalName(prefix)\n    const functionGenerator = new CodeGenerator(\n      this.variableCounter,\n      new Set(),\n      [createScopeFrame()],\n      this.namesVisibleHere(),\n    )\n    const parameters = parameterPrefixes.map(parameter => new IdentifierName(parameter))\n\n    parameters.forEach(parameter => functionGenerator.reserveFunctionName(parameter))\n    buildBody(functionGenerator, parameters)\n    this.syncVariablesFrom(functionGenerator)\n    const asyncFunction = resolveAsyncOption(options)\n    this.currentBody.push(new FunctionCodeNode(name, parameters, [...functionGenerator.toNodes()], asyncFunction))\n\n    return name\n  }\n\n  functionExpression(\n    prefix: string | undefined,\n    parameterPrefixes: readonly string[],\n    buildBody: (generator: CodeGenerator, parameters: readonly IdentifierName[]) => void,\n    options: FunctionOptions = {},\n  ): CodeFragment {\n    const name = prefix === undefined ? undefined : this.allocateFunctionName(prefix)\n    const functionGenerator = new CodeGenerator(\n      this.variableCounter,\n      new Set(),\n      [createScopeFrame()],\n      this.namesVisibleHere(),\n    )\n    const parameters = parameterPrefixes.map(parameter => new IdentifierName(parameter))\n\n    parameters.forEach(parameter => functionGenerator.reserveFunctionName(parameter))\n    buildBody(functionGenerator, parameters)\n    this.syncVariablesFrom(functionGenerator)\n    const asyncFunction = resolveAsyncOption(options)\n\n    return CodeFragment.functionExpression(\n      new FunctionExpressionToken(name, parameters, [...functionGenerator.toNodes()], asyncFunction),\n    )\n  }\n\n  withSourcePositions(positions: readonly SourcePosition[], buildNodes: () => void): void {\n    const nodes: CodeNode[] = []\n\n    this.nodeFrames.push({ body: nodes })\n\n    try {\n      buildNodes()\n    } finally {\n      this.nodeFrames.pop()\n    }\n\n    nodes.forEach(node => this.currentBody.push(new PositionedCodeNode(node, positions)))\n  }\n\n  note(text: string): void {\n    splitCommentLines(text).forEach(line => this.currentBody.push(new CommentCodeNode(line, false)))\n  }\n\n  comment(text: string): void {\n    const previousNode = this.currentBody[this.currentBody.length - 1]\n\n    if (previousNode !== undefined && !(previousNode instanceof BlankLineCodeNode)) {\n      this.blank()\n    }\n\n    splitCommentLines(text).forEach(line => this.currentBody.push(new CommentCodeNode(line, true)))\n  }\n\n  blank(): void {\n    this.currentBody.push(new BlankLineCodeNode())\n  }\n\n  toNodes(): readonly CodeNode[] {\n    return this.rootNodes\n  }\n\n  private captureLexicalBody(body: () => void): CodeNode[] {\n    const nodes: CodeNode[] = []\n\n    this.scopeStack.push(createScopeFrame())\n    this.nodeFrames.push({ body: nodes })\n\n    try {\n      body()\n    } finally {\n      this.nodeFrames.pop()\n      this.scopeStack.pop()\n    }\n\n    return nodes\n  }\n\n  private allocateLexicalName(prefix: string): IdentifierName {\n    return this.allocateName(\n      prefix,\n      name => this.isNameVisible(name) || this.inheritedNames.has(name),\n      name => this.currentScope.names.add(name),\n    )\n  }\n\n  private allocateFunctionName(prefix: string): IdentifierName {\n    return this.allocateName(\n      prefix,\n      name => this.isNameVisible(name) || this.inheritedNames.has(name),\n      name => {\n        this.functionNames.add(name)\n        this.rootScope.names.add(name)\n      },\n    )\n  }\n\n  private allocateName(\n    prefix: string,\n    isUnavailable: (name: string) => boolean,\n    reserve: (name: string) => void,\n  ): IdentifierName {\n    const baseName = new IdentifierName(prefix)\n\n    if (!isUnavailable(baseName.value)) {\n      reserve(baseName.value)\n\n      return baseName\n    }\n\n    let suffix = 1\n    let candidate = new IdentifierName(`${prefix}_${suffix}`)\n\n    while (isUnavailable(candidate.value)) {\n      suffix += 1\n      candidate = new IdentifierName(`${prefix}_${suffix}`)\n    }\n\n    reserve(candidate.value)\n\n    return candidate\n  }\n\n  private reserveLexicalName(name: IdentifierName): void {\n    if (this.isNameVisible(name.value) || this.inheritedNames.has(name.value)) {\n      throw new ForgeInternalError(`CodeGenerator: name \"${name.value}\" is already visible in this scope`)\n    }\n\n    this.currentScope.names.add(name.value)\n  }\n\n  private reserveFunctionName(name: IdentifierName): void {\n    if (this.isNameVisible(name.value)) {\n      throw new ForgeInternalError(`CodeGenerator: name \"${name.value}\" is already declared in this function`)\n    }\n\n    this.functionNames.add(name.value)\n    this.rootScope.names.add(name.value)\n  }\n\n  private isNameVisible(name: string): boolean {\n    return this.functionNames.has(name) || this.scopeStack.some(frame => frame.names.has(name))\n  }\n\n  private namesVisibleHere(): ReadonlySet<string> {\n    return new Set([\n      ...this.inheritedNames,\n      ...this.functionNames,\n      ...this.scopeStack.flatMap(frame => [...frame.names]),\n    ])\n  }\n\n  private get currentBody(): CodeNode[] {\n    return this.nodeFrames[this.nodeFrames.length - 1].body\n  }\n\n  private get rootScope(): ScopeFrame {\n    return this.scopeStack[0]\n  }\n\n  private get currentScope(): ScopeFrame {\n    return this.scopeStack[this.scopeStack.length - 1]\n  }\n}\n\nconst createScopeFrame = (names: Iterable<string> = []): ScopeFrame => ({ names: new Set(names) })\n\nconst splitCommentLines = (text: string): string[] => text.split(/\\r\\n|[\\n\\r\\u2028\\u2029]/)\n\nconst resolveAsyncOption = (options: FunctionOptions): boolean =>\n  typeof options.async === 'function' ? options.async() : options.async === true\n","import { isTemplateNode } from '../../../contracts/ast/nodes'\nimport { TemplateNode } from '../../../contracts/ast/template.type'\nimport { FieldCodeKind, type DynamicFieldCode, type StaticFieldCode } from '../../../contracts/models/fieldModel.type'\nimport { CodeFragment, code, literal, propertyCode, SafeCode } from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport ExpressionDispatcher from '../expressions/ExpressionDispatcher'\n\n/**\n * Emits field code expressions consistently across generated-function compilers.\n *\n * A field code identifies a field -- it can be a static string or an authored\n * expression. Compilers use the resulting expression for answer lookup,\n * `Self()` resolution, validation metadata, and field inventory, so this\n * class keeps the string coercion rules in one place.\n */\nexport default class FieldCodeEmitter {\n  constructor(private readonly expr: ExpressionDispatcher) {}\n\n  /**\n   * Emits a field-code model as either a string literal or a scoped `const`.\n   * Dynamic codes (those derived from an expression) compile under the current\n   * iterator scope, so callers must already be inside the enclosing loop.\n   */\n  compileModelExpression(\n    fieldCode: StaticFieldCode | DynamicFieldCode | undefined,\n    generator: CodeGenerator,\n  ): CodeFragment | IdentifierName | undefined {\n    if (fieldCode === undefined) {\n      return undefined\n    }\n\n    if (fieldCode.kind === FieldCodeKind.STATIC) {\n      return literal(fieldCode.value)\n    }\n\n    const variableName = isTemplateNode(fieldCode.node.node) ? 'templateCode' : 'fieldCode'\n\n    return generator.const(variableName, code`String(${this.expr.compileOperandCode(fieldCode.node.node, generator)})`)\n  }\n\n  /**\n   * Emits a registered field code as either a string literal or a scoped const.\n   */\n  compileRegisteredExpression(\n    fieldCode: unknown,\n    generator: CodeGenerator,\n    variableName = 'fieldCode',\n  ): CodeFragment | IdentifierName | undefined {\n    const codeExpression = this.compileRegisteredInlineExpression(fieldCode, generator)\n\n    if (codeExpression === undefined) {\n      return undefined\n    }\n\n    if (typeof fieldCode === 'string') {\n      return codeExpression\n    }\n\n    return generator.const(variableName, codeExpression)\n  }\n\n  /**\n   * Emits a registered field code as an inline expression, used when assigning block properties.\n   */\n  compileRegisteredInlineExpression(fieldCode: unknown, generator?: CodeGenerator): CodeFragment | undefined {\n    if (typeof fieldCode === 'string') {\n      return literal(fieldCode)\n    }\n\n    if (this.expr.isCompilableNode(fieldCode) || this.expr.isTemplateNode(fieldCode)) {\n      return code`String(${this.expr.compileOperandCode(fieldCode, generator)})`\n    }\n\n    return undefined\n  }\n\n  /**\n   * Emits a template field code under the current iterator/template scope.\n   */\n  compileTemplateExpression(\n    node: TemplateNode,\n    generator: CodeGenerator,\n    variableName = 'templateCode',\n  ): CodeFragment | IdentifierName | undefined {\n    const fieldCode = node.properties?.code\n\n    if (typeof fieldCode === 'string') {\n      return literal(fieldCode)\n    }\n\n    if (!this.expr.isTemplateNode(fieldCode)) {\n      return undefined\n    }\n\n    return generator.const(variableName, code`String(${this.expr.compileTemplateExpressionCode(fieldCode, generator)})`)\n  }\n\n  /**\n   * Assigns a FIELD block's code property only when it resolves to a string expression.\n   */\n  assignProperty(\n    fieldCode: unknown,\n    generator: CodeGenerator,\n    targetObject: SafeCode,\n    key: string,\n    preferredCodeExpression?: SafeCode,\n  ): void {\n    const codeExpression = preferredCodeExpression ?? this.compileRegisteredInlineExpression(fieldCode, generator)\n\n    if (codeExpression === undefined) {\n      return\n    }\n\n    generator.assign(code`${targetObject}${propertyCode(key)}`, codeExpression)\n  }\n}\n","import { CodeFragment, code } from '../codegen/fragments/CodeFragment'\nimport { NodeCompilationContext } from './types'\n\n/** Compiles nullish coalescing with one primary evaluation and a lazy fallback. */\nexport default class NullishNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  compile(properties: Record<string, unknown>): CodeFragment {\n    const result = this.ctx.generator.let('nullishResult', this.ctx.compileOperandCode(properties.input))\n\n    this.ctx.generator.if(code`${result} == null`, () => {\n      this.ctx.generator.assign(result, this.ctx.compileOperandCode(properties.fallback))\n    })\n\n    return code`${result}`\n  }\n}\n","import { FunctionType } from '../../../../../authoring/types/enums'\nimport { formatCallsiteChain, resolveCallsitePositionChain } from '../../../../../shared/diagnostics/formatCallsite'\nimport {\n  CodeFragment,\n  arrayCode,\n  callCode,\n  code,\n  literal,\n  positionedCode,\n  propertyCode,\n} from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\n\nexport interface DiagnosticMetadata {\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n  readonly definedAt?: string\n}\n\nconst GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM = new IdentifierName('_forgeHelpers')\nconst RUNTIME_DIAGNOSTICS_PARAM = new IdentifierName('_forgeRuntimeDiagnostics')\nconst CONTEXT_PARAM = new IdentifierName('ctx')\n\nexport default class DiagnosticEmitter {\n  private readonly metadataByKey = new Map<string, number>()\n\n  private readonly metadataEntries: DiagnosticMetadata[] = []\n\n  reset(): void {\n    this.metadataByKey.clear()\n    this.metadataEntries.length = 0\n  }\n\n  snapshot(): readonly DiagnosticMetadata[] {\n    return Object.freeze(this.metadataEntries.map(metadata => Object.freeze({ ...metadata })))\n  }\n\n  /**\n   * Binds authored source positions to a fragment without routing it through a\n   * tracked helper call. For expressions that cannot throw, tracking buys no\n   * error attribution — only the source-map positions matter.\n   */\n  attachPositions(expression: CodeFragment, source: unknown): CodeFragment {\n    return positionedCode(expression, this.resolvePositions(source))\n  }\n\n  compileExpression(source: unknown, generator: CodeGenerator, compile: () => CodeFragment): CodeFragment {\n    const metadata = this.getMetadata(source)\n\n    if (metadata === undefined) {\n      return compile()\n    }\n\n    const result = generator.let('expressionResult')\n    const diagnosticReference = this.intern(metadata)\n    const positions = this.resolvePositions(source)\n\n    generator.withSourcePositions(positions, () => {\n      generator.tryCatch(\n        () => generator.assign(result, compile()),\n        'error',\n        error => generator.throw(code`${RUNTIME_DIAGNOSTICS_PARAM}.wrap(${error}, ${diagnosticReference})`),\n      )\n    })\n\n    return positionedCode(code`${result}`, positions)\n  }\n\n  /**\n   * Unlike `wrapExpression`, the function name is always known here (it's a\n   * required parameter, not derived from `source`), so metadata is always\n   * worth tracking and this always routes through the helper call.\n   */\n  wrapFunctionCall(\n    helperName: string,\n    funcName: string,\n    argExprs: readonly CodeFragment[],\n    source: unknown,\n  ): CodeFragment {\n    const metadata: DiagnosticMetadata = {\n      ...this.getSourceDiagnostics(source),\n      functionName: funcName,\n      functionType: this.getFunctionType(source),\n    }\n\n    return positionedCode(\n      this.compileFunctionHelperCall(helperName, this.intern(metadata), funcName, argExprs),\n      this.resolvePositions(source),\n    )\n  }\n\n  private getMetadata(source: unknown, functionName?: string): DiagnosticMetadata | undefined {\n    const sourceDiagnostics = this.getSourceDiagnostics(source)\n    const resolvedFunctionName = functionName ?? this.getFunctionName(source)\n    const functionType = this.getFunctionType(source)\n\n    if (\n      sourceDiagnostics.nodeId === undefined &&\n      sourceDiagnostics.formattedPath === undefined &&\n      sourceDiagnostics.definedAt === undefined &&\n      resolvedFunctionName === undefined &&\n      functionType === undefined\n    ) {\n      return undefined\n    }\n\n    return {\n      ...sourceDiagnostics,\n      functionName: resolvedFunctionName,\n      functionType,\n    }\n  }\n\n  private getSourceDiagnostics(source: unknown): DiagnosticMetadata {\n    const formattedPath = this.getFormattedPath(source)\n    const definedAt = this.getDefinedAt(source)\n\n    if (!isRecord(source)) {\n      return {\n        formattedPath,\n        definedAt,\n      }\n    }\n\n    return {\n      nodeId: typeof source.id === 'string' ? source.id : undefined,\n      formattedPath,\n      definedAt,\n    }\n  }\n\n  private getDefinedAt(source: unknown): string | undefined {\n    const callsite = this.getCallsite(source)\n\n    if (callsite === undefined) {\n      return undefined\n    }\n\n    const chain = formatCallsiteChain(callsite)\n\n    return chain.length > 0 ? chain.join('\\n') : undefined\n  }\n\n  /** Resolves the chain of authored call-site positions (innermost first) for source-map output. */\n  private resolvePositions(source: unknown) {\n    return resolveCallsitePositionChain(this.getCallsite(source))\n  }\n\n  private getCallsite(source: unknown): { stack?: string } | undefined {\n    if (!isRecord(source)) {\n      return undefined\n    }\n\n    const diagnostics = source.diagnostics\n\n    if (!isRecord(diagnostics)) {\n      return undefined\n    }\n\n    const callsite = diagnostics.callsite\n\n    if (!isRecord(callsite)) {\n      return undefined\n    }\n\n    const { stack } = callsite\n\n    if (stack !== undefined && typeof stack !== 'string') {\n      return undefined\n    }\n\n    return { stack }\n  }\n\n  private getFormattedPath(source: unknown): string | undefined {\n    if (!isRecord(source)) {\n      return undefined\n    }\n\n    const diagnostics = source.diagnostics\n\n    if (!isRecord(diagnostics)) {\n      return undefined\n    }\n\n    const sourceLocation = diagnostics.source\n\n    if (!isRecord(sourceLocation)) {\n      return undefined\n    }\n\n    return typeof sourceLocation.formattedPath === 'string' ? sourceLocation.formattedPath : undefined\n  }\n\n  private getFunctionName(source: unknown): string | undefined {\n    if (!isRecord(source)) {\n      return undefined\n    }\n\n    const properties = isRecord(source.properties) ? source.properties : source\n    const name = properties.name\n\n    return typeof name === 'string' ? name : undefined\n  }\n\n  private getFunctionType(source: unknown): string | undefined {\n    if (!isRecord(source)) {\n      return undefined\n    }\n\n    const expressionType = source.expressionType\n\n    switch (expressionType) {\n      case FunctionType.CONDITION:\n      case FunctionType.TRANSFORMER:\n      case FunctionType.GENERATOR:\n      case FunctionType.EFFECT:\n        return expressionType\n      default:\n        return undefined\n    }\n  }\n\n  private compileFunctionHelperCall(\n    helperName: string,\n    diagnosticReference: number,\n    funcName: string,\n    argExprs: readonly CodeFragment[],\n  ): CodeFragment {\n    const args = [\n      CONTEXT_PARAM,\n      RUNTIME_DIAGNOSTICS_PARAM,\n      literal(diagnosticReference),\n      literal(funcName),\n      arrayCode(argExprs),\n    ]\n\n    return callCode(code`${GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM}${propertyCode(helperName)}`, args)\n  }\n\n  private intern(metadata: DiagnosticMetadata): number {\n    const key = JSON.stringify(metadata)\n    const existingReference = this.metadataByKey.get(key)\n\n    if (existingReference !== undefined) {\n      return existingReference\n    }\n\n    const reference = this.metadataEntries.length\n\n    this.metadataEntries.push(metadata)\n    this.metadataByKey.set(key, reference)\n\n    return reference\n  }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value)\n}\n","import { TemplateValue } from '../../../contracts/ast/template.type'\nimport { CodeFragment, code, literal, optionalPropertyCode, propertyCode } from '../codegen/fragments/CodeFragment'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport { NodeCompilationContext } from './types'\n\n/**\n * Compiles authored reference paths to safe JavaScript property access.\n *\n * This is where DSL namespaces such as answers, @self, @scope, and @loop are\n * translated into the runtime values available inside generated functions.\n */\nexport default class ReferenceNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  /**\n   * Routes a reference path to its runtime source: a namespace like `data` or\n   * `session`, the `@self` field, or a scoped iterator frame (the item/index\n   * variables from a surrounding loop).\n   */\n  compile(properties: Record<string, unknown>): CodeFragment {\n    const path = (properties.path ?? []) as (string | number | TemplateValue)[]\n    const base = properties.base\n\n    if (path.length === 0) {\n      if (base !== undefined) {\n        return this.ctx.compileOperandCode(base)\n      }\n\n      return literal(undefined)\n    }\n\n    if (base !== undefined) {\n      return this.compileBaseReference(base, path)\n    }\n\n    const namespace = path[0] as string\n\n    if (namespace === '@scope') {\n      return this.compileIteratorScopeReference(path)\n    }\n\n    if (namespace === '@loop') {\n      return this.compileIteratorLoopReference(path)\n    }\n\n    if (namespace === '@self') {\n      return this.compileSelfAnswerReference(['answers', ...path])\n    }\n\n    if (namespace === 'answers') {\n      return this.compileAnswerReference(path)\n    }\n\n    const ctxNamespace = this.ctx.namespaceToCtxCode(namespace)\n    const remaining = path.slice(1)\n\n    if (remaining.length === 0) {\n      return ctxNamespace\n    }\n\n    return remaining.reduce<CodeFragment>(\n      (acc, segment) => code`${acc}${optionalPropertyCode(String(segment))}`,\n      ctxNamespace,\n    )\n  }\n\n  /**\n   * Applies a relative path to an already-compiled base expression.\n   */\n  private compileBaseReference(base: unknown, path: (string | number | TemplateValue)[]): CodeFragment {\n    const baseExpr = this.ctx.compileOperandCode(base)\n\n    return path.reduce<CodeFragment>(\n      (acc, segment) => code`${acc}${optionalPropertyCode(String(segment))}`,\n      code`(${baseExpr})`,\n    )\n  }\n\n  /**\n   * Resolves answers[fieldCode].current, including dynamic field-code operands.\n   */\n  private compileAnswerReference(path: (string | number | TemplateValue)[]): CodeFragment {\n    if (path.length < 2) {\n      return literal(undefined)\n    }\n\n    const fieldCode = path[1]\n\n    if (fieldCode === '@self') {\n      return this.compileSelfAnswerReference(path)\n    }\n\n    const fieldAccess =\n      typeof fieldCode === 'string'\n        ? propertyCode(fieldCode)\n        : code`[String(${this.ctx.compileOperandCode(fieldCode)})]`\n    let expr = code`ctx.answers${fieldAccess}?.current`\n\n    for (let i = 2; i < path.length; i++) {\n      expr = code`${expr}${optionalPropertyCode(String(path[i]))}`\n    }\n\n    return expr\n  }\n\n  /**\n   * Resolves @self references against the field code supplied by the caller.\n   */\n  private compileSelfAnswerReference(path: (string | number | TemplateValue)[]): CodeFragment {\n    const selfCodeExpr = this.ctx.selfCodeExpr\n\n    if (selfCodeExpr !== undefined) {\n      let expr = code`ctx.answers[${selfCodeExpr}]?.current`\n\n      for (let i = 2; i < path.length; i++) {\n        expr = code`${expr}${optionalPropertyCode(String(path[i]))}`\n      }\n\n      return expr\n    }\n\n    return literal(undefined)\n  }\n\n  /**\n   * Resolves @scope references from the active iterator stack frame.\n   */\n  private compileIteratorScopeReference(path: (string | number | TemplateValue)[]): CodeFragment {\n    if (path.length < 2) {\n      return literal(undefined)\n    }\n\n    const level = typeof path[1] === 'string' ? parseInt(path[1] as string, 10) : (path[1] as number)\n    const frame = this.ctx.iteratorStack[this.ctx.iteratorStack.length - 1 - level]\n\n    if (!frame) {\n      return literal(undefined)\n    }\n\n    if (path.length === 2) {\n      return toCode(frame.rawItemExpr)\n    }\n\n    const property = path[2] as string\n    const itemVar = toCode(frame.itemVar)\n    const rawItemExpr = toCode(frame.rawItemExpr)\n\n    if (property === '@key') {\n      return code`${itemVar}[\"@key\"]`\n    }\n\n    if (property === '@item') {\n      return rawItemExpr\n    }\n\n    if (property === '@value') {\n      return code`${itemVar}[\"@value\"]`\n    }\n\n    let expr = code`${itemVar}${propertyCode(property)}`\n\n    for (let i = 3; i < path.length; i++) {\n      expr = code`${expr}${optionalPropertyCode(String(path[i]))}`\n    }\n\n    return expr\n  }\n\n  /**\n   * Resolves @loop metadata such as index, first, last, and length.\n   */\n  private compileIteratorLoopReference(path: (string | number | TemplateValue)[]): CodeFragment {\n    if (path.length < 3) {\n      return literal(undefined)\n    }\n\n    const level = typeof path[1] === 'string' ? parseInt(path[1] as string, 10) : (path[1] as number)\n    const frame = this.ctx.iteratorStack[this.ctx.iteratorStack.length - 1 - level]\n\n    if (!frame) {\n      return literal(undefined)\n    }\n\n    const property = path[2] as string\n    const indexVar = toCode(frame.indexVar)\n    const inputLengthExpr = toCode(frame.inputLengthExpr)\n\n    if (property === 'index') {\n      return code`(${indexVar} + 1)`\n    }\n\n    if (property === 'index0') {\n      return indexVar\n    }\n\n    if (property === 'revindex') {\n      return code`(${inputLengthExpr} - ${indexVar})`\n    }\n\n    if (property === 'revindex0') {\n      return code`(${inputLengthExpr} - ${indexVar} - 1)`\n    }\n\n    if (property === 'first') {\n      return code`${indexVar} === 0`\n    }\n\n    if (property === 'last') {\n      return code`${indexVar} === ${inputLengthExpr} - 1`\n    }\n\n    if (property === 'length') {\n      return inputLengthExpr\n    }\n\n    return literal(undefined)\n  }\n}\n\nconst toCode = (value: CodeFragment | IdentifierName): CodeFragment =>\n  value instanceof IdentifierName ? code`${value}` : value\n","import { PredicateType } from '../../../../../authoring/types/enums'\nimport { CodeFragment, arrayCode, code, literal } from '../codegen/fragments/CodeFragment'\nimport { isASTNode, isTemplateNode } from '../../../contracts/ast/nodes'\nimport { NodeCompilationContext } from './types'\n\n/**\n * Compiles predicate nodes into boolean JavaScript expressions.\n *\n * Predicate nodes are shared across validation, reachability, rendering guards,\n * and hooks, so this compiler keeps the output as a pure expression (not\n * statements) and delegates registered condition function calls back through\n * the `ExpressionDispatcher`.\n */\nexport default class PredicateNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  /**\n   * Dispatches each predicate type (TEST, AND, OR, NOT, XOR) to its compiler.\n   */\n  compile(predicateType: string, properties: Record<string, unknown>, matchSubject?: CodeFragment): CodeFragment {\n    switch (predicateType) {\n      case PredicateType.TEST:\n        return this.compileTest(properties, matchSubject)\n      case PredicateType.AND:\n        return this.compileLogical(properties, true, matchSubject)\n      case PredicateType.OR:\n        return this.compileLogical(properties, false, matchSubject)\n      case PredicateType.NOT:\n        return this.compileNot(properties, matchSubject)\n      case PredicateType.XOR:\n        return this.compileXor(properties, matchSubject)\n      default:\n        return literal(false)\n    }\n  }\n\n  /** Applies a match's evaluated subject to each condition leaf in its predicate tree. */\n  compileOperand(operand: unknown, matchSubject?: CodeFragment): CodeFragment {\n    if (matchSubject === undefined) {\n      return this.ctx.compileOperandCode(operand)\n    }\n\n    if (\n      (isASTNode(operand) || isTemplateNode(operand)) &&\n      'predicateType' in operand &&\n      typeof operand.predicateType === 'string'\n    ) {\n      return this.compile(operand.predicateType, operand.properties ?? {}, matchSubject)\n    }\n\n    return this.ctx.compileOperandCode(operand)\n  }\n\n  /**\n   * Compiles a TEST predicate by calling a registered condition function,\n   * optionally wrapping the result in logical negation.\n   */\n  private compileTest(properties: Record<string, unknown>, matchSubject?: CodeFragment): CodeFragment {\n    const subject = properties.subject\n    const condition = properties.condition as Record<string, unknown> | undefined\n    const negate = properties.negate === true\n\n    if ((!matchSubject && !subject) || !condition) {\n      return literal(false)\n    }\n\n    const conditionProps = (condition.properties ?? condition) as Record<string, unknown>\n    const funcName = conditionProps.name as string\n    const funcArgs = (conditionProps.arguments ?? []) as unknown[]\n    const subjectExpr = matchSubject ?? this.ctx.compileOperandCode(subject)\n    const argExprs = funcArgs.map(arg => this.ctx.compileOperandCode(arg))\n    const callExpr = this.ctx.compileFunctionCallCode(funcName, [subjectExpr, ...argExprs], condition, {\n      argumentPrefixes: ['subject', ...funcArgs.map((_, index) => `functionArgument${index + 1}`)],\n    })\n\n    if (negate) {\n      return code`!(${callExpr})`\n    }\n\n    return callExpr\n  }\n\n  /**\n   * Preserves JavaScript's short-circuit behaviour for AND and OR predicates.\n   */\n  private compileLogical(\n    properties: Record<string, unknown>,\n    isAnd: boolean,\n    matchSubject?: CodeFragment,\n  ): CodeFragment {\n    const operands = (properties.operands ?? []) as unknown[]\n\n    if (operands.length === 0) {\n      return literal(isAnd)\n    }\n\n    const result = this.ctx.generator.let('predicateResult', this.compileOperand(operands[0], matchSubject))\n\n    operands.slice(1).forEach(operand => {\n      const condition = isAnd ? code`${result}` : code`!${result}`\n\n      this.ctx.generator.if(condition, () => {\n        this.ctx.generator.assign(result, this.compileOperand(operand, matchSubject))\n      })\n    })\n\n    return code`${result}`\n  }\n\n  /**\n   * Emits logical negation around a nested predicate operand.\n   */\n  private compileNot(properties: Record<string, unknown>, matchSubject?: CodeFragment): CodeFragment {\n    return code`(!(${this.compileOperand(properties.operand, matchSubject)}))`\n  }\n\n  /**\n   * Counts truthy operands so XOR remains correct for more than two inputs.\n   */\n  private compileXor(properties: Record<string, unknown>, matchSubject?: CodeFragment): CodeFragment {\n    const operands = (properties.operands ?? []) as unknown[]\n    const compiled = operands.map(op => code`Boolean(${this.compileOperand(op, matchSubject)})`)\n\n    return code`(${arrayCode(compiled)}.filter(Boolean).length === 1)`\n  }\n}\n","import { CodeFragment, code } from '../codegen/fragments/CodeFragment'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport { NodeCompilationContext } from './types'\n\n/**\n * Compiles authored function calls and pipelines (chains of transformers\n * where each step receives the previous step's result).\n *\n * The `ExpressionDispatcher` owns diagnostics and await tracking, so this\n * class only shapes arguments and feeds function calls back through it.\n */\nexport default class PipelineNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  /**\n   * Threads the previous step result into each pipeline function call.\n   */\n  compilePipeline(properties: Record<string, unknown>): CodeFragment {\n    const steps = (properties.steps ?? []) as Record<string, unknown>[]\n    const value = this.ctx.generator.let('pipelineValue', this.ctx.compileOperandCode(properties.input))\n\n    steps.forEach(step => this.compilePipelineStep(value, step))\n\n    return code`${value}`\n  }\n\n  /**\n   * Compiles one transformer step, treating `undefined` as \"no value was\n   * passed through the pipeline\".\n   */\n  private compilePipelineStep(value: IdentifierName, step: Record<string, unknown>): void {\n    const stepProps = (step.properties ?? step) as Record<string, unknown>\n    const funcName = stepProps.name as string\n    const funcArgs = (stepProps.arguments ?? []) as unknown[]\n    this.ctx.generator.if(code`${value} !== undefined`, () => {\n      const argExprs = funcArgs.map(arg => this.ctx.compileOperandCode(arg))\n      const callResult = this.ctx.compileFunctionCallCode(funcName, [code`${value}`, ...argExprs], step, {\n        argumentPrefixes: ['pipelineValue', ...funcArgs.map((_, index) => `functionArgument${index + 1}`)],\n      })\n\n      this.ctx.generator.assign(value, callResult)\n    })\n  }\n\n  /**\n   * Compiles a standalone function call (condition, transformer, or generator)\n   * with diagnostic source metadata for runtime error reporting.\n   */\n  compileFunction(properties: Record<string, unknown>, source?: unknown): CodeFragment {\n    const funcName = properties.name as string\n    const funcArgs = (properties.arguments ?? []) as unknown[]\n    const argExprs = funcArgs.map(arg => this.ctx.compileOperandCode(arg))\n\n    return this.ctx.compileFunctionCallCode(funcName, argExprs, source ?? properties, {\n      argumentPrefixes: funcArgs.map((_, index) => `functionArgument${index + 1}`),\n    })\n  }\n}\n","import { CodeFragment, code } from '../codegen/fragments/CodeFragment'\nimport { NodeCompilationContext } from './types'\n\n/**\n * Compiles authored conditional expressions into JavaScript expressions (not\n * statements). The result stays usable anywhere an operand is expected, such\n * as formatter arguments, block properties, validation messages, or hook\n * outcomes.\n */\nexport default class ConditionalNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  /**\n   * Emits a lazy ternary so only the selected branch is evaluated at runtime.\n   */\n  compile(properties: Record<string, unknown>): CodeFragment {\n    const result = this.ctx.generator.let('conditionalResult')\n    const predicate = this.ctx.compileOperandCode(properties.predicate)\n\n    this.ctx.generator.if(\n      predicate,\n      () => this.ctx.generator.assign(result, this.ctx.compileOperandCode(properties.thenValue)),\n      () => this.ctx.generator.assign(result, this.ctx.compileOperandCode(properties.elseValue)),\n    )\n\n    return code`${result}`\n  }\n}\n","import { CodeFragment, code, literal } from '../codegen/fragments/CodeFragment'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport { NodeCompilationContext } from './types'\nimport PredicateNodeCompiler from './PredicateNodeCompiler'\n\n/** Compiles ordered branches against one evaluated subject, keeping branch operands and values lazy. */\nexport default class MatchNodeCompiler {\n  constructor(private readonly ctx: NodeCompilationContext) {}\n\n  /**\n   * Binds the subject before emitting a first-match-wins conditional chain.\n   */\n  compile(properties: Record<string, unknown>): CodeFragment {\n    const branches = (properties.branches ?? []) as Array<Record<string, unknown>>\n    const otherwise = properties.otherwise\n    const subject = this.ctx.generator.const('matchSubject', this.ctx.compileOperandCode(properties.subject))\n    const result = this.ctx.generator.let('matchResult')\n\n    this.compileBranch(branches, otherwise, result, code`${subject}`)\n\n    return code`${result}`\n  }\n\n  private compileBranch(\n    branches: readonly Record<string, unknown>[],\n    otherwise: unknown,\n    result: IdentifierName,\n    subject: CodeFragment,\n  ): void {\n    const [branch, ...remainingBranches] = branches\n\n    if (branch === undefined) {\n      this.ctx.generator.assign(\n        result,\n        otherwise === undefined ? literal(undefined) : this.ctx.compileOperandCode(otherwise),\n      )\n\n      return\n    }\n\n    const predicate =\n      'expected' in branch\n        ? code`(${subject} === ${this.ctx.compileOperandCode(branch.expected)})`\n        : new PredicateNodeCompiler(this.ctx).compileOperand(branch.predicate, subject)\n\n    this.ctx.generator.if(\n      predicate,\n      () => this.ctx.generator.assign(result, this.ctx.compileOperandCode(branch.value)),\n      () => this.compileBranch(remainingBranches, otherwise, result, subject),\n    )\n  }\n}\n","import NullishNodeCompiler from './NullishNodeCompiler'\nimport { ASTNode } from '../../../contracts/ast/ast.type'\nimport { ASTNodeType } from '../../../contracts/ast/enums'\nimport { ExpressionType, FunctionType, IteratorType } from '../../../../../authoring/types/enums'\nimport { TemplateNode } from '../../../contracts/ast/template.type'\nimport ForgeUnregisteredFunctionError from '../../../../errors/ForgeUnregisteredFunctionError'\nimport {\n  CodeFragment,\n  arrayCode,\n  code,\n  literal,\n  objectCode,\n  ObjectCodeProperty,\n  SafeCode,\n} from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport DiagnosticEmitter, { type DiagnosticMetadata } from '../emitters/DiagnosticEmitter'\nimport { FunctionCallCompileOptions, IteratorScopeFrame, NodeCompilationContext } from './types'\nimport ReferenceNodeCompiler from './ReferenceNodeCompiler'\nimport PredicateNodeCompiler from './PredicateNodeCompiler'\nimport PipelineNodeCompiler from './PipelineNodeCompiler'\nimport ConditionalNodeCompiler from './ConditionalNodeCompiler'\nimport MatchNodeCompiler from './MatchNodeCompiler'\nimport { isASTNode } from '../../../contracts/ast/nodes'\nimport { isDeepStaticValue } from '../../../contracts/models/authoredValue.type'\nimport type { CompilationDependencies } from '../compilationDependencies.type'\n\nexport type { IteratorScopeFrame } from './types'\n\n/**\n * Coordinates the individual expression-node compilers and owns the temporary\n * state accumulated while generating a single function.\n *\n * Concern compilers (e.g. validation, reachability, hooks) use this as the\n * single entry point for compiling AST and template expressions. Routing\n * everything through here keeps iterator scope, `@self` scope, diagnostics,\n * and generated-function await tracking consistent across generated functions.\n */\nexport default class ExpressionDispatcher implements NodeCompilationContext {\n  private readonly iteratorFrames: IteratorScopeFrame[] = []\n\n  private readonly selfCodeExprs: CodeFragment[] = []\n\n  private readonly validationFunctionPrefixes: string[] = []\n\n  /** Nested expression bodies currently being emitted, innermost last. */\n  private readonly generatorScopes: CodeGenerator[] = []\n\n  private readonly references = new ReferenceNodeCompiler(this)\n\n  private readonly predicates = new PredicateNodeCompiler(this)\n\n  private readonly pipelines = new PipelineNodeCompiler(this)\n\n  private readonly nullish = new NullishNodeCompiler(this)\n\n  private readonly conditionals = new ConditionalNodeCompiler(this)\n\n  private readonly matches = new MatchNodeCompiler(this)\n\n  private readonly diagnostics = new DiagnosticEmitter()\n\n  private usedAwait = false\n\n  private fragmentGenerator = new CodeGenerator()\n\n  constructor(private readonly dependencies: CompilationDependencies) {}\n\n  get iteratorStack(): readonly IteratorScopeFrame[] {\n    return this.iteratorFrames\n  }\n\n  get iteratorDepth(): number {\n    return this.iteratorFrames.length\n  }\n\n  get selfCodeExpr(): CodeFragment | undefined {\n    return this.selfCodeExprs[this.selfCodeExprs.length - 1]\n  }\n\n  get usesAwait(): boolean {\n    return this.usedAwait\n  }\n\n  get generator(): CodeGenerator {\n    return this.generatorScopes[this.generatorScopes.length - 1] ?? this.fragmentGenerator\n  }\n\n  get diagnosticCatalogue(): readonly DiagnosticMetadata[] {\n    return this.diagnostics.snapshot()\n  }\n\n  /**\n   * Compiles a nested function body under its own await tracking and reports\n   * whether that body emitted an `await`. An await inside a nested function\n   * makes that function async, not the enclosing one, so the enclosing\n   * function's flag is restored afterwards.\n   */\n  trackNestedFunctionAwait(compileBody: () => void): boolean {\n    const enclosingUsedAwait = this.usedAwait\n\n    this.usedAwait = false\n\n    try {\n      compileBody()\n\n      return this.usedAwait\n    } finally {\n      this.usedAwait = enclosingUsedAwait\n    }\n  }\n\n  /**\n   * Clears per-function generation state so a concern compiler can start fresh.\n   */\n  reset(): void {\n    this.iteratorFrames.length = 0\n    this.selfCodeExprs.length = 0\n    this.validationFunctionPrefixes.length = 0\n    this.generatorScopes.length = 0\n    this.diagnostics.reset()\n    this.usedAwait = false\n    this.fragmentGenerator = new CodeGenerator()\n  }\n\n  /** Runs expression lowering against the function or lexical body that owns the emitted statements. */\n  withGeneratorScope<T>(generator: CodeGenerator, compile: () => T): T {\n    this.generatorScopes.push(generator)\n\n    try {\n      return compile()\n    } finally {\n      this.generatorScopes.pop()\n    }\n  }\n\n  /**\n   * Compiles a nested expression with `@scope` and `@loop` bound to an iterator\n   * frame (the item, index, and length variables for one level of iteration).\n   */\n  withIteratorFrame<T>(frame: IteratorScopeFrame, compile: () => T): T {\n    this.iteratorFrames.push(frame)\n\n    try {\n      return compile()\n    } finally {\n      this.iteratorFrames.pop()\n    }\n  }\n\n  /**\n   * Adds the current field-code expression for @self answer references.\n   */\n  pushSelfCodeExpression(codeExpr: CodeFragment): void {\n    this.selfCodeExprs.push(codeExpr)\n  }\n\n  /**\n   * Removes the current @self field-code expression.\n   */\n  popSelfCodeExpression(): void {\n    this.selfCodeExprs.pop()\n  }\n\n  /**\n   * Compiles a nested expression with @self bound when a field code is known.\n   */\n  withSelfCodeExpression<T>(codeExpr: SafeCode | undefined, compile: () => T): T {\n    if (codeExpr === undefined) {\n      return compile()\n    }\n\n    const typedCodeExpression = codeExpr instanceof IdentifierName ? code`${codeExpr}` : codeExpr\n\n    this.pushSelfCodeExpression(typedCodeExpression)\n\n    try {\n      return compile()\n    } finally {\n      this.popSelfCodeExpression()\n    }\n  }\n\n  /**\n   * Gives validation callbacks a stable developer-facing identity while their\n   * authored value (the raw value a journey author wrote) is compiled into\n   * generated code through the shared runtime-value compiler.\n   */\n  withValidationFunctionPrefix<T>(prefix: string, compile: () => T): T {\n    this.validationFunctionPrefixes.push(prefix)\n\n    try {\n      return compile()\n    } finally {\n      this.validationFunctionPrefixes.pop()\n    }\n  }\n\n  /**\n   * Registered AST nodes and iterator template nodes (expression nodes\n   * embedded inside authored templates) share the same expression compilers.\n   * Keeping the dispatch split here lets render, validation, answer prep,\n   * reachability, and hooks all use one scope and async model.\n   */\n  compileExpressionCode(node: ASTNode, generator?: CodeGenerator): CodeFragment {\n    if (generator !== undefined && generator !== this.generator) {\n      return this.withGeneratorScope(generator, () => this.compileExpressionCode(node))\n    }\n\n    if (!this.isCompilableNode(node)) {\n      return literal(node)\n    }\n\n    const properties = (node as unknown as { properties: Record<string, unknown> }).properties ?? {}\n    const expressionType =\n      node.type === ASTNodeType.EXPRESSION ? (node as unknown as { expressionType: string }).expressionType : undefined\n    const compile = () => {\n      if (node.type === ASTNodeType.PREDICATE) {\n        const predicateType = (node as unknown as { predicateType: string }).predicateType\n\n        return this.predicates.compile(predicateType, properties)\n      }\n\n      if (node.type === ASTNodeType.EXPRESSION) {\n        return this.dispatchExpression(expressionType as string, properties, node)\n      }\n\n      return literal(undefined)\n    }\n\n    if (this.hasOwnDiagnosticBoundary(expressionType) || this.isValidationPredicate(node.type)) {\n      return compile()\n    }\n\n    if (expressionType === ExpressionType.REFERENCE) {\n      const expression = compile()\n\n      if (this.isThrowFreeReference(expressionType, expression)) {\n        return this.diagnostics.attachPositions(expression, node)\n      }\n\n      return this.diagnostics.compileExpression(node, this.generator, () => expression)\n    }\n\n    return this.diagnostics.compileExpression(node, this.generator, compile)\n  }\n\n  /**\n   * Compiles expression nodes found inside templates, using the same scope\n   * and dispatch logic as top-level AST nodes.\n   */\n  compileTemplateExpressionCode(node: TemplateNode, generator?: CodeGenerator): CodeFragment {\n    if (generator !== undefined && generator !== this.generator) {\n      return this.withGeneratorScope(generator, () => this.compileTemplateExpressionCode(node))\n    }\n\n    const properties = (node.properties ?? {}) as Record<string, unknown>\n    const expressionType = node.originalType === ASTNodeType.EXPRESSION ? (node.expressionType as string) : undefined\n    const compile = () => {\n      if (node.originalType === ASTNodeType.PREDICATE) {\n        return this.predicates.compile(node.predicateType as string, properties)\n      }\n\n      if (node.originalType === ASTNodeType.EXPRESSION) {\n        return this.dispatchExpression(expressionType as string, properties, node)\n      }\n\n      return literal(undefined)\n    }\n\n    if (this.hasOwnDiagnosticBoundary(expressionType) || this.isValidationPredicate(node.originalType)) {\n      return compile()\n    }\n\n    if (expressionType === ExpressionType.REFERENCE) {\n      const expression = compile()\n\n      if (this.isThrowFreeReference(expressionType, expression)) {\n        return this.diagnostics.attachPositions(expression, node)\n      }\n\n      return this.diagnostics.compileExpression(node, this.generator, () => expression)\n    }\n\n    return this.diagnostics.compileExpression(node, this.generator, compile)\n  }\n\n  /**\n   * Reference chains compile to `?.`-guarded property reads, so unless a\n   * dynamic segment introduced a call they cannot throw. Tracking them through\n   * a diagnostic wrapper would allocate machinery purely to attribute an\n   * error that can never happen.\n   */\n  private isThrowFreeReference(expressionType: string | undefined, expression: CodeFragment): boolean {\n    return expressionType === ExpressionType.REFERENCE && !expression.containsInvocation\n  }\n\n  private hasOwnDiagnosticBoundary(expressionType: string | undefined): boolean {\n    // Function calls carry their own diagnostic metadata through evaluateFunction.\n    // Validation rules contain tracked operands and function calls, so wrapping\n    // the rule object itself only adds an unrelated callback around construction.\n    return expressionType === FunctionType.CONDITION ||\n      expressionType === FunctionType.TRANSFORMER ||\n      expressionType === FunctionType.GENERATOR ||\n      expressionType === ExpressionType.VALIDATION\n  }\n\n  private isValidationPredicate(nodeType: unknown): boolean {\n    // Predicate leaves already carry diagnostics through their references and\n    // registered function calls. Keep their boolean composition visible inside\n    // the named validation condition instead of wrapping the whole predicate.\n    return this.validationFunctionPrefixes.length > 0 && nodeType === ASTNodeType.PREDICATE\n  }\n\n  private dispatchExpression(\n    expressionType: string,\n    properties: Record<string, unknown>,\n    source?: unknown,\n  ): CodeFragment {\n    switch (expressionType) {\n      case ExpressionType.REFERENCE:\n        return this.references.compile(properties)\n      case ExpressionType.PIPELINE:\n        return this.pipelines.compilePipeline(properties)\n      case ExpressionType.ITERATE:\n        return this.compileIterate(properties)\n      case ExpressionType.VALIDATION:\n        return this.compileValidation(properties)\n      case FunctionType.CONDITION:\n      case FunctionType.TRANSFORMER:\n      case FunctionType.GENERATOR:\n        return this.pipelines.compileFunction(properties, source)\n      case ExpressionType.NULLISH:\n        return this.nullish.compile(properties)\n      case ExpressionType.CONDITIONAL:\n        return this.conditionals.compile(properties)\n      case ExpressionType.MATCH:\n        return this.matches.compile(properties)\n      default:\n        return literal(undefined)\n    }\n  }\n\n  /**\n   * Operands can be plain data, registered nodes, template nodes, or nested\n   * containers containing any of those. Compiling them recursively here keeps\n   * function arguments and block properties on the same rules.\n   */\n  compileOperandCode(value: unknown, generator?: CodeGenerator): CodeFragment {\n    if (generator !== undefined && generator !== this.generator) {\n      return this.withGeneratorScope(generator, () => this.compileOperandCode(value))\n    }\n\n    if (this.isTemplateNode(value)) {\n      return this.compileTemplateExpressionCode(value)\n    }\n\n    if (this.isCompilableNode(value)) {\n      return this.compileExpressionCode(value as ASTNode)\n    }\n\n    if (Array.isArray(value)) {\n      return arrayCode(value.map(entry => this.compileOperandCode(entry)))\n    }\n\n    if (value !== null && value !== undefined && typeof value === 'object') {\n      const properties = Object.entries(value as Record<string, unknown>).map(([key, entry]) => ({\n        key,\n        value: this.compileOperandCode(entry),\n      }))\n\n      return code`(${objectCode(properties)})`\n    }\n\n    if (value === undefined) {\n      return literal(undefined)\n    }\n\n    return literal(value)\n  }\n\n  /**\n   * Dispatches authored iterators to the MAP, FILTER, and FIND compilers,\n   * each of which produces a JavaScript expression (not statements).\n   */\n  private compileIterate(properties: Record<string, unknown>): CodeFragment {\n    const iterator = properties.iterator as\n      | {\n          type?: unknown\n          yieldTemplate?: unknown\n          predicateTemplate?: unknown\n        }\n      | undefined\n\n    // Iterator input and templates lower into this generator scope so async\n    // results are resolved before the next loop operation uses them.\n    if (iterator?.type === IteratorType.MAP) {\n      return this.compileMapIterator(properties.input, iterator.yieldTemplate)\n    }\n\n    if (iterator?.type === IteratorType.FILTER) {\n      return this.compileFilterIterator(properties.input, iterator.predicateTemplate)\n    }\n\n    if (iterator?.type === IteratorType.FIND) {\n      return this.compileFindIterator(properties.input, iterator.predicateTemplate)\n    }\n\n    if (iterator?.type === IteratorType.SOME) {\n      return this.compileSomeIterator(properties.input, iterator.predicateTemplate)\n    }\n\n    if (iterator?.type === IteratorType.EVERY) {\n      return this.compileEveryIterator(properties.input, iterator.predicateTemplate)\n    }\n\n    if (iterator?.type === IteratorType.COUNT) {\n      return this.compileCountIterator(properties.input, iterator.predicateTemplate)\n    }\n\n    return literal(undefined)\n  }\n\n  /**\n   * Builds the validation result object used by field-level and journey-level\n   * validation rules.\n   */\n  private compileValidation(properties: Record<string, unknown>): CodeFragment {\n    const condition = properties.condition\n\n    if (condition === undefined) {\n      return literal(undefined)\n    }\n\n    const messageValue = properties.message\n    const detailsValue = properties.details\n    const functionPrefix = this.validationFunctionPrefixes[this.validationFunctionPrefixes.length - 1] ?? 'validation'\n    const validationCondition = this.compileReturnFunctionExpression(\n      () => this.compileOperandCode(condition),\n      `evaluate_${functionPrefix}_condition`,\n    )\n    const message = this.isStaticOperand(messageValue)\n      ? this.compileStaticOperand(messageValue, literal(''))\n      : this.compileReturnFunctionExpression(\n          () => this.compileOperandCode(messageValue),\n          `evaluate_${functionPrefix}_message`,\n        )\n    const ruleProperties: ObjectCodeProperty[] = [\n      { key: 'condition', value: validationCondition },\n      { key: 'message', value: message },\n      { key: 'submissionOnly', value: literal(properties.submissionOnly === true) },\n    ]\n\n    if (properties.groups !== undefined) {\n      ruleProperties.push({ key: 'groups', value: this.compileOperandCode(properties.groups) })\n    }\n\n    if (detailsValue !== undefined) {\n      const details = this.isStaticOperand(detailsValue)\n        ? this.compileStaticOperand(detailsValue, literal(undefined))\n        : this.compileReturnFunctionExpression(\n            () => this.compileOperandCode(detailsValue),\n            `evaluate_${functionPrefix}_details`,\n          )\n\n      ruleProperties.push({ key: 'details', value: details })\n    }\n\n    return objectCode(ruleProperties)\n  }\n\n  /**\n   * Compiles a map iterator into a JavaScript expression that builds an array\n   * by evaluating the yield template for each input item.\n   */\n  private compileMapIterator(input: unknown, yieldTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.const('_result', arrayCode([]))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const yieldExpr = this.withIteratorFrame(frame, () =>\n        yieldTemplate !== undefined ? this.compileOperandCode(yieldTemplate) : literal(undefined),\n      )\n      const yieldVar = generator.const('_yield', yieldExpr)\n\n      generator.if(code`${yieldVar} !== undefined`, () => {\n        generator.statement(code`${resultVar}.push(${yieldVar})`)\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  /**\n   * Compiles a filter iterator into a JavaScript expression that keeps only\n   * items matching the predicate template.\n   */\n  private compileFilterIterator(input: unknown, predicateTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.const('_result', arrayCode([]))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const predicateExpr = this.withIteratorFrame(frame, () =>\n        predicateTemplate !== undefined ? this.compileOperandCode(predicateTemplate) : literal(false),\n      )\n\n      generator.if(predicateExpr, () => {\n        generator.statement(code`${resultVar}.push(${rawItemExpr})`)\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  /**\n   * Compiles a find iterator into a JavaScript expression that returns the\n   * first item matching the predicate template.\n   */\n  private compileFindIterator(input: unknown, predicateTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.let('_result', literal(undefined))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const predicateExpr = this.withIteratorFrame(frame, () =>\n        predicateTemplate !== undefined ? this.compileOperandCode(predicateTemplate) : literal(false),\n      )\n\n      generator.if(predicateExpr, () => {\n        generator.assign(resultVar, rawItemExpr)\n        generator.break()\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  private compileSomeIterator(input: unknown, predicateTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.let('_result', literal(false))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const predicateExpr = this.withIteratorFrame(frame, () =>\n        predicateTemplate !== undefined ? this.compileOperandCode(predicateTemplate) : literal(false),\n      )\n\n      generator.if(predicateExpr, () => {\n        generator.assign(resultVar, literal(true))\n        generator.break()\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  private compileCountIterator(input: unknown, predicateTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.let('_result', literal(0))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const predicateExpr = this.withIteratorFrame(frame, () =>\n        predicateTemplate !== undefined ? this.compileOperandCode(predicateTemplate) : literal(false),\n      )\n\n      generator.if(predicateExpr, () => {\n        generator.assign(resultVar, code`${resultVar} + 1`)\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  private compileEveryIterator(input: unknown, predicateTemplate: unknown): CodeFragment {\n    const inputExpr = this.compileOperandCode(input)\n    const generator = this.generator\n    const inputVar = generator.let('_input', inputExpr)\n\n    this.compileNormalizeIteratorInput(inputVar, generator)\n\n    const resultVar = generator.let('_result', literal(true))\n\n    this.compileIteratorArrayLoop(inputVar, generator, (indexVar, rawItemExpr) => {\n      const itemVar = this.compileIteratorItemScope(rawItemExpr, generator)\n      const frame: IteratorScopeFrame = {\n        itemVar,\n        indexVar,\n        inputLengthExpr: code`${inputVar}.length`,\n        rawItemExpr,\n      }\n      const predicateExpr = this.withIteratorFrame(frame, () =>\n        predicateTemplate !== undefined ? this.compileOperandCode(predicateTemplate) : literal(false),\n      )\n\n      generator.if(code`!(${predicateExpr})`, () => {\n        generator.assign(resultVar, literal(false))\n        generator.break()\n      })\n    })\n\n    return code`${resultVar}`\n  }\n\n  /**\n   * Normalizes object inputs to keyed items so iterator templates can use @key\n   * and @value. Shared with `IteratorLoopEmitter` so both iterator code paths\n   * emit the same normalisation under the same generated names.\n   */\n  compileNormalizeIteratorInput(inputVar: IdentifierName, generator: CodeGenerator): void {\n    generator.if(code`${inputVar} != null && !Array.isArray(${inputVar}) && typeof ${inputVar} === \"object\"`, () => {\n      const mapEntry = generator.functionExpression(\n        'normaliseIteratorEntry',\n        ['entry'],\n        (callbackGenerator, [entry]) => {\n          const keyedObject = objectCode([{ key: '@key', value: code`${entry}[0]` }])\n          const scalarObject = objectCode([\n            { key: '@key', value: code`${entry}[0]` },\n            { key: '@value', value: code`${entry}[1]` },\n          ])\n\n          callbackGenerator.return(\n            code`typeof ${entry}[1] === \"object\" && ${entry}[1] !== null ? Object.assign(${keyedObject}, ${entry}[1]) : ${scalarObject}`,\n          )\n        },\n      )\n\n      generator.assign(inputVar, code`Object.entries(${inputVar}).map(${mapEntry})`)\n    })\n\n    generator.if(code`Array.isArray(${inputVar})`, () => {\n      const keepItem = generator.functionExpression('keepIteratorItem', ['item'], (callbackGenerator, [item]) => {\n        callbackGenerator.return(code`${item} != null`)\n      })\n\n      generator.assign(inputVar, code`${inputVar}.filter(${keepItem})`)\n    })\n  }\n\n  /**\n   * Produces the per-item object exposed to @scope and `Item()` references.\n   * Shared with `IteratorLoopEmitter` for the same reason as normalisation.\n   */\n  compileIteratorItemScopeExpression(rawItemExpr: CodeFragment | IdentifierName): CodeFragment {\n    return code`typeof ${rawItemExpr} === \"object\" && ${rawItemExpr} !== null ? Object.assign({}, ${rawItemExpr}) : ${objectCode([{ key: '@value', value: rawItemExpr }])}`\n  }\n\n  private compileIteratorItemScope(rawItemExpr: CodeFragment, generator: CodeGenerator): IdentifierName {\n    return generator.const('_item', this.compileIteratorItemScopeExpression(rawItemExpr))\n  }\n\n  private compileIteratorArrayLoop(\n    inputVar: IdentifierName,\n    generator: CodeGenerator,\n    compileItem: (indexVar: IdentifierName, rawItemExpr: CodeFragment) => void,\n  ): void {\n    generator.if(code`Array.isArray(${inputVar})`, () => {\n      generator.forRange('_index', literal(0), code`${inputVar}.length`, indexVar => {\n        const rawItemExpr = code`${inputVar}[${indexVar}]`\n\n        generator.if(code`${rawItemExpr} == null`, () => {\n          generator.continue()\n        })\n        generator.statement(code`_forgeHelpers.consumeIteratorIteration(ctx)`)\n\n        compileItem(indexVar, rawItemExpr)\n      })\n    })\n  }\n\n  compileFunctionCallCode(\n    funcName: string,\n    argExprs: readonly CodeFragment[],\n    source?: unknown,\n    options: FunctionCallCompileOptions = {},\n  ): CodeFragment {\n    const registeredFunction = this.dependencies.functionRegistry.get(funcName)\n\n    if (!registeredFunction) {\n      throw new ForgeUnregisteredFunctionError({\n        functionName: funcName,\n        functionType: (source as { expressionType?: string } | undefined)?.expressionType ?? 'unknown',\n      })\n    }\n\n    this.usedAwait = true\n\n    const validationPrefix = this.validationFunctionPrefixes[this.validationFunctionPrefixes.length - 1]\n\n    if (validationPrefix !== undefined) {\n      const helperCall = this.compileDebuggableValidationFunctionCall(funcName, argExprs, source, options)\n\n      return this.compileMaybeAsyncResult(helperCall)\n    }\n\n    const helperCall = this.diagnostics.wrapFunctionCall('evaluateFunction', funcName, argExprs, source)\n\n    return this.compileMaybeAsyncResult(helperCall)\n  }\n\n  private compileDebuggableValidationFunctionCall(\n    funcName: string,\n    argExprs: readonly CodeFragment[],\n    source: unknown,\n    options: FunctionCallCompileOptions,\n  ): CodeFragment {\n    return this.compileNamedArgumentHelperCall('evaluateFunction', funcName, argExprs, source, options, scope =>\n      this.generator.const(scope.prefix, scope.argument),\n    )\n  }\n\n  private compileMaybeAsyncResult(helperCall: CodeFragment): CodeFragment {\n    const functionResult = this.generator.let('functionResult', helperCall)\n\n    this.generator.if(code`_forgeHelpers.isThenable(${functionResult})`, () => {\n      this.generator.assign(functionResult, code`await ${functionResult}`)\n    })\n\n    return code`${functionResult}`\n  }\n\n  /**\n   * Assigns each argument to a named const (via `declareArgument`) before the\n   * helper call, so a developer paused in the debugger can inspect the exact\n   * values passed to the registered function.\n   */\n  private compileNamedArgumentHelperCall(\n    helperName: string,\n    funcName: string,\n    argExprs: readonly CodeFragment[],\n    source: unknown,\n    options: FunctionCallCompileOptions,\n    declareArgument: (scope: { prefix: string; argument: CodeFragment }) => IdentifierName,\n  ): CodeFragment {\n    const argumentValues = argExprs.map((argument, index) => {\n      const prefix = options.argumentPrefixes?.[index] ?? `functionArgument${index + 1}`\n\n      return declareArgument({ prefix, argument })\n    })\n\n    return this.diagnostics.wrapFunctionCall(\n      helperName,\n      funcName,\n      argumentValues.map(argument => code`${argument}`),\n      source,\n    )\n  }\n\n  private isStaticOperand(value: unknown): boolean {\n    return isDeepStaticValue(value)\n  }\n\n  private compileStaticOperand(value: unknown, fallback: CodeFragment): CodeFragment {\n    return value !== undefined ? this.compileOperandCode(value) : fallback\n  }\n\n  /**\n   * Wraps a lazily-evaluated validation value (condition, message, details) in\n   * a named function expression. The expression compiles inside the function\n   * body so its statements and await tracking stay isolated from the enclosing\n   * generated function.\n   */\n  private compileReturnFunctionExpression(compileExpression: () => CodeFragment, name: string): CodeFragment {\n    let bodyUsesAwait = false\n\n    return this.generator.functionExpression(\n      name,\n      [],\n      functionGenerator => {\n        bodyUsesAwait = this.trackNestedFunctionAwait(() => {\n          const expression = this.withGeneratorScope(functionGenerator, compileExpression)\n\n          functionGenerator.return(expression)\n        })\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  /**\n   * Maps top-level reference namespaces (e.g. `data`, `session`, `params`) to\n   * their corresponding runtime context property.\n   */\n  namespaceToCtxCode(namespace: string): CodeFragment {\n    switch (namespace) {\n      case 'data':\n        return code`ctx.data`\n      case 'session':\n        return code`ctx.session`\n      case 'params':\n        return code`ctx.params`\n      case 'query':\n        return code`ctx.query`\n      case 'request':\n        return code`ctx.request`\n      case 'post':\n        return code`ctx.post`\n      default:\n        return code`ctx[${namespace}]`\n    }\n  }\n\n  /**\n   * Checks whether a value is an AST node that has been registered in the node\n   * index and can be compiled into a JavaScript expression.\n   */\n  isCompilableNode(value: unknown): value is ASTNode {\n    return isASTNode(value) && 'id' in value\n  }\n\n  /**\n   * Checks whether a value is a template node (an expression node embedded\n   * inside an authored value such as a block property or hook argument).\n   */\n  isTemplateNode(value: unknown): value is TemplateNode {\n    return value !== null &&\n      value !== undefined &&\n      typeof value === 'object' &&\n      (value as Record<string, unknown>).type === ASTNodeType.TEMPLATE\n  }\n}\n","import AssignmentCodeNode from '../statements/AssignmentCodeNode'\nimport ArrayExpressionToken from '../fragments/ArrayExpressionToken'\nimport BlankLineCodeNode from '../statements/BlankLineCodeNode'\nimport BreakCodeNode from '../statements/BreakCodeNode'\nimport CallExpressionToken from '../fragments/CallExpressionToken'\nimport { CodeFragment, code, joinCode, nil } from '../fragments/CodeFragment'\nimport { SourcePosition } from '../SourcePosition.type'\nimport CommentCodeNode from '../statements/CommentCodeNode'\nimport ContinueCodeNode from '../statements/ContinueCodeNode'\nimport DeclarationCodeNode from '../statements/DeclarationCodeNode'\nimport DirectiveCodeNode from '../statements/DirectiveCodeNode'\nimport ExpressionCodeNode from '../statements/ExpressionCodeNode'\nimport ForRangeCodeNode from '../statements/ForRangeCodeNode'\nimport FunctionCodeNode from '../statements/FunctionCodeNode'\nimport FunctionExpressionToken from '../fragments/FunctionExpressionToken'\nimport CodeNode from '../statements/CodeNode'\nimport IfCodeNode from '../statements/IfCodeNode'\nimport ObjectExpressionToken from '../fragments/ObjectExpressionToken'\nimport PositionedCodeNode from '../statements/PositionedCodeNode'\nimport PositionedCodeToken from '../fragments/PositionedCodeToken'\nimport ReturnCodeNode from '../statements/ReturnCodeNode'\nimport ScopeCodeNode from '../statements/ScopeCodeNode'\nimport ThrowCodeNode from '../statements/ThrowCodeNode'\nimport TryCatchCodeNode from '../statements/TryCatchCodeNode'\nimport WhileCodeNode from '../statements/WhileCodeNode'\n\nconst MAX_READABLE_LINE_LENGTH = 120\n\n/**\n * Renders the code-node tree (the intermediate representation built by `CodeGenerator`) into\n * JavaScript text and source-map segments in one pass.\n */\n\nexport interface SourceMapSegment {\n  readonly generatedColumn: number\n  readonly position: SourcePosition\n}\n\nexport interface RenderedSource {\n  readonly source: string\n  readonly segmentsByLine: readonly (readonly SourceMapSegment[])[]\n}\n\nexport enum GeneratedCodeStyle {\n  READABLE = 'readable',\n  COMPACT = 'compact',\n}\n\nexport interface SourceRendererOptions {\n  readonly style?: GeneratedCodeStyle\n}\n\nexport default class SourceRenderer {\n  private readonly lines: string[] = []\n\n  private readonly segmentsByLine: SourceMapSegment[][] = []\n\n  private readonly style: GeneratedCodeStyle\n\n  constructor(options: SourceRendererOptions = {}) {\n    this.style = options.style ?? GeneratedCodeStyle.READABLE\n  }\n\n  render(nodes: readonly CodeNode[]): RenderedSource {\n    this.renderBody(nodes, 0, [])\n\n    return { source: this.lines.join('\\n'), segmentsByLine: this.segmentsByLine }\n  }\n\n  renderCode(value: CodeFragment): RenderedSource {\n    this.writeCodeLine(value, 0)\n\n    return { source: this.lines.join('\\n'), segmentsByLine: this.segmentsByLine }\n  }\n\n  private renderBody(nodes: readonly CodeNode[], depth: number, inheritedPositions: readonly SourcePosition[]): void {\n    nodes.forEach((node, index) => {\n      this.renderGeneratedNode(node, depth, inheritedPositions)\n\n      if (this.shouldSeparateNodes(node, nodes[index + 1])) {\n        this.writeBlankLine()\n      }\n    })\n  }\n\n  private renderGeneratedNode(node: CodeNode, depth: number, positions: readonly SourcePosition[] = []): void {\n    if (node instanceof PositionedCodeNode) {\n      this.renderGeneratedNode(node.node, depth, [...node.positions, ...positions])\n\n      return\n    }\n\n    const writeHeader = (value: CodeFragment): void => this.writeCodeLine(value, depth, positions)\n\n    if (node instanceof DirectiveCodeNode) {\n      writeHeader(code`${node.value};`)\n\n      return\n    }\n\n    if (node instanceof DeclarationCodeNode) {\n      const value = node.value === undefined ? nil : code` = ${node.value}`\n\n      writeHeader(code`${CodeFragment.trusted(node.declarationKind)} ${node.name}${value};`)\n\n      return\n    }\n\n    if (node instanceof AssignmentCodeNode) {\n      writeHeader(code`${node.target} = ${node.value};`)\n\n      return\n    }\n\n    if (node instanceof ExpressionCodeNode) {\n      writeHeader(code`${node.expression};`)\n\n      return\n    }\n\n    if (node instanceof ReturnCodeNode) {\n      const value = node.value === undefined ? nil : code` ${node.value}`\n\n      writeHeader(code`return${value};`)\n\n      return\n    }\n\n    if (node instanceof ThrowCodeNode) {\n      writeHeader(code`throw ${node.value};`)\n\n      return\n    }\n\n    if (node instanceof BreakCodeNode) {\n      writeHeader(code`break;`)\n\n      return\n    }\n\n    if (node instanceof ContinueCodeNode) {\n      writeHeader(code`continue;`)\n\n      return\n    }\n\n    if (node instanceof BlankLineCodeNode) {\n      this.writeBlankLine()\n\n      return\n    }\n\n    if (node instanceof CommentCodeNode) {\n      this.writeCommentLine(node.banner ? `// --- ${node.text} ---` : `// ${node.text}`, depth)\n\n      return\n    }\n\n    if (node instanceof ScopeCodeNode) {\n      writeHeader(code`{`)\n      this.renderBody(node.body, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n\n      return\n    }\n\n    if (node instanceof IfCodeNode) {\n      this.writeIf(node, depth, positions)\n\n      return\n    }\n\n    if (node instanceof WhileCodeNode) {\n      writeHeader(code`while (${node.condition}) {`)\n      this.renderBody(node.body, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n\n      return\n    }\n\n    if (node instanceof ForRangeCodeNode) {\n      writeHeader(code`for (let ${node.index} = ${node.from}; ${node.index} < ${node.to}; ${node.index}++) {`)\n      this.renderBody(node.body, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n\n      return\n    }\n\n    if (node instanceof FunctionCodeNode) {\n      const asyncKeyword = node.async ? CodeFragment.trusted('async ') : nil\n\n      writeHeader(code`${asyncKeyword}function ${node.name}(${joinCode(node.parameters)}) {`)\n      this.renderBody(node.body, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n\n      return\n    }\n\n    if (node instanceof TryCatchCodeNode) {\n      writeHeader(code`try {`)\n      this.renderBody(node.tryBody, depth + 1, positions)\n      this.writeCodeLine(code`} catch (${node.errorName}) {`, depth, positions)\n      this.renderBody(node.catchBody, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n\n      return\n    }\n\n    throwUnhandledGeneratedNode(node)\n  }\n\n  private writeIf(node: IfCodeNode, depth: number, positions: readonly SourcePosition[]): void {\n    node.branches.forEach((branch, index) => {\n      const keyword = index === 0 ? CodeFragment.trusted('if') : CodeFragment.trusted('else if')\n      const header = code`${keyword} (${branch.condition}) {`\n\n      this.writeCodeLine(header, depth, positions)\n      this.renderBody(branch.body, depth + 1, positions)\n      this.writeCodeLine(code`}`, depth)\n    })\n\n    if (node.elseBody === undefined) {\n      return\n    }\n\n    this.writeCodeLine(code`else {`, depth, positions)\n    this.renderBody(node.elseBody, depth + 1, positions)\n    this.writeCodeLine(code`}`, depth)\n  }\n\n  private writeBlankLine(): void {\n    if (this.style === GeneratedCodeStyle.COMPACT) {\n      return\n    }\n\n    this.lines.push('')\n    this.segmentsByLine.push([])\n  }\n\n  private writeCommentLine(text: string, depth: number): void {\n    if (this.style === GeneratedCodeStyle.COMPACT) {\n      return\n    }\n\n    this.writeLine(text, depth)\n  }\n\n  private writeLine(text: string, depth: number): void {\n    const indent = this.style === GeneratedCodeStyle.COMPACT ? '' : '  '.repeat(depth)\n\n    this.lines.push(text.length === 0 ? '' : indent + text)\n    this.segmentsByLine.push([])\n  }\n\n  private writeCodeLine(value: CodeFragment, depth: number, fallbackPositions: readonly SourcePosition[] = []): void {\n    const indentation = (lineDepth: number): string =>\n      this.style === GeneratedCodeStyle.COMPACT ? '' : '  '.repeat(lineDepth)\n    let currentDepth = depth\n    let line = indentation(currentDepth)\n    let segments: SourceMapSegment[] = []\n\n    const flushLine = (nextDepth: number = currentDepth): void => {\n      this.lines.push(line)\n      this.segmentsByLine.push(segments)\n      currentDepth = nextDepth\n      line = indentation(currentDepth)\n      segments = []\n      fallbackPositions.forEach(writePosition)\n    }\n\n    const writePosition = (position: SourcePosition): void => {\n      const previousColumn = segments.length === 0 ? -1 : segments[segments.length - 1].generatedColumn\n\n      segments.push({ generatedColumn: Math.max(line.length, previousColumn + 1), position })\n    }\n\n    // Source maps treat the last preceding segment as active until the next one.\n    // Writing the broad fallback positions first means a more precise position\n    // from a nested token can override them for the actual executable range.\n    fallbackPositions.forEach(writePosition)\n\n    const renderItems = (\n      items: CodeFragment['items'],\n      inheritedPositions: readonly SourcePosition[],\n      positionsAlreadyWritten = false,\n    ): void => {\n      let inheritedPositionsWritten = positionsAlreadyWritten\n\n      const writeInheritedPositions = (): void => {\n        if (inheritedPositionsWritten) {\n          return\n        }\n\n        inheritedPositions.forEach(writePosition)\n        inheritedPositionsWritten = true\n      }\n\n      items.forEach(item => {\n        if (item instanceof PositionedCodeToken) {\n          renderItems(item.value.items, [...item.positions, ...inheritedPositions])\n\n          return\n        }\n\n        if (item instanceof FunctionExpressionToken) {\n          const asyncKeyword = item.async ? 'async ' : ''\n          const functionName = item.name === undefined ? '' : ` ${item.name.value}`\n          const parameters = item.parameters.map(parameter => parameter.value).join(', ')\n\n          writeInheritedPositions()\n          line += `${asyncKeyword}function${functionName}(${parameters}) {`\n          flushLine(currentDepth)\n          this.renderBody(\n            item.body,\n            currentDepth + 1,\n            inheritedPositions.length > 0 ? inheritedPositions : fallbackPositions,\n          )\n          line += '}'\n\n          return\n        }\n\n        if (item instanceof CallExpressionToken) {\n          writeInheritedPositions()\n          this.renderCallExpression(\n            item,\n            inheritedPositions,\n            currentDepth,\n            line.length,\n            part => {\n              line += part\n            },\n            flushLine,\n            renderItems,\n          )\n\n          return\n        }\n\n        if (item instanceof ArrayExpressionToken) {\n          writeInheritedPositions()\n          this.renderArrayExpression(\n            item,\n            inheritedPositions,\n            currentDepth,\n            part => {\n              line += part\n            },\n            flushLine,\n            renderItems,\n          )\n\n          return\n        }\n\n        if (item instanceof ObjectExpressionToken) {\n          writeInheritedPositions()\n          this.renderObjectExpression(\n            item,\n            inheritedPositions,\n            currentDepth,\n            part => {\n              line += part\n            },\n            flushLine,\n            renderItems,\n          )\n\n          return\n        }\n\n        const parts = item.split('\\n')\n\n        parts.forEach((part, index) => {\n          if (index > 0) {\n            flushLine()\n            inheritedPositionsWritten = false\n          }\n\n          if (part.length > 0) {\n            writeInheritedPositions()\n          }\n\n          line += part\n        })\n      })\n    }\n\n    renderItems(value.items, [])\n\n    flushLine()\n  }\n\n  private renderCallExpression(\n    token: CallExpressionToken,\n    inheritedPositions: readonly SourcePosition[],\n    depth: number,\n    currentLineLength: number,\n    write: (value: string) => void,\n    flushLine: (nextDepth?: number) => void,\n    renderItems: (\n      items: CodeFragment['items'],\n      positions: readonly SourcePosition[],\n      positionsAlreadyWritten?: boolean,\n    ) => void,\n  ): void {\n    renderItems(token.target.items, inheritedPositions, true)\n    write('(')\n\n    if (!this.shouldRenderCallAcrossLines(token, currentLineLength)) {\n      token.args.forEach((arg, index) => {\n        if (index > 0) {\n          write(', ')\n        }\n\n        renderItems(arg.items, inheritedPositions, true)\n      })\n      write(')')\n\n      return\n    }\n\n    flushLine(depth + 1)\n    token.args.forEach((arg, index) => {\n      renderItems(arg.items, inheritedPositions)\n\n      if (index < token.args.length - 1) {\n        write(',')\n      }\n\n      flushLine(index < token.args.length - 1 ? depth + 1 : depth)\n    })\n    write(')')\n  }\n\n  private renderArrayExpression(\n    token: ArrayExpressionToken,\n    inheritedPositions: readonly SourcePosition[],\n    depth: number,\n    write: (value: string) => void,\n    flushLine: (nextDepth?: number) => void,\n    renderItems: (\n      items: CodeFragment['items'],\n      positions: readonly SourcePosition[],\n      positionsAlreadyWritten?: boolean,\n    ) => void,\n  ): void {\n    write('[')\n\n    if (!this.shouldRenderAcrossLines(token)) {\n      token.values.forEach((value, index) => {\n        if (index > 0) {\n          write(', ')\n        }\n\n        renderItems(value.items, inheritedPositions, true)\n      })\n      write(']')\n\n      return\n    }\n\n    flushLine(depth + 1)\n    token.values.forEach((value, index) => {\n      renderItems(value.items, inheritedPositions)\n\n      if (index < token.values.length - 1) {\n        write(',')\n      }\n\n      flushLine(index < token.values.length - 1 ? depth + 1 : depth)\n    })\n    write(']')\n  }\n\n  private renderObjectExpression(\n    token: ObjectExpressionToken,\n    inheritedPositions: readonly SourcePosition[],\n    depth: number,\n    write: (value: string) => void,\n    flushLine: (nextDepth?: number) => void,\n    renderItems: (\n      items: CodeFragment['items'],\n      positions: readonly SourcePosition[],\n      positionsAlreadyWritten?: boolean,\n    ) => void,\n  ): void {\n    if (!this.shouldRenderAcrossLines(token)) {\n      const spacing = token.properties.length === 0 ? '' : ' '\n\n      write(`{${spacing}`)\n      token.properties.forEach((property, index) => {\n        if (index > 0) {\n          write(', ')\n        }\n\n        renderItems(property.key.items, inheritedPositions, true)\n        write(': ')\n        renderItems(property.value.items, inheritedPositions, true)\n      })\n      write(`${spacing}}`)\n\n      return\n    }\n\n    write('{')\n    flushLine(depth + 1)\n    token.properties.forEach((property, index) => {\n      renderItems(property.key.items, inheritedPositions)\n      write(': ')\n      renderItems(property.value.items, inheritedPositions, true)\n\n      if (index < token.properties.length - 1) {\n        write(',')\n      }\n\n      flushLine(index < token.properties.length - 1 ? depth + 1 : depth)\n    })\n    write('}')\n  }\n\n  private shouldRenderAcrossLines(token: ArrayExpressionToken | ObjectExpressionToken): boolean {\n    if (this.style === GeneratedCodeStyle.COMPACT) {\n      return false\n    }\n\n    if (token instanceof ArrayExpressionToken) {\n      return token.values.some(value => this.containsLineStructure(value))\n    }\n\n    return token.properties.length > 2 || token.properties.some(property => this.containsLineStructure(property.value))\n  }\n\n  private shouldRenderCallAcrossLines(token: CallExpressionToken, currentLineLength: number): boolean {\n    if (this.style === GeneratedCodeStyle.COMPACT) {\n      return false\n    }\n\n    if (token.args.some(arg => this.containsLineStructure(arg))) {\n      return true\n    }\n\n    if (this.containsLineStructure(token.target)) {\n      return false\n    }\n\n    const argumentsLength = token.args.reduce((length, arg) => length + arg.toString().length, 0)\n    const separatorsLength = Math.max(token.args.length - 1, 0) * 2\n    const callLength = token.target.toString().length + argumentsLength + separatorsLength + 2\n\n    return currentLineLength + callLength > MAX_READABLE_LINE_LENGTH\n  }\n\n  private containsLineStructure(value: CodeFragment): boolean {\n    return value.items.some(item => {\n      if (typeof item === 'string') {\n        return item.includes('\\n')\n      }\n\n      if (item instanceof FunctionExpressionToken) {\n        return true\n      }\n\n      if (item instanceof CallExpressionToken) {\n        return this.shouldRenderCallAcrossLines(item, 0)\n      }\n\n      if (item instanceof PositionedCodeToken) {\n        return this.containsLineStructure(item.value)\n      }\n\n      if (item instanceof ArrayExpressionToken) {\n        return item.values.some(arrayValue => this.containsLineStructure(arrayValue))\n      }\n\n      return item.properties.some(property => this.containsLineStructure(property.value))\n    })\n  }\n\n  private shouldSeparateNodes(node: CodeNode, nextNode: CodeNode | undefined): boolean {\n    if (this.style === GeneratedCodeStyle.COMPACT || nextNode === undefined) {\n      return false\n    }\n\n    const current = this.unwrapPositionedNode(node)\n    const next = this.unwrapPositionedNode(nextNode)\n\n    if (next instanceof BlankLineCodeNode) {\n      return false\n    }\n\n    if (current instanceof DeclarationCodeNode) {\n      return !(next instanceof DeclarationCodeNode)\n    }\n\n    return current instanceof ForRangeCodeNode ||\n      current instanceof IfCodeNode ||\n      current instanceof TryCatchCodeNode ||\n      current instanceof WhileCodeNode\n  }\n\n  private unwrapPositionedNode(node: CodeNode): CodeNode {\n    return node instanceof PositionedCodeNode ? this.unwrapPositionedNode(node.node) : node\n  }\n}\n\nfunction throwUnhandledGeneratedNode(value: CodeNode): never {\n  throw new Error(`Unhandled generated code node: ${String(value)}`)\n}\n","import { SourceMapSegment } from './SourceRenderer'\n\n/**\n * Encodes renderer source-map segments as an inline `data:` source-map URL so\n * debuggers can bind definition-file breakpoints onto compiled functions.\n * `lineOffset` prepends empty mapping lines for the wrapper V8 builds around\n * `new Function` bodies, aligning generated line indexes with the final script.\n */\nexport const encodeInlineSourceMap = (\n  segmentsByLine: readonly (readonly SourceMapSegment[])[],\n  lineOffset: number,\n): string => {\n  const sources: string[] = []\n  const sourceIndexes = new Map<string, number>()\n\n  const sourceIndexOf = (file: string): number => {\n    const existing = sourceIndexes.get(file)\n\n    if (existing !== undefined) {\n      return existing\n    }\n\n    sources.push(file)\n    sourceIndexes.set(file, sources.length - 1)\n\n    return sources.length - 1\n  }\n\n  // Generated-column deltas reset per line; source fields carry across the\n  // whole mappings string. Source-map coordinates are 0-based; captured\n  // positions are 1-based.\n  let previousSourceIndex = 0\n  let previousSourceLine = 0\n  let previousSourceColumn = 0\n\n  const mappingLines = segmentsByLine.map(segments => {\n    let previousGeneratedColumn = 0\n\n    return (\n      segments\n        .map(segment => {\n          const sourceIndex = sourceIndexOf(segment.position.file)\n          const encoded = [\n            segment.generatedColumn - previousGeneratedColumn,\n            sourceIndex - previousSourceIndex,\n            segment.position.line - 1 - previousSourceLine,\n            segment.position.column - 1 - previousSourceColumn,\n          ]\n            .map(encodeVlq)\n            .join('')\n\n          previousGeneratedColumn = segment.generatedColumn\n          previousSourceIndex = sourceIndex\n          previousSourceLine = segment.position.line - 1\n          previousSourceColumn = segment.position.column - 1\n\n          return encoded\n        })\n        .join(',')\n    )\n  })\n\n  const mappings = [...Array<string>(lineOffset).fill(''), ...mappingLines].join(';')\n  const sourceMap = { version: 3, sources, names: [], mappings }\n\n  return `data:application/json;base64,${Buffer.from(JSON.stringify(sourceMap), 'utf8').toString('base64')}`\n}\n\nconst VLQ_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n\n/* eslint-disable no-bitwise -- VLQ is a bit-packing format */\nconst encodeVlq = (value: number): string => {\n  let remaining = value < 0 ? (-value << 1) | 1 : value << 1\n  let encoded = ''\n\n  do {\n    let digit = remaining & 31\n\n    remaining >>>= 5\n\n    if (remaining > 0) {\n      digit |= 32\n    }\n\n    encoded += VLQ_ALPHABET[digit]\n  } while (remaining > 0)\n\n  return encoded\n}\n","export const RENDER_BLOCK_BRAND: symbol = Symbol.for('forge:RenderBlock')\n","import { z, type ZodType } from 'zod'\nimport { RENDER_BLOCK_BRAND } from '../../../concerns/render/contracts/renderBlock.brand'\nimport { FunctionType } from '../../../../authoring/types/enums'\nimport type { IteratorBudgetContract } from '../../contracts/runtime/iteratorBudget.type'\n\ninterface AnswerHistory {\n  current: unknown\n  parsed?: unknown\n  mutations: { value: unknown; source: string }[]\n}\n\ninterface RenderAnswerHistory {\n  current: unknown\n  parsed?: unknown\n  mutations?: { value: unknown; source: string }[]\n}\n\ninterface AnswerHistoryContext {\n  answers: Record<string, AnswerHistory>\n}\n\ninterface RenderFieldValueContext {\n  answers: Record<string, RenderAnswerHistory | undefined>\n  request: Record<string, unknown>\n}\n\ninterface RenderFieldFailureContext extends ComponentInputContext {\n  fieldFailures: Record<string, unknown[]>\n  fieldFailureAnchors: Record<string, string>\n}\n\nexport interface FunctionRegistryLookupEntry {\n  evaluate(...args: unknown[]): unknown\n  inputSchema?: ZodType\n  argumentsSchema?: ZodType\n  outputSchema?: ZodType\n  functionType?: FunctionType\n}\n\ninterface FunctionEvaluationContext {\n  conditions: {\n    get(name: string): FunctionRegistryLookupEntry\n  }\n}\n\ninterface IteratorBudgetContext {\n  iteratorBudget: IteratorBudgetContract\n}\n\ninterface ComponentRegistryLookupEntry {\n  inputSchema?: ZodType\n  errorAnchor?(props: Record<string, unknown>): string | undefined\n}\n\ninterface ComponentInputContext {\n  components: {\n    get(variant: string): ComponentRegistryLookupEntry | undefined\n  }\n}\n\ninterface FieldPreparationContext extends AnswerHistoryContext, ComponentInputContext {\n  post: Record<string, unknown>\n}\n\n/** One entry of a generated step's `fieldDefinitions` array; the callbacks carry the compiled authored expressions. */\ninterface PreparedFieldDefinition {\n  code: string\n  component: string\n  acceptsMultipleValues: boolean\n  validatesInput: boolean\n  formatSubmittedValue?: (value: unknown) => unknown\n  evaluateDependentWhen?: () => unknown\n  resolveDefaultValue?: () => unknown\n  parseStoredValue?: (value: unknown) => unknown\n}\n\ninterface PreparedFieldAnswer {\n  code: string\n  mode: 'POST' | 'GET'\n  current: unknown\n  parsed: unknown\n  mutations: { value: unknown; source: string }[]\n}\n\ninterface RuntimeDiagnosticState {\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n  readonly definedAt?: string\n}\n\ninterface RuntimeEvaluationDiagnostics {\n  current: RuntimeDiagnosticState | undefined\n  resolve(reference: number): RuntimeDiagnosticState | undefined\n  wrap(error: unknown, reference?: number): unknown\n}\n\ninterface RuntimeValidationRule {\n  readonly condition?: () => unknown\n  readonly details?: unknown | (() => unknown)\n  readonly evaluate?: () => unknown\n  readonly groups?: unknown\n  readonly message?: unknown | (() => unknown)\n  readonly passed?: unknown\n  readonly submissionOnly?: boolean\n}\n\ninterface RuntimeValidationFailure {\n  readonly rule: RuntimeValidationRule\n  readonly message: unknown\n  readonly details: unknown\n}\n\n/** Identifies the field a validation failure belongs to; template fields compute their block id per iteration. */\ninterface FieldValidationIdentity {\n  readonly blockId: unknown\n  readonly blockCode: unknown\n}\n\ninterface RuntimeDomainValidationFailure {\n  readonly passed: false\n  readonly message: unknown\n  readonly submissionOnly: boolean\n  readonly groups: unknown\n  readonly details: unknown\n}\n\ninterface RuntimeFieldValidationFailure extends RuntimeDomainValidationFailure {\n  readonly blockId: unknown\n  readonly blockCode: unknown\n}\n\nconst VALIDATION_CONDITION_FUNCTION_TYPE = 'FunctionType.Condition'\ntype MaybeAsync<TValue> = TValue | PromiseLike<TValue>\n\nexport interface GeneratedFunctionRuntimeLibrary {\n  renderBlockBrand: symbol\n  isThenable(value: unknown): value is PromiseLike<unknown>\n  consumeIteratorIteration(ctx: IteratorBudgetContext): void\n  ensureAnswerHistory(ctx: AnswerHistoryContext, code: string): AnswerHistory\n  pushAnswerMutation(answerHistory: AnswerHistory, value: unknown, source: string): void\n  normalizePostValue(rawValue: unknown, multiple: boolean): unknown\n  checkComponentInputValue(ctx: ComponentInputContext, variant: string, value: unknown, multiple: boolean): unknown\n  groupFieldDefinitionsByCode(definitions: readonly PreparedFieldDefinition[]): PreparedFieldDefinition[][]\n  preparePostedFieldAnswerGroup(\n    ctx: FieldPreparationContext,\n    fields: readonly PreparedFieldDefinition[],\n  ): Promise<PreparedFieldAnswer>\n  prepareStoredFieldAnswerGroup(\n    ctx: AnswerHistoryContext,\n    fields: readonly PreparedFieldDefinition[],\n  ): Promise<PreparedFieldAnswer>\n  isTransformerTypeError(error: unknown): boolean\n  resolveFieldValue(ctx: RenderFieldValueContext, blockProps: Record<string, unknown>): void\n  resolveFieldFailures(\n    ctx: RenderFieldFailureContext,\n    blockId: unknown,\n    variant: string,\n    blockProps: Record<string, unknown>,\n  ): void\n  evaluateFunction(\n    ctx: FunctionEvaluationContext,\n    diagnostics: RuntimeEvaluationDiagnostics | undefined,\n    diagnosticReference: number,\n    functionName: string,\n    args: unknown[],\n  ): unknown\n  collectFieldValidationFailures(\n    results: unknown,\n    ruleIsActive: (rule: RuntimeValidationRule) => boolean,\n    identity: FieldValidationIdentity,\n  ): MaybeAsync<RuntimeFieldValidationFailure[]>\n  collectDomainValidationFailures(\n    results: unknown,\n    ruleIsActive: (rule: RuntimeValidationRule) => boolean,\n  ): MaybeAsync<RuntimeDomainValidationFailure[]>\n}\n\nexport const generatedFunctionRuntimeLibrary: GeneratedFunctionRuntimeLibrary = {\n  renderBlockBrand: RENDER_BLOCK_BRAND,\n  isThenable,\n\n  consumeIteratorIteration(ctx) {\n    ctx.iteratorBudget.consume()\n  },\n\n  // Answer-preparation functions are detached from this object by generated\n  // code (`mode === \"POST\" ? _forgeHelpers.preparePostedFieldAnswerGroup : ...`),\n  // so they and everything they call live as module functions free of `this`.\n  ensureAnswerHistory,\n  pushAnswerMutation,\n  normalizePostValue,\n  checkComponentInputValue,\n  groupFieldDefinitionsByCode,\n  preparePostedFieldAnswerGroup,\n  prepareStoredFieldAnswerGroup,\n  isTransformerTypeError,\n\n  resolveFieldValue(ctx, blockProps) {\n    const fieldCode = blockProps.code\n\n    if (typeof fieldCode !== 'string') {\n      return\n    }\n\n    const answerHistory = ctx.answers[fieldCode]\n\n    if (ctx.request.method === 'POST') {\n      blockProps.value = resolvePostFieldValue(answerHistory)\n\n      return\n    }\n\n    blockProps.value = resolveGetFieldValue(answerHistory, blockProps.defaultValue)\n  },\n\n  resolveFieldFailures(ctx, blockId, variant, blockProps) {\n    // Validation shows for the whole step at once: when any field failed, every\n    // field carries errors - its own failures, or [] when it passed. When nothing\n    // failed there is no errors property, matching the un-validated render.\n    if (Object.keys(ctx.fieldFailures).length === 0) {\n      return\n    }\n\n    const failures = ctx.fieldFailures[String(blockId)] ?? []\n\n    blockProps.errors = failures\n\n    if (failures.length === 0) {\n      return\n    }\n\n    // The failing block instance's document anchor, for the error summary link.\n    // The component owns the ids it renders, so it declares how to derive the\n    // anchor; without a declaration the anchor is the field code.\n    const anchor = ctx.components.get(variant)?.errorAnchor?.(blockProps) ?? blockProps.code\n\n    if (typeof anchor === 'string') {\n      ctx.fieldFailureAnchors[String(blockId)] = anchor\n    }\n  },\n\n  evaluateFunction(ctx, diagnostics, diagnosticReference, functionName, args) {\n    const entry = ctx.conditions.get(functionName)\n    const previous = enterDiagnostics(diagnostics, diagnosticReference)\n\n    try {\n      const shortCircuit = precheckShortCircuit(entry, functionName, args)\n\n      if (shortCircuit !== undefined) {\n        exitDiagnostics(diagnostics, previous)\n\n        return shortCircuit.value\n      }\n\n      const result = entry.evaluate(...args)\n\n      if (isThenable(result)) {\n        return Promise.resolve(result).then(\n          resolved => {\n            try {\n              validateOutput(entry, functionName, resolved)\n\n              return resolved\n            } catch (error) {\n              throw wrapDiagnosticError(diagnostics, diagnosticReference, error)\n            } finally {\n              exitDiagnostics(diagnostics, previous)\n            }\n          },\n          error => {\n            exitDiagnostics(diagnostics, previous)\n\n            throw wrapDiagnosticError(diagnostics, diagnosticReference, error)\n          },\n        )\n      }\n\n      validateOutput(entry, functionName, result)\n      exitDiagnostics(diagnostics, previous)\n\n      return result\n    } catch (error) {\n      exitDiagnostics(diagnostics, previous)\n\n      throw wrapDiagnosticError(diagnostics, diagnosticReference, error)\n    }\n  },\n\n  collectFieldValidationFailures(results, ruleIsActive, identity) {\n    return mapMaybeAsync(collectValidationFailures(results, ruleIsActive), failures =>\n      failures.map(failure => toFieldValidationFailure(failure, identity)),\n    )\n  },\n\n  collectDomainValidationFailures(results, ruleIsActive) {\n    return mapMaybeAsync(collectValidationFailures(results, ruleIsActive), failures =>\n      failures.map(toDomainValidationFailure),\n    )\n  },\n}\n\nfunction ensureAnswerHistory(ctx: AnswerHistoryContext, code: string): AnswerHistory {\n  let answerHistory = ctx.answers[code]\n\n  if (!answerHistory) {\n    answerHistory = { current: undefined, mutations: [] }\n    ctx.answers[code] = answerHistory\n  }\n\n  return answerHistory\n}\n\nfunction pushAnswerMutation(answerHistory: AnswerHistory, value: unknown, source: string): void {\n  answerHistory.mutations.push({ value, source })\n  answerHistory.current = value\n}\n\nfunction normalizePostValue(rawValue: unknown, multiple: boolean): unknown {\n  if (multiple) {\n    if (Array.isArray(rawValue)) {\n      return rawValue\n    }\n\n    return rawValue !== undefined && rawValue !== null ? [rawValue] : []\n  }\n\n  if (!Array.isArray(rawValue)) {\n    return rawValue\n  }\n\n  return rawValue.find(\n    value => value !== undefined && value !== null && (typeof value !== 'string' || value.trim() !== ''),\n  )\n}\n\n/**\n * Checks a submitted value against the component variant's `inputSchema` after\n * normalisation. A value that fails the schema can't have come from the\n * rendered form, so it's replaced with an empty value (`[]` for multi-value\n * fields, `undefined` for single-value fields) rather than throwing. A passing\n * value uses the schema's parsed output so its sanitisation and transformations\n * are retained. An unanswered value, an unknown variant, or a variant without\n * a schema is left untouched.\n */\nfunction checkComponentInputValue(\n  ctx: ComponentInputContext,\n  variant: string,\n  value: unknown,\n  multiple: boolean,\n): unknown {\n  if (value === undefined) {\n    return value\n  }\n\n  const entry = ctx.components.get(variant)\n\n  if (entry === undefined || entry.inputSchema === undefined) {\n    return value\n  }\n\n  const parsed = entry.inputSchema.safeParse(value)\n\n  if (parsed.success) {\n    return parsed.data\n  }\n\n  return multiple ? [] : undefined\n}\n\n/**\n * Groups same-code field definitions into variant groups, preserving\n * declaration order. Runs at request time because iterator template fields\n * only resolve their codes per request; entries without a resolvable code\n * each stay in their own group.\n */\nfunction groupFieldDefinitionsByCode(definitions: readonly PreparedFieldDefinition[]): PreparedFieldDefinition[][] {\n  const groups: PreparedFieldDefinition[][] = []\n  const groupsByCode = new Map<string, PreparedFieldDefinition[]>()\n\n  definitions.forEach(definition => {\n    const existingGroup = definition.code === undefined ? undefined : groupsByCode.get(definition.code)\n\n    if (existingGroup !== undefined) {\n      existingGroup.push(definition)\n\n      return\n    }\n\n    const group = [definition]\n\n    groups.push(group)\n    if (definition.code !== undefined) {\n      groupsByCode.set(definition.code, group)\n    }\n  })\n\n  return groups\n}\n\n/**\n * Picks the active owner of a same-code variant group: the first field in\n * declaration order whose `dependentWhen` holds (or which has none). Only the\n * owner runs preparation; inactive variants contribute nothing.\n */\nasync function findActiveFieldVariant(\n  fields: readonly PreparedFieldDefinition[],\n): Promise<PreparedFieldDefinition | undefined> {\n  // Sequential on purpose: first active variant in declaration order wins.\n  for (const field of fields) {\n    if (field.evaluateDependentWhen === undefined || (await field.evaluateDependentWhen())) {\n      return field\n    }\n  }\n\n  return undefined\n}\n\nasync function preparePostedFieldAnswerGroup(\n  ctx: FieldPreparationContext,\n  fields: readonly PreparedFieldDefinition[],\n): Promise<PreparedFieldAnswer> {\n  if (fields.length === 1) {\n    return preparePostedFieldAnswer(ctx, fields[0])\n  }\n\n  const activeField = await findActiveFieldVariant(fields)\n\n  if (activeField === undefined) {\n    // No variant is active, so the logical field clears its stale answer once.\n    pushAnswerMutation(ensureAnswerHistory(ctx, fields[0].code), undefined, 'dependentWhen')\n\n    return buildPreparedFieldAnswer(ctx, fields[0].code, 'POST')\n  }\n\n  await runPostedFieldPipeline(ctx, activeField)\n\n  return buildPreparedFieldAnswer(ctx, activeField.code, 'POST')\n}\n\nasync function prepareStoredFieldAnswerGroup(\n  ctx: AnswerHistoryContext,\n  fields: readonly PreparedFieldDefinition[],\n): Promise<PreparedFieldAnswer> {\n  if (fields.length === 1) {\n    return prepareStoredFieldAnswer(ctx, fields[0])\n  }\n\n  const activeField = await findActiveFieldVariant(fields)\n\n  if (activeField === undefined) {\n    // No variant is active: no defaults, no parsing, just the stored view.\n    return buildPreparedFieldAnswer(ctx, fields[0].code, 'GET')\n  }\n\n  return prepareStoredFieldAnswer(ctx, activeField)\n}\n\nasync function preparePostedFieldAnswer(\n  ctx: FieldPreparationContext,\n  field: PreparedFieldDefinition,\n): Promise<PreparedFieldAnswer> {\n  await runPostedFieldPipeline(ctx, field)\n\n  if (field.evaluateDependentWhen !== undefined) {\n    const dependentWhenResult = await field.evaluateDependentWhen()\n\n    if (!dependentWhenResult) {\n      pushAnswerMutation(ensureAnswerHistory(ctx, field.code), undefined, 'dependentWhen')\n    }\n  }\n\n  return buildPreparedFieldAnswer(ctx, field.code, 'POST')\n}\n\nasync function runPostedFieldPipeline(ctx: FieldPreparationContext, field: PreparedFieldDefinition): Promise<void> {\n  const answerHistory = ensureAnswerHistory(ctx, field.code)\n  let rawValue = normalizePostValue(ctx.post[field.code], field.acceptsMultipleValues)\n\n  if (field.validatesInput) {\n    rawValue = checkComponentInputValue(ctx, field.component, rawValue, field.acceptsMultipleValues)\n  }\n\n  pushAnswerMutation(answerHistory, rawValue, 'post')\n\n  if (field.formatSubmittedValue !== undefined) {\n    const formattedValue = await field.formatSubmittedValue(rawValue)\n\n    if (formattedValue !== rawValue) {\n      pushAnswerMutation(answerHistory, formattedValue, 'processed')\n    }\n  }\n}\n\nasync function prepareStoredFieldAnswer(\n  ctx: AnswerHistoryContext,\n  field: PreparedFieldDefinition,\n): Promise<PreparedFieldAnswer> {\n  let answerHistory: AnswerHistory | undefined = ctx.answers[field.code]\n\n  if (answerHistory?.current === undefined) {\n    answerHistory = ensureAnswerHistory(ctx, field.code)\n    const defaultValue = field.resolveDefaultValue === undefined ? undefined : await field.resolveDefaultValue()\n\n    pushAnswerMutation(answerHistory, defaultValue, 'default')\n  }\n\n  if (answerHistory.current !== undefined && field.parseStoredValue !== undefined) {\n    const parsedValue = await field.parseStoredValue(answerHistory.current)\n\n    if (parsedValue !== undefined) {\n      answerHistory.parsed = parsedValue\n    }\n  }\n\n  return buildPreparedFieldAnswer(ctx, field.code, 'GET')\n}\n\nfunction buildPreparedFieldAnswer(\n  ctx: AnswerHistoryContext,\n  fieldCode: string,\n  mode: 'POST' | 'GET',\n): PreparedFieldAnswer {\n  const preparedAnswerHistory: AnswerHistory | undefined = ctx.answers[fieldCode]\n\n  return {\n    code: fieldCode,\n    mode,\n    current: preparedAnswerHistory?.current,\n    parsed: preparedAnswerHistory?.parsed,\n    mutations: preparedAnswerHistory?.mutations.slice() ?? [],\n  }\n}\n\n/**\n * Runs a field's transformer thunks in order. A thunk returning `undefined`\n * keeps the previous value; a thunk throwing a TypeError (an authored\n * transformer rejecting the value's shape) reverts to the original value and\n * abandons the rest of the pipeline. Any other error propagates.\n */\nfunction isTransformerTypeError(error: unknown): boolean {\n  if (error instanceof TypeError) {\n    return true\n  }\n\n  return isRecord(error) && error.cause instanceof TypeError\n}\n\nfunction collectValidationFailures(\n  results: unknown,\n  ruleIsActive: (rule: RuntimeValidationRule) => boolean,\n): MaybeAsync<RuntimeValidationFailure[]> {\n  const failures: RuntimeValidationFailure[] = []\n  const validationStack = [results]\n  const collectNext = (): MaybeAsync<RuntimeValidationFailure[]> => {\n    const validationRule = takeNextActiveValidationRule(validationStack, ruleIsActive)\n\n    if (validationRule === undefined) {\n      return failures\n    }\n\n    return chainMaybeAsync(collectValidationRuleFailures(validationRule), ruleFailures => {\n      failures.push(...ruleFailures)\n\n      return collectNext()\n    })\n  }\n\n  return collectNext()\n}\n\nfunction collectValidationRuleFailures(rule: RuntimeValidationRule): MaybeAsync<RuntimeValidationFailure[]> {\n  return chainUnknownMaybeAsync(evaluateValidationRule(rule), validationPassed => {\n    if (validationPassed) {\n      return []\n    }\n\n    return chainUnknownMaybeAsync(resolveValidationRuleValue(rule, rule.message, ''), message =>\n      mapUnknownMaybeAsync(resolveValidationRuleValue(rule, rule.details, undefined), details => [\n        { rule, message, details },\n      ]),\n    )\n  })\n}\n\nfunction toFieldValidationFailure(\n  failure: RuntimeValidationFailure,\n  identity: FieldValidationIdentity,\n): RuntimeFieldValidationFailure {\n  return {\n    blockId: identity.blockId,\n    blockCode: identity.blockCode,\n    ...toDomainValidationFailure(failure),\n  }\n}\n\nfunction toDomainValidationFailure(failure: RuntimeValidationFailure): RuntimeDomainValidationFailure {\n  return {\n    passed: false,\n    message: failure.message,\n    submissionOnly: failure.rule.submissionOnly === true,\n    groups: failure.rule.groups,\n    details: failure.details,\n  }\n}\n\nexport function validateOutput(entry: FunctionRegistryLookupEntry, functionName: string, result: unknown): void {\n  if (entry.outputSchema === undefined) {\n    return\n  }\n\n  const parsed = entry.outputSchema.safeParse(result)\n\n  if (!parsed.success) {\n    throw new TypeError(`${functionName}: return value failed schema validation — ${parsed.error.message}`)\n  }\n}\n\nexport interface ShortCircuitOutcome {\n  value: unknown\n}\n\n/**\n * Validates a function call's arguments against its registry entry's schemas\n * before `evaluate` runs. Returns a short-circuit outcome (whose `value`\n * replaces the call result) or `undefined` to let the call proceed normally.\n *\n * Generators have no injected first parameter, so all their `args` are config.\n * Every other function kind (condition, transformer, effect) receives its\n * input value as `args[0]`, and `argumentsSchema` covers only the remaining\n * arguments. Invalid config arguments are always an author mistake and throw,\n * even when the input value is absent.\n *\n * An undefined input value never reaches a condition or transformer: a\n * condition can't hold (`false`) and a transformer has nothing to transform\n * (`undefined`), regardless of any `inputSchema`. `null` is a real value and\n * flows through. Effects still receive an undefined context, since it may be\n * exactly what they act on.\n *\n * For a defined value, `inputSchema` only fails softly for conditions -- a\n * wrongly-shaped field is a normal \"not valid yet\" outcome, so they return\n * `false`. Any other value schema failure is an author mistake and throws.\n */\nexport function precheckShortCircuit(\n  entry: FunctionRegistryLookupEntry,\n  functionName: string,\n  args: unknown[],\n): ShortCircuitOutcome | undefined {\n  const hasInjectedValue = entry.functionType !== FunctionType.GENERATOR\n  const configArgs = hasInjectedValue ? args.slice(1) : args\n\n  if (entry.argumentsSchema !== undefined) {\n    const parsed = entry.argumentsSchema.safeParse(configArgs)\n\n    if (!parsed.success) {\n      throw new TypeError(`${functionName}: arguments failed schema validation — ${parsed.error.message}`)\n    }\n  }\n\n  if (!hasInjectedValue) {\n    return undefined\n  }\n\n  if (args[0] === undefined) {\n    if (entry.functionType === FunctionType.CONDITION) {\n      return { value: false }\n    }\n\n    if (entry.functionType === FunctionType.TRANSFORMER) {\n      return { value: undefined }\n    }\n  }\n\n  if (entry.inputSchema === undefined) {\n    return undefined\n  }\n\n  if (entry.functionType === FunctionType.CONDITION) {\n    if (z.validate(entry.inputSchema, args[0])) {\n      return undefined\n    }\n\n    return { value: false }\n  }\n\n  const parsedValue = entry.inputSchema.safeParse(args[0])\n\n  if (parsedValue.success) {\n    return undefined\n  }\n\n  throw new TypeError(`${functionName}: value failed schema validation — ${parsedValue.error.message}`)\n}\n\nfunction enterDiagnostics(\n  diagnostics: RuntimeEvaluationDiagnostics | undefined,\n  diagnosticReference: number,\n): RuntimeDiagnosticState | undefined {\n  if (diagnostics === undefined) {\n    return undefined\n  }\n\n  const previous = diagnostics.current\n  const metadata = diagnostics.resolve(diagnosticReference)\n\n  if (metadata !== undefined) {\n    diagnostics.current = metadata\n  }\n\n  return previous\n}\n\nfunction exitDiagnostics(\n  diagnostics: RuntimeEvaluationDiagnostics | undefined,\n  previous: RuntimeDiagnosticState | undefined,\n): void {\n  if (diagnostics !== undefined) {\n    diagnostics.current = previous\n  }\n}\n\nfunction wrapDiagnosticError(\n  diagnostics: RuntimeEvaluationDiagnostics | undefined,\n  diagnosticReference: number,\n  error: unknown,\n): unknown {\n  if (diagnostics === undefined) {\n    return error\n  }\n\n  return diagnostics.wrap(error, diagnosticReference)\n}\n\nfunction takeNextActiveValidationRule(\n  validationStack: unknown[],\n  ruleIsActive: (rule: RuntimeValidationRule) => boolean,\n): RuntimeValidationRule | undefined {\n  while (validationStack.length > 0) {\n    const candidate = validationStack.pop()\n\n    if (candidate === null || candidate === undefined) {\n      continue\n    }\n\n    if (Array.isArray(candidate)) {\n      candidate.toReversed().forEach(item => validationStack.push(item))\n\n      continue\n    }\n\n    const validationRule = candidate as RuntimeValidationRule\n\n    if (ruleIsActive(validationRule)) {\n      return validationRule\n    }\n  }\n\n  return undefined\n}\n\nfunction resolveValidationRuleValue(\n  rule: RuntimeValidationRule,\n  evaluate: unknown | (() => unknown),\n  fallback: unknown,\n): unknown {\n  if (typeof evaluate === 'function') {\n    return evaluate.call(rule)\n  }\n\n  return evaluate === undefined ? fallback : evaluate\n}\n\nfunction evaluateValidationRule(rule: RuntimeValidationRule): unknown {\n  if (typeof rule.condition === 'function') {\n    return evaluateValidationCondition(rule, rule.condition)\n  }\n\n  if (typeof rule.evaluate === 'function') {\n    return rule.evaluate.call(rule)\n  }\n\n  return rule.passed\n}\n\nfunction evaluateValidationCondition(rule: RuntimeValidationRule, condition: () => unknown): MaybeAsync<boolean> {\n  try {\n    const result = condition.call(rule)\n\n    if (isThenable(result)) {\n      return Promise.resolve(result).then(Boolean, error => {\n        if (isValidationConditionTypeError(error)) {\n          return false\n        }\n\n        throw error\n      })\n    }\n\n    return !!result\n  } catch (error) {\n    if (isValidationConditionTypeError(error)) {\n      return false\n    }\n\n    throw error\n  }\n}\n\nfunction isValidationConditionTypeError(error: unknown): boolean {\n  if (error instanceof TypeError) {\n    return true\n  }\n\n  if (!isRecord(error)) {\n    return false\n  }\n\n  return error.cause instanceof TypeError && error.functionType === VALIDATION_CONDITION_FUNCTION_TYPE\n}\n\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n  return value !== null &&\n    value !== undefined &&\n    (typeof value === 'object' || typeof value === 'function') &&\n    typeof (value as { then?: unknown }).then === 'function'\n}\n\nfunction chainMaybeAsync<TInput, TOutput>(\n  value: MaybeAsync<TInput>,\n  next: (value: TInput) => MaybeAsync<TOutput>,\n): MaybeAsync<TOutput> {\n  return isThenable(value) ? Promise.resolve(value).then(next) : next(value)\n}\n\nfunction mapMaybeAsync<TInput, TOutput>(\n  value: MaybeAsync<TInput>,\n  map: (value: TInput) => TOutput,\n): MaybeAsync<TOutput> {\n  return isThenable(value) ? Promise.resolve(value).then(map) : map(value)\n}\n\nfunction chainUnknownMaybeAsync<TOutput>(\n  value: unknown,\n  next: (value: unknown) => MaybeAsync<TOutput>,\n): MaybeAsync<TOutput> {\n  return isThenable(value) ? Promise.resolve(value).then(next) : next(value)\n}\n\nfunction mapUnknownMaybeAsync<TOutput>(value: unknown, map: (value: unknown) => TOutput): MaybeAsync<TOutput> {\n  return isThenable(value) ? Promise.resolve(value).then(map) : map(value)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction resolvePostFieldValue(answerHistory: RenderAnswerHistory | undefined): unknown {\n  const answerMutations = answerHistory?.mutations ?? []\n  let postMutationIndex = -1\n  let mutationIndex = answerMutations.length - 1\n\n  while (mutationIndex >= 0) {\n    const currentMutationIndex = mutationIndex\n    const mutation = answerMutations[currentMutationIndex]\n\n    mutationIndex -= 1\n\n    if (mutation?.source === 'post') {\n      postMutationIndex = currentMutationIndex\n      break\n    }\n  }\n\n  let shouldUsePostValue = postMutationIndex >= 0\n\n  if (shouldUsePostValue) {\n    let laterMutationIndex = postMutationIndex + 1\n\n    while (laterMutationIndex < answerMutations.length) {\n      const laterMutation = answerMutations[laterMutationIndex]\n\n      laterMutationIndex += 1\n\n      if (laterMutation?.source !== 'processed') {\n        shouldUsePostValue = false\n        break\n      }\n    }\n  }\n\n  if (shouldUsePostValue) {\n    return answerMutations[postMutationIndex]?.value\n  }\n\n  return answerHistory?.current\n}\n\nfunction resolveGetFieldValue(answerHistory: RenderAnswerHistory | undefined, defaultValue: unknown): unknown {\n  if (answerHistory?.parsed !== undefined) {\n    return answerHistory.parsed\n  }\n\n  if (answerHistory) {\n    return answerHistory.current\n  }\n\n  return defaultValue\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeCompilationErrorOptions {\n  readonly phase: string\n  readonly cause: unknown\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n}\n\nexport default class ForgeCompilationError extends ForgeBaseError {\n  readonly phase: string\n\n  readonly nodeId?: string\n\n  readonly functionName?: string\n\n  readonly functionType?: string\n\n  readonly cause: unknown\n\n  constructor(options: ForgeCompilationErrorOptions) {\n    super(`Failed to compile generated Forge ${options.phase} function`, options)\n    this.phase = options.phase\n    this.nodeId = options.nodeId\n    this.functionName = options.functionName\n    this.functionType = options.functionType\n    this.cause = options.cause\n  }\n}\n","import DiagnosticErrorFormatter from './DiagnosticErrorFormatter'\nimport ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeRuntimeEvaluationErrorOptions {\n  readonly phase: string\n  readonly cause: unknown\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n  readonly definedAt?: string\n}\n\nexport interface ForgeRuntimeEvaluationDiagnostics {\n  readonly phase: string\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n  readonly definedAt?: string\n}\n\nexport const FORGE_RUNTIME_EVALUATION_DIAGNOSTICS = Symbol.for('hmpps-forge.runtimeEvaluationDiagnostics')\n\n/**\n * Wraps a failure thrown while evaluating a compiled forge function. The\n * author's error stays pristine on `cause`; this wrapper renders the combined\n * story — the cause's author frames, folded forge frames, defined-at frames,\n * and the diagnostics block. `definedAt` holds the newline-joined defined-at\n * chain, innermost frame first.\n */\nexport default class ForgeRuntimeEvaluationError extends ForgeBaseError {\n  readonly phase: string\n\n  /** Mirrored from the cause so host error middleware keeps reading the author's HTTP status */\n  readonly status?: number\n\n  readonly statusCode?: number\n\n  readonly nodeId?: string\n\n  readonly functionName?: string\n\n  readonly functionType?: string\n\n  readonly definedAt?: string\n\n  readonly cause: unknown\n\n  constructor(options: ForgeRuntimeEvaluationErrorOptions) {\n    super(buildMessage(options), options)\n    this.phase = options.phase\n    this.nodeId = options.nodeId\n    this.functionName = options.functionName\n    this.functionType = options.functionType\n    this.definedAt = options.definedAt\n    this.cause = options.cause\n    this.status = readHttpStatus(options.cause)\n    this.statusCode = this.status\n    Object.defineProperty(this, FORGE_RUNTIME_EVALUATION_DIAGNOSTICS, {\n      value: {\n        phase: options.phase,\n        nodeId: options.nodeId,\n        formattedPath: options.formattedPath,\n        functionName: options.functionName,\n        functionType: options.functionType,\n        definedAt: options.definedAt,\n      } satisfies ForgeRuntimeEvaluationDiagnostics,\n    })\n  }\n\n  protected override stackBodySource(): string | undefined {\n    return this.cause instanceof Error ? (this.cause.stack ?? super.stackBodySource()) : super.stackBodySource()\n  }\n\n  protected override definedAtStackFrames(): string[] {\n    return this.definedAt?.split('\\n') ?? []\n  }\n\n  protected override formatDiagnosticsBlock(): string {\n    return DiagnosticErrorFormatter.formatRuntimeDiagnostics({\n      phase: this.phase,\n      formattedPath: this.formattedPath,\n      functionName: this.functionName,\n      functionType: this.functionType,\n    })\n  }\n}\n\nconst readHttpStatus = (cause: unknown): number | undefined => {\n  if (cause === null || typeof cause !== 'object') {\n    return undefined\n  }\n\n  const { status, statusCode } = cause as { status?: unknown; statusCode?: unknown }\n\n  if (typeof status === 'number') {\n    return status\n  }\n\n  return typeof statusCode === 'number' ? statusCode : undefined\n}\n\nconst buildMessage = (options: ForgeRuntimeEvaluationErrorOptions): string => {\n  const base = `Failed to evaluate compiled Forge ${options.phase} function`\n\n  return options.cause instanceof Error ? `${base}: ${options.cause.message}` : base\n}\n\nexport const getForgeRuntimeEvaluationDiagnostics = (error: Error): ForgeRuntimeEvaluationDiagnostics | undefined => {\n  const diagnostics: unknown = Reflect.get(error, FORGE_RUNTIME_EVALUATION_DIAGNOSTICS)\n\n  if (!isForgeRuntimeEvaluationDiagnostics(diagnostics)) {\n    return undefined\n  }\n\n  return diagnostics\n}\n\nconst isForgeRuntimeEvaluationDiagnostics = (value: unknown): value is ForgeRuntimeEvaluationDiagnostics => {\n  return value !== null &&\n    value !== undefined &&\n    typeof value === 'object' &&\n    !Array.isArray(value) &&\n    typeof (value as Record<string, unknown>).phase === 'string'\n}\n","import { createHash } from 'node:crypto'\nimport ExpressionDispatcher from './expressions/ExpressionDispatcher'\nimport BlankLineCodeNode from './codegen/statements/BlankLineCodeNode'\nimport { code } from './codegen/fragments/CodeFragment'\nimport CodeGenerator from './codegen/CodeGenerator'\nimport CommentCodeNode from './codegen/statements/CommentCodeNode'\nimport DirectiveCodeNode from './codegen/statements/DirectiveCodeNode'\nimport CodeNode from './codegen/statements/CodeNode'\nimport IdentifierName from './codegen/fragments/IdentifierName'\nimport ThrowCodeNode from './codegen/statements/ThrowCodeNode'\nimport TryCatchCodeNode from './codegen/statements/TryCatchCodeNode'\nimport SourceRenderer, { SourceMapSegment } from './codegen/rendering/SourceRenderer'\nimport { encodeInlineSourceMap } from './codegen/rendering/sourceMapEncoder'\nimport { generatedFunctionRuntimeLibrary } from './generatedFunctionRuntimeLibrary'\nimport ForgeCompilationError from '../../../errors/ForgeCompilationError'\nimport ForgeRuntimeEvaluationError from '../../../errors/ForgeRuntimeEvaluationError'\nimport type { DiagnosticMetadata } from './emitters/DiagnosticEmitter'\n\n/**\n * The eight generated-function phases. Typing `PHASE_PURPOSES` by this enum\n * makes a missing purpose entry a type error, so the header comments can never\n * drift from the phases the compilers actually emit.\n */\nexport enum CompilationPhase {\n  ANSWER_PREPARATION = 'answer-preparation',\n  VALIDATION = 'validation',\n  ENTRY_VALIDATION = 'entry-validation',\n  HOOKS = 'hooks',\n  REACHABILITY = 'reachability',\n  FIELD_INVENTORY = 'field-inventory',\n  RESOLVE = 'resolve',\n  ROUTE_TREE = 'route-tree',\n}\n\ninterface CompileOptions {\n  phase?: CompilationPhase\n  /** Journey/step identity segment for the script URL, e.g. `guide.defining-steps` */\n  label?: string\n}\n\ninterface RuntimeDiagnosticState {\n  readonly nodeId?: string\n  readonly formattedPath?: string\n  readonly functionName?: string\n  readonly functionType?: string\n  readonly definedAt?: string\n}\n\ninterface RuntimeEvaluationDiagnostics {\n  current: RuntimeDiagnosticState | undefined\n  resolve(reference: number): RuntimeDiagnosticState | undefined\n  wrap(error: unknown, reference?: number): unknown\n}\n\nconst RUNTIME_DIAGNOSTICS_PARAM = '_forgeRuntimeDiagnostics'\nexport const GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM = '_forgeHelpers'\n\n/**\n * Resets the expression dispatcher (the component that compiles authored\n * expressions into JavaScript) before a compiler builds source.\n *\n * The dispatcher tracks stateful context like the current iterator nesting\n * and whether the generated code needs `await`. Resetting here makes every\n * compiler start from a clean slate while still sharing the same sync/async\n * decision rules.\n */\nexport function buildGeneratedSource<TSource>(expr: ExpressionDispatcher, buildSource: () => TSource): TSource {\n  expr.reset()\n\n  return buildSource()\n}\n\n/** Renders inspectable source without constructing the generated function. */\nexport function renderGeneratedSource(expr: ExpressionDispatcher, buildSource: () => CodeGenerator): string {\n  const built = buildGeneratedSource(expr, buildSource)\n\n  return new SourceRenderer().render(built.toNodes()).source\n}\n\n/**\n * Compiles a generated-source node tree into either `Function` or `AsyncFunction`.\n *\n * A compiler becomes async only when the expression dispatcher finds an\n * `await` at the top level of the generated code; awaits inside nested\n * function expressions belong to those functions and do not count.\n */\nexport function compileGeneratedFunction<TFunction extends GeneratedFunction>(\n  expr: ExpressionDispatcher,\n  parameterNames: string[],\n  buildSource: () => CodeGenerator,\n  options: CompileOptions = {},\n): TFunction {\n  const phase = options.phase ?? 'unknown'\n  const generatedSource = buildGeneratedSource(expr, buildSource)\n  const diagnosticCatalogue = expr.diagnosticCatalogue\n  const wrapperNodes = wrapGeneratedBody(generatedSource, phase)\n  const usesAwait = expr.usesAwait\n  const { source, segmentsByLine } = new SourceRenderer().render(wrapperNodes)\n  const sourceMapUrl = resolveSourceMapUrl(segmentsByLine, usesAwait)\n  let compiled: GeneratedFunction\n\n  try {\n    compiled = createCompiledFunction<GeneratedFunction>(\n      [...parameterNames, GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM, RUNTIME_DIAGNOSTICS_PARAM],\n      source,\n      {\n        usesAwait,\n        sourceName: nextSourceName(phase, options.label, source, sourceMapUrl),\n        sourceMapUrl,\n      },\n    )\n  } catch (cause) {\n    throw new ForgeCompilationError({ phase, cause })\n  }\n\n  const wrapped: GeneratedFunction = (...args: never[]) => {\n    const runtimeDiagnostics = createRuntimeDiagnostics(phase, diagnosticCatalogue)\n    const runtimeArgs = parameterNames.map((_, index) => args[index])\n\n    try {\n      const result = Reflect.apply(compiled, undefined, [\n        ...runtimeArgs,\n        generatedFunctionRuntimeLibrary,\n        runtimeDiagnostics,\n      ])\n\n      if (isPromiseLike(result)) {\n        return Promise.resolve(result).catch((error: unknown) => {\n          throw runtimeDiagnostics.wrap(error)\n        })\n      }\n\n      return result\n    } catch (error) {\n      throw runtimeDiagnostics.wrap(error)\n    }\n  }\n\n  return wrapped as TFunction\n}\n\n/**\n * Every compiled function gets its own script URL. Debuggers key scripts by\n * URL, so N steps sharing `forge:compiled/hooks` would shadow each other in\n * scripts panels even though V8 itself keeps them distinct. The prefix stays\n * `forge:compiled/` so frame filtering still treats these as internal.\n *\n * A label makes the scripts panel navigable, while a content fingerprint stops\n * an IDE reusing stale generated source after reconnecting to a restarted\n * process. Every script remains a sibling `.js` file so debuggers do not have\n * to represent one generated URL as both a file and a directory.\n */\nconst sourceNameCounters = new Map<string, number>()\n\nconst nextSourceName = (\n  phase: string,\n  label: string | undefined,\n  source: string,\n  sourceMapUrl: string | undefined,\n): string => {\n  const fingerprint = createHash('sha256')\n    .update(source)\n    .update('\\0')\n    .update(sourceMapUrl ?? '')\n    .digest('hex')\n    .slice(0, 8)\n  const readableName = label ?? 'unlabelled'\n  const counterKey = `${phase}/${readableName}`\n  const next = (sourceNameCounters.get(counterKey) ?? 0) + 1\n\n  sourceNameCounters.set(counterKey, next)\n\n  return `forge:compiled/${phase}/${readableName}.${fingerprint}.${next}.js`\n}\n\nconst createRuntimeDiagnostics = (\n  phase: string,\n  diagnosticCatalogue: readonly DiagnosticMetadata[],\n): RuntimeEvaluationDiagnostics => {\n  const diagnostics: RuntimeEvaluationDiagnostics = {\n    current: undefined,\n    resolve: reference => diagnosticCatalogue[reference],\n    wrap: (error, reference) => {\n      if (error instanceof ForgeRuntimeEvaluationError) {\n        return error\n      }\n\n      const current =\n        reference === undefined ? diagnostics.current : (diagnostics.resolve(reference) ?? diagnostics.current)\n\n      return new ForgeRuntimeEvaluationError({\n        phase,\n        nodeId: current?.nodeId,\n        formattedPath: current?.formattedPath,\n        functionName: current?.functionName,\n        functionType: current?.functionType,\n        definedAt: current?.definedAt,\n        cause: error,\n      })\n    },\n  }\n\n  return diagnostics\n}\n\n/**\n * Explains each compiled function to the developer reading it in a debugger:\n * what it does, when it runs, and what it returns. Rendered as the header\n * comment block ahead of the generated body.\n */\nconst PHASE_PURPOSES: Record<CompilationPhase, readonly string[]> = {\n  [CompilationPhase.ANSWER_PREPARATION]: [\n    \"Prepares this step's field answers before validation: POST requests normalise\",\n    'the submitted values, GET requests surface stored answers and defaults.',\n    'Returns one preparation task per field for the work executor to run.',\n  ],\n  [CompilationPhase.VALIDATION]: [\n    \"Builds this step's validation plan: one entry per field rule plus any\",\n    'domain-level checks. The work executor runs it and stores the outcome',\n    'that decides error display.',\n  ],\n  [CompilationPhase.ENTRY_VALIDATION]: [\n    'Selects which validation groups to display when this step first renders:',\n    'each validateOnEntry rule whose condition holds contributes its groups.',\n  ],\n  [CompilationPhase.HOOKS]: [\n    'Runs the authored hook lifecycle: each hook evaluates its condition, then',\n    'its effects, in authored order. Effects are awaited before any outcome',\n    'is inspected.',\n  ],\n  [CompilationPhase.REACHABILITY]: [\n    'Computes reachability facts for the journey: which steps can currently be',\n    'entered and where forward redirects should land.',\n  ],\n  [CompilationPhase.FIELD_INVENTORY]: [\n    'Lists every field each step owns, so answers belonging to steps that',\n    'become unreachable can be cleared down.',\n  ],\n  [CompilationPhase.RESOLVE]: [\n    \"Resolves this step's blocks into render-ready props, evaluating conditions\",\n    'and dynamic values against the current request context.',\n  ],\n  [CompilationPhase.ROUTE_TREE]: ['Resolves the metadata carried on each route-tree node for the current request.'],\n}\n\nconst resolvePhasePurpose = (phase: string): readonly string[] => {\n  return (PHASE_PURPOSES as Record<string, readonly string[] | undefined>)[phase] ?? []\n}\n\n/**\n * Moves any `\"use strict\"` directive above the wrapper, then wraps the body\n * in a try/catch. Uncaught errors are routed through the runtime diagnostics\n * so stack traces shown to journey authors include the node that failed.\n */\nconst wrapGeneratedBody = (generator: CodeGenerator, phase: string): CodeNode[] => {\n  const bodyNodes = [...generator.toNodes()]\n  const firstNode = bodyNodes[0]\n  const strictDirective =\n    firstNode instanceof DirectiveCodeNode && firstNode.value === 'use strict' ? firstNode : undefined\n\n  if (strictDirective !== undefined) {\n    bodyNodes.shift()\n  }\n\n  while (bodyNodes[0] instanceof BlankLineCodeNode) {\n    bodyNodes.shift()\n  }\n\n  const errorName = new IdentifierName('error')\n\n  return [\n    ...(strictDirective === undefined ? [] : [strictDirective]),\n    new CommentCodeNode('Compiled by Forge from the journey definition.', false),\n    ...resolvePhasePurpose(phase).map(purposeLine => new CommentCodeNode(purposeLine, false)),\n    new TryCatchCodeNode(bodyNodes, errorName, [\n      new ThrowCodeNode(code`${new IdentifierName(RUNTIME_DIAGNOSTICS_PARAM)}.wrap(${errorName})`),\n    ]),\n  ]\n}\n\nconst resolveSourceMapUrl = (\n  segmentsByLine: readonly (readonly SourceMapSegment[])[],\n  usesAwait: boolean,\n): string | undefined => {\n  const wrapperOffset = measureWrapperOffset(usesAwait)\n\n  if (wrapperOffset === undefined || segmentsByLine.every(segments => segments.length === 0)) {\n    return undefined\n  }\n\n  return encodeInlineSourceMap(segmentsByLine, wrapperOffset)\n}\n\nconst isPromiseLike = (value: unknown): value is PromiseLike<unknown> => {\n  return value !== null &&\n    value !== undefined &&\n    (typeof value === 'object' || typeof value === 'function') &&\n    typeof (value as { then?: unknown }).then === 'function'\n}\n\nexport type GeneratedFunction = (...args: never[]) => unknown\n\nconst AsyncFunctionConstructor = Object.getPrototypeOf(async function compiledAsync() {\n  return undefined\n}).constructor as FunctionConstructor\n\n/**\n * Creates either a normal Function or an AsyncFunction from generated source.\n *\n * The compiler keeps sync functions genuinely sync for the hot path, but any\n * emitted `await` requires the async constructor because `await` is illegal in a\n * normal function body. Runtime callers still await the result so both shapes\n * share the same orchestration path.\n */\ninterface CreateCompiledFunctionOptions {\n  usesAwait: boolean\n  /** Named script origin so eval'd frames render as `forge:compiled/...` instead of `<anonymous>` */\n  sourceName?: string\n  /** Inline `data:` source map binding definition-file breakpoints onto the compiled function */\n  sourceMapUrl?: string\n}\n\nexport function createCompiledFunction<TFunction extends GeneratedFunction>(\n  parameterNames: string[],\n  source: string,\n  options: CreateCompiledFunctionOptions,\n): TFunction {\n  const constructor = options.usesAwait ? AsyncFunctionConstructor : Function\n  const namedSource = [\n    source,\n    ...(options.sourceName === undefined ? [] : [`//# sourceURL=${options.sourceName}`]),\n    ...(options.sourceMapUrl === undefined ? [] : [`//# sourceMappingURL=${options.sourceMapUrl}`]),\n  ].join('\\n')\n\n  return new constructor(...parameterNames, namedSource) as TFunction\n}\n\n/**\n * `new Function(body)` doesn't compile the body on its own - V8 wraps it in a\n * few lines of `function anonymous(...) {` scaffolding first. Stack traces and\n * source maps count lines from the top of that wrapped script, so our line\n * numbers are all off by the height of the scaffolding. Rather than hardcode\n * that height (it can differ between sync and async, or between engine\n * versions), we measure it: build a throwaway function with a known one-line\n * body, `toString()` it, and see which line the body actually landed on.\n */\nconst wrapperOffsets = new Map<boolean, number | undefined>()\n\nexport const measureWrapperOffset = (usesAwait: boolean): number | undefined => {\n  if (wrapperOffsets.has(usesAwait)) {\n    return wrapperOffsets.get(usesAwait)\n  }\n\n  const probeBody = 'return \"forge-offset-probe\";'\n  const constructor = usesAwait ? AsyncFunctionConstructor : Function\n  const probeLine = new constructor(probeBody)\n    .toString()\n    .split('\\n')\n    .findIndex(line => line === probeBody)\n  const offset = probeLine === -1 ? undefined : probeLine\n\n  wrapperOffsets.set(usesAwait, offset)\n\n  return offset\n}\n","import { CodeFragment, code, literal } from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport ExpressionDispatcher from '../expressions/ExpressionDispatcher'\nimport { IteratorScopeFrame } from '../expressions/types'\n\n/** The emitted loop's bindings, exposed to per-item compile callbacks. */\nexport interface IteratorEmitScope {\n  readonly input: IdentifierName\n  readonly index: IdentifierName\n  readonly item: IdentifierName\n  readonly rawItem: IdentifierName\n  readonly inputLength: CodeFragment\n}\n\n/**\n * Emits the shared iterator loop that every phase compiler (the per-concern\n * code generators in lowering) uses. It normalises the input collection,\n * guards on arrays, walks with index/raw-item/item bindings, and runs the\n * per-item callback inside an iterator scope frame so `Item()` and `Loop()`\n * expression references resolve correctly. Both `RuntimeValueCompiler` and\n * `ScopedTemplateCompiler` delegate here.\n */\nexport default class IteratorLoopEmitter {\n  constructor(private readonly expr: ExpressionDispatcher) {}\n\n  compileLoop(input: unknown, generator: CodeGenerator, compileItem: (scope: IteratorEmitScope) => void): void {\n    const inputName = generator.let('iteratorInput', this.expr.compileOperandCode(input, generator))\n\n    this.expr.compileNormalizeIteratorInput(inputName, generator)\n\n    generator.if(code`Array.isArray(${inputName})`, () => {\n      const indexName = generator.let('iteratorIndex', literal(0))\n\n      generator.while(code`${indexName} < ${inputName}.length`, () => {\n        const currentIndex = generator.const('currentIteratorIndex', indexName)\n        const rawItem = generator.const('rawIteratorItem', code`${inputName}[${currentIndex}]`)\n\n        generator.assign(indexName, code`${indexName} + 1`)\n        generator.if(code`${rawItem} == null`, () => generator.continue())\n        generator.statement(code`_forgeHelpers.consumeIteratorIteration(ctx)`)\n\n        const item = generator.const('iteratorItem', this.expr.compileIteratorItemScopeExpression(rawItem))\n        const inputLength = code`${inputName}.length`\n        const scope: IteratorEmitScope = { input: inputName, index: currentIndex, item, rawItem, inputLength }\n        const frame: IteratorScopeFrame = {\n          itemVar: item,\n          indexVar: currentIndex,\n          inputLengthExpr: inputLength,\n          rawItemExpr: rawItem,\n        }\n\n        this.expr.withIteratorFrame(frame, () => {\n          compileItem(scope)\n        })\n      })\n    })\n  }\n\n}\n","import { IteratorType } from '../../../../../authoring/types/enums'\nimport type { ASTNode } from '../../../contracts/ast/ast.type'\nimport type { TemplateNode } from '../../../contracts/ast/template.type'\nimport {\n  AuthoredValueKind,\n  toRawOperand,\n  type AuthoredValue,\n  type BlockValue,\n  type ConditionalValue,\n  type IterationValue,\n  type ListValue,\n  type MatchValue,\n  type RecordValue,\n} from '../../../contracts/models/authoredValue.type'\nimport ForgeInternalError from '../../../../errors/ForgeInternalError'\nimport {\n  CodeFragment,\n  arrayCode,\n  code,\n  literal,\n  objectCode,\n  propertyCode,\n  structuredLiteralCode,\n  SafeCode,\n} from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport IteratorLoopEmitter from '../emitters/IteratorLoopEmitter'\nimport ExpressionDispatcher from '../expressions/ExpressionDispatcher'\nimport PredicateNodeCompiler from '../expressions/PredicateNodeCompiler'\n\nexport interface RuntimeValueCompileOptions {\n  readonly expressionErrorFallback?: CodeFragment\n  readonly expressionErrorMode?: RuntimeValueErrorMode\n  readonly omitUndefinedArrayItems?: boolean\n}\n\nexport interface RuntimeValueCompilerPolicy {\n  readonly expressionErrorFallback: CodeFragment\n  readonly expressionErrorMode?: RuntimeValueErrorMode\n  readonly omitUndefinedArrayItems: boolean\n  /**\n   * Emits a nested `BlockValue` as its own named unit (comment, props const,\n   * resolve const) and returns the name to reference. Only the resolve concern\n   * (which turns blocks into render-ready props) handles nested blocks; a\n   * policy without this callback treats a nested block as an impossible state.\n   */\n  readonly compileBlockValue?: (block: BlockValue, generator: CodeGenerator, nameHint: string) => SafeCode\n}\n\ntype RuntimeValueErrorMode = 'fallback' | 'throw'\n\n/** Turns authored values (the raw values journey authors write) into generated JavaScript code that produces them at runtime. */\nexport default class RuntimeValueCompiler {\n  private readonly loops: IteratorLoopEmitter\n\n  constructor(\n    private readonly expr: ExpressionDispatcher,\n    private readonly policy: RuntimeValueCompilerPolicy,\n  ) {\n    this.loops = new IteratorLoopEmitter(this.expr)\n  }\n\n  compileAssignment(\n    value: AuthoredValue,\n    generator: CodeGenerator,\n    targetObject: SafeCode,\n    key: string,\n    options: RuntimeValueCompileOptions = {},\n  ): void {\n    const target = code`${targetObject}${propertyCode(key)}`\n\n    if (value.kind === AuthoredValueKind.EXPRESSION) {\n      this.compileExpressionInto(value.node, generator, target, options)\n\n      return\n    }\n\n    generator.assign(target, this.compileValueExpression(value, generator, key, options))\n  }\n\n  /**\n   * Compiles a value to an expression usable inside a literal. Values that\n   * need statements — nested blocks, invoking expressions, conditionals,\n   * matches, iterations — are hoisted into named consts emitted just above,\n   * in authored order, and the returned expression references the name.\n   */\n  compileValueExpression(\n    value: AuthoredValue,\n    generator: CodeGenerator,\n    nameHint: string,\n    options: RuntimeValueCompileOptions = {},\n  ): SafeCode {\n    switch (value.kind) {\n      case AuthoredValueKind.STATIC:\n        return structuredLiteralCode(value.value)\n      case AuthoredValueKind.EXPRESSION:\n        return this.compileExpressionOperand(value.node, generator, nameHint, options)\n      case AuthoredValueKind.RECORD:\n        return this.compileRecordExpression(value, generator, options)\n      case AuthoredValueKind.LIST:\n        return this.compileListExpression(value, generator, nameHint, options)\n      case AuthoredValueKind.BLOCK:\n        return this.compileBlockExpression(value, generator, nameHint)\n      default: {\n        const result = generator.let(this.toPropertyValueVariablePrefix(nameHint))\n\n        this.compileValue(value, generator, result, options)\n\n        return result\n      }\n    }\n  }\n\n  compileValue(\n    value: AuthoredValue,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions = {},\n  ): void {\n    switch (value.kind) {\n      case AuthoredValueKind.STATIC:\n        generator.assign(target, structuredLiteralCode(value.value))\n\n        return\n      case AuthoredValueKind.EXPRESSION:\n        this.compileExpressionValue(value.node, generator, target, options)\n\n        return\n      case AuthoredValueKind.CONDITIONAL:\n        this.compileConditionalValue(value, generator, target, options)\n\n        return\n      case AuthoredValueKind.MATCH:\n        this.compileMatchValue(value, generator, target, options)\n\n        return\n      case AuthoredValueKind.ITERATION:\n        this.compileIterationValue(value, generator, target, options)\n\n        return\n      case AuthoredValueKind.LIST:\n        generator.assign(target, this.compileListExpression(value, generator, target.value, options))\n\n        return\n      case AuthoredValueKind.RECORD:\n        generator.assign(target, this.compileRecordExpression(value, generator, options))\n\n        return\n      case AuthoredValueKind.BLOCK:\n        generator.assign(target, this.compileBlockExpression(value, generator, target.value))\n\n        return\n      default:\n        throw new ForgeInternalError('Unclassified authored value reached the runtime value compiler')\n    }\n  }\n\n  private compileExpressionValue(\n    node: ASTNode | TemplateNode,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    this.compileExpressionInto(node, generator, target, options)\n  }\n\n  /**\n   * Assigns a compiled expression to `target`. In throw mode the assignment is\n   * an unconditional statement, so function calls may hoist their argument\n   * consts into the surrounding body; in fallback mode every temp must stay\n   * inside the try block, so hoisting stays off.\n   */\n  private compileExpressionInto(\n    node: ASTNode | TemplateNode,\n    generator: CodeGenerator,\n    target: SafeCode,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    const errorMode = options.expressionErrorMode ?? this.policy.expressionErrorMode ?? 'fallback'\n\n    if (errorMode === 'throw') {\n      const expression = this.expr.withGeneratorScope(generator, () => this.compileNodeExpression(node, generator))\n\n      generator.assign(target, expression)\n\n      return\n    }\n\n    const fallback = options.expressionErrorFallback ?? this.policy.expressionErrorFallback\n\n    generator.tryCatch(\n      () => generator.assign(target, this.compileNodeExpression(node, generator)),\n      'error',\n      () => generator.assign(target, fallback),\n    )\n  }\n\n  private compileNodeExpression(node: ASTNode | TemplateNode, generator: CodeGenerator): CodeFragment {\n    return this.expr.isTemplateNode(node)\n      ? this.expr.compileTemplateExpressionCode(node, generator)\n      : this.expr.compileExpressionCode(node, generator)\n  }\n\n  private compileExpressionWithCatch(\n    compileExpression: () => CodeFragment,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    const errorMode = options.expressionErrorMode ?? this.policy.expressionErrorMode ?? 'fallback'\n\n    if (errorMode === 'throw') {\n      generator.assign(target, compileExpression())\n\n      return\n    }\n\n    const fallback = options.expressionErrorFallback ?? this.policy.expressionErrorFallback\n\n    generator.tryCatch(\n      () => generator.assign(target, compileExpression()),\n      'error',\n      () => generator.assign(target, fallback),\n    )\n  }\n\n  /**\n   * Compiles an expression operand for a literal position. Invocation-bearing\n   * expressions are hoisted into a named const so authored calls keep their\n   * source order and stay inspectable; plain reads are inlined. Fallback-mode\n   * expressions always hoist, because the try/catch needs statements.\n   */\n  private compileExpressionOperand(\n    node: ASTNode | TemplateNode,\n    generator: CodeGenerator,\n    nameHint: string,\n    options: RuntimeValueCompileOptions,\n  ): SafeCode {\n    const errorMode = options.expressionErrorMode ?? this.policy.expressionErrorMode ?? 'fallback'\n\n    if (errorMode === 'throw') {\n      const expression = this.expr.withGeneratorScope(generator, () => this.compileNodeExpression(node, generator))\n\n      if (!expression.containsInvocation) {\n        return expression\n      }\n\n      return generator.const(this.toPropertyValueVariablePrefix(nameHint), expression)\n    }\n\n    const result = generator.let(this.toPropertyValueVariablePrefix(nameHint))\n\n    this.compileExpressionInto(node, generator, result, options)\n\n    return result\n  }\n\n  private compileRecordExpression(\n    value: RecordValue,\n    generator: CodeGenerator,\n    options: RuntimeValueCompileOptions,\n  ): CodeFragment {\n    return objectCode(\n      value.entries.map(entry => ({\n        key: entry.key,\n        value: this.compileValueExpression(entry.value, generator, entry.key, options),\n      })),\n    )\n  }\n\n  /**\n   * Lists inline as array literals when no item can resolve to `undefined`.\n   * When one can and undefined items must be dropped, the list falls back to\n   * push-based construction under a named const.\n   */\n  private compileListExpression(\n    value: ListValue,\n    generator: CodeGenerator,\n    nameHint: string,\n    options: RuntimeValueCompileOptions,\n  ): SafeCode {\n    const omitUndefined = options.omitUndefinedArrayItems ?? this.policy.omitUndefinedArrayItems\n\n    if (omitUndefined && value.items.some(item => this.mayResolveUndefined(item))) {\n      return this.compileListConstruction(value, generator, this.toPropertyValueVariablePrefix(nameHint), options)\n    }\n\n    return arrayCode(value.items.map(item => this.compileValueExpression(item, generator, nameHint, options)))\n  }\n\n  private mayResolveUndefined(value: AuthoredValue): boolean {\n    if (value.kind === AuthoredValueKind.STATIC) {\n      return value.value === undefined\n    }\n\n    return value.kind !== AuthoredValueKind.RECORD &&\n      value.kind !== AuthoredValueKind.LIST &&\n      value.kind !== AuthoredValueKind.BLOCK\n  }\n\n  private compileListConstruction(\n    value: ListValue,\n    generator: CodeGenerator,\n    namePrefix: string,\n    options: RuntimeValueCompileOptions,\n  ): IdentifierName {\n    const omitUndefined = options.omitUndefinedArrayItems ?? this.policy.omitUndefinedArrayItems\n    const arrayValue = generator.const(namePrefix, code`[]`)\n\n    value.items.forEach(element => {\n      if (element.kind === AuthoredValueKind.STATIC) {\n        generator.statement(code`${arrayValue}.push(${structuredLiteralCode(element.value)})`)\n\n        return\n      }\n\n      const arrayItem = generator.let('arrayItem')\n\n      this.compileValue(element, generator, arrayItem, options)\n\n      if (omitUndefined) {\n        generator.if(code`${arrayItem} !== undefined`, () => {\n          generator.statement(code`${arrayValue}.push(${arrayItem})`)\n        })\n\n        return\n      }\n\n      generator.statement(code`${arrayValue}.push(${arrayItem})`)\n    })\n\n    return arrayValue\n  }\n\n  private compileConditionalValue(\n    value: ConditionalValue,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    const predicate = generator.let('conditionalPredicate')\n\n    this.compileExpressionWithCatch(\n      () => this.expr.compileOperandCode(toRawOperand(value.predicate), generator),\n      generator,\n      predicate,\n      {\n        ...options,\n        expressionErrorFallback: literal(false),\n      },\n    )\n\n    generator.if(\n      predicate,\n      () => this.compileValue(value.thenValue, generator, target, options),\n      () => this.compileValue(value.elseValue, generator, target, options),\n    )\n  }\n\n  private compileMatchValue(\n    value: MatchValue,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    const subject = generator.let('matchSubject')\n\n    this.compileValue(value.subject, generator, subject, options)\n    this.compileMatchBranches(value.branches, value.otherwise, generator, target, options, code`${subject}`)\n  }\n\n  private compileMatchBranches(\n    branches: MatchValue['branches'],\n    otherwise: MatchValue['otherwise'],\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n    subject: CodeFragment,\n  ): void {\n    const [branch, ...remainingBranches] = branches\n\n    if (branch === undefined) {\n      if (otherwise !== undefined) {\n        this.compileValue(otherwise, generator, target, options)\n      }\n\n      return\n    }\n\n    const predicate = generator.let('matchPredicate')\n\n    this.compileExpressionWithCatch(\n      () =>\n        this.expr.withGeneratorScope(generator, () =>\n          'expected' in branch\n            ? code`(${subject} === ${this.expr.compileOperandCode(toRawOperand(branch.expected))})`\n            : new PredicateNodeCompiler(this.expr).compileOperand(toRawOperand(branch.predicate), subject),\n        ),\n      generator,\n      predicate,\n      { ...options, expressionErrorFallback: literal(false) },\n    )\n    generator.if(\n      predicate,\n      () => this.compileValue(branch.value, generator, target, options),\n      () => this.compileMatchBranches(remainingBranches, otherwise, generator, target, options, subject),\n    )\n  }\n\n  private compileIterationValue(\n    value: IterationValue,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    if (value.iterator === IteratorType.MAP) {\n      this.compileMapValue(value, generator, target, options)\n\n      return\n    }\n\n    if (value.iterator === IteratorType.FILTER) {\n      this.compileFilterValue(value, generator, target)\n\n      return\n    }\n\n    if (value.iterator === IteratorType.FIND) {\n      this.compileFindValue(value, generator, target)\n\n      return\n    }\n\n    if (\n      value.iterator === IteratorType.SOME ||\n      value.iterator === IteratorType.EVERY ||\n      value.iterator === IteratorType.COUNT\n    ) {\n      this.compileExpressionValue(value.source, generator, target, options)\n\n      return\n    }\n\n    generator.assign(target, literal(undefined))\n  }\n\n  private compileMapValue(\n    value: IterationValue,\n    generator: CodeGenerator,\n    target: IdentifierName,\n    options: RuntimeValueCompileOptions,\n  ): void {\n    const mapValue = generator.const('mapValue', code`[]`)\n\n    this.loops.compileLoop(toRawOperand(value.input), generator, () => {\n      const mapItem = generator.let('mapItem')\n\n      if (value.yieldTemplate === undefined) {\n        generator.assign(mapItem, literal(undefined))\n      } else {\n        this.compileValue(value.yieldTemplate, generator, mapItem, options)\n      }\n\n      generator.if(code`${mapItem} !== undefined`, () => {\n        generator.statement(code`${mapValue}.push(${mapItem})`)\n      })\n    })\n\n    generator.assign(target, mapValue)\n  }\n\n  private compileFilterValue(value: IterationValue, generator: CodeGenerator, target: IdentifierName): void {\n    const filterValue = generator.const('filterValue', code`[]`)\n\n    this.loops.compileLoop(toRawOperand(value.input), generator, scope => {\n      const predicate = generator.let('filterPredicate')\n\n      this.compileExpressionWithCatch(\n        () => this.expr.compileOperandCode(this.toRawPredicate(value), generator),\n        generator,\n        predicate,\n        { expressionErrorFallback: literal(false) },\n      )\n      generator.if(predicate, () => {\n        generator.statement(code`${filterValue}.push(${scope.rawItem})`)\n      })\n    })\n\n    generator.assign(target, filterValue)\n  }\n\n  private compileFindValue(value: IterationValue, generator: CodeGenerator, target: IdentifierName): void {\n    this.loops.compileLoop(toRawOperand(value.input), generator, scope => {\n      const predicate = generator.let('findPredicate')\n\n      this.compileExpressionWithCatch(\n        () => this.expr.compileOperandCode(this.toRawPredicate(value), generator),\n        generator,\n        predicate,\n        { expressionErrorFallback: literal(false) },\n      )\n      generator.if(predicate, () => {\n        generator.assign(target, scope.rawItem)\n        generator.break()\n      })\n    })\n  }\n\n  private compileBlockExpression(value: BlockValue, generator: CodeGenerator, nameHint: string): SafeCode {\n    if (this.policy.compileBlockValue === undefined) {\n      throw new ForgeInternalError('A nested block value is only compilable by the resolve concern')\n    }\n\n    return this.policy.compileBlockValue(value, generator, nameHint)\n  }\n\n  private toRawPredicate(value: IterationValue): unknown {\n    return value.predicate === undefined ? undefined : toRawOperand(value.predicate)\n  }\n\n  private toPropertyValueVariablePrefix(key: string): string {\n    const words = key.match(/[A-Za-z0-9]+/g)?.map(word => word.toLowerCase()) ?? []\n\n    if (words.length === 0) {\n      return 'propertyValue'\n    }\n\n    const firstWord = words[0] ?? 'property'\n    const restWords = words.slice(1)\n    const variablePrefix = `${firstWord}${restWords.map(word => this.capitaliseWord(word)).join('')}Value`\n\n    if (/^[A-Za-z_$]/.test(variablePrefix)) {\n      return variablePrefix\n    }\n\n    return `property${this.capitaliseWord(variablePrefix)}`\n  }\n\n  private capitaliseWord(value: string): string {\n    return `${value.charAt(0).toUpperCase()}${value.slice(1)}`\n  }\n}\n","import { IteratorType } from '../../../../../authoring/types/enums'\nimport { IterateASTNode } from '../../../contracts/ast/expressions.type'\nimport { isTemplateNode } from '../../../contracts/ast/nodes'\nimport { TemplateNode, TemplateValue } from '../../../contracts/ast/template.type'\nimport type { FieldModel, IterateRef } from '../../../contracts/models/fieldModel.type'\nimport { arrayCode, CodeFragment, code, literal } from '../codegen/fragments/CodeFragment'\nimport CodeGenerator from '../codegen/CodeGenerator'\nimport IdentifierName from '../codegen/fragments/IdentifierName'\nimport FieldCodeEmitter from '../emitters/FieldCodeEmitter'\nimport IteratorLoopEmitter, { IteratorEmitScope } from '../emitters/IteratorLoopEmitter'\nimport ExpressionDispatcher from '../expressions/ExpressionDispatcher'\n\ninterface TemplateMapIteratorProperties {\n  readonly input?: unknown\n  readonly iterator?: {\n    readonly type?: unknown\n    readonly yieldTemplate?: TemplateValue\n  }\n}\n\ninterface FieldOccurrenceOptions {\n  readonly compileLeaf: (field: FieldModel) => void\n  /** Emitted ahead of each top-level iterator loop, e.g. `Fields produced by an iterator`. */\n  readonly loopComment?: string\n}\n\ninterface FieldOccurrenceRun {\n  readonly ref: IterateRef | undefined\n  readonly fields: FieldModel[]\n}\n\n/**\n * Emits the iterator loop nesting that fields and blocks sit inside.\n *\n * Answer preparation, validation, field inventory, and resolve all need the\n * same MAP expansion behaviour: normalise input, enter `Item()`/`Loop()`\n * scope, and resolve dynamic field codes under that scope. The actual loop\n * body lives in `IteratorLoopEmitter`; this class reconstructs the nesting\n * structure from each field model's `iteratorPath` and the registered\n * iterate nodes.\n */\nexport default class ScopedTemplateCompiler {\n  private readonly fieldCodes: FieldCodeEmitter\n\n  private readonly loops: IteratorLoopEmitter\n\n  constructor(private readonly expr: ExpressionDispatcher) {\n    this.fieldCodes = new FieldCodeEmitter(expr)\n    this.loops = new IteratorLoopEmitter(expr)\n  }\n\n  /**\n   * Emits every field in model order, reconstructing the iterator loop nesting\n   * from each field's `iteratorPath`. Consecutive fields sharing an iterator\n   * path prefix share one emitted loop, so the generated code (and the runtime\n   * evaluation order) matches the authored template structure.\n   */\n  compileFieldOccurrences(\n    fields: readonly FieldModel[],\n    generator: CodeGenerator,\n    options: FieldOccurrenceOptions,\n  ): void {\n    this.compileFieldOccurrenceRuns(fields, 0, generator, options)\n  }\n\n  /**\n   * Emits a registered MAP iterator node and compiles its yield template (the\n   * per-item output shape) under iterator scope.\n   */\n  compileMapIterator(\n    node: IterateASTNode,\n    generator: CodeGenerator,\n    compileYield: (template: TemplateValue, scope: IteratorEmitScope) => void,\n  ): void {\n    const yieldTemplate = node.properties.iterator.yieldTemplate\n\n    if (node.properties.iterator.type !== IteratorType.MAP || yieldTemplate === undefined) {\n      return\n    }\n\n    this.loops.compileLoop(node.properties.input, generator, scope => {\n      compileYield(yieldTemplate, scope)\n    })\n  }\n\n  /**\n   * Resolves a template field code to generated source, including dynamic code expressions.\n   */\n  compileTemplateCodeExpression(\n    node: TemplateNode,\n    generator: CodeGenerator,\n  ): CodeFragment | IdentifierName | undefined {\n    return this.fieldCodes.compileTemplateExpression(node, generator)\n  }\n\n  /**\n   * Emits the runtime block ID for one template node under the current iterator scope.\n   */\n  compileTemplateInstanceIdExpression(node: TemplateNode): CodeFragment {\n    const prefix = `compiled:${String(node.id)}`\n    const iteratorIndexes = this.expr.iteratorStack.map(frame => frame.indexVar)\n\n    if (iteratorIndexes.length === 0) {\n      return literal(prefix)\n    }\n\n    return code`${`${prefix}:`} + ${arrayCode(iteratorIndexes.map(index => code`${index}`))}.join(\":\")`\n  }\n\n  private compileFieldOccurrenceRuns(\n    fields: readonly FieldModel[],\n    depth: number,\n    generator: CodeGenerator,\n    options: FieldOccurrenceOptions,\n  ): void {\n    this.groupConsecutiveRuns(fields, depth).forEach(run => {\n      if (run.ref === undefined) {\n        run.fields.forEach(field => options.compileLeaf(field))\n\n        return\n      }\n\n      if (depth === 0 && options.loopComment !== undefined) {\n        generator.comment(options.loopComment)\n      }\n\n      const runRef = run.ref\n\n      this.compileIterateRefLoop(runRef, generator, () => {\n        this.compileFieldOccurrenceRuns(run.fields, depth + 1, generator, options)\n      })\n    })\n  }\n\n  private groupConsecutiveRuns(fields: readonly FieldModel[], depth: number): FieldOccurrenceRun[] {\n    return fields.reduce<FieldOccurrenceRun[]>((runs, field) => {\n      const ref = field.iteratorPath[depth]\n      const lastRun = runs.at(-1)\n\n      if (lastRun !== undefined && lastRun.ref?.node === ref?.node) {\n        lastRun.fields.push(field)\n\n        return runs\n      }\n\n      runs.push({ ref, fields: [field] })\n\n      return runs\n    }, [])\n  }\n\n  /** Emits one loop level for a registered or template MAP iterate node. */\n  private compileIterateRefLoop(ref: IterateRef, generator: CodeGenerator, compileBody: () => void): void {\n    const input = isTemplateNode(ref.node)\n      ? ((ref.node.properties ?? {}) as TemplateMapIteratorProperties).input\n      : ref.node.properties.input\n\n    this.loops.compileLoop(input, generator, () => {\n      compileBody()\n    })\n  }\n}\n","import { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport { toRawOperand } from '../../../chassis/contracts/models/authoredValue.type'\nimport {\n  arrayCode,\n  callCode,\n  CodeFragment,\n  code,\n  literal,\n  objectCode,\n  propertyCode,\n  SafeCode,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport FieldCodeEmitter from '../../../chassis/compilation/lowering/emitters/FieldCodeEmitter'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport RuntimeValueCompiler from '../../../chassis/compilation/lowering/structures/RuntimeValueCompiler'\nimport ScopedTemplateCompiler from '../../../chassis/compilation/lowering/structures/ScopedTemplateCompiler'\nimport {\n  FieldCodeKind,\n  ValidationRulesKind,\n  type FieldModel,\n  type ValidationRulesModel,\n} from '../../../chassis/contracts/models/fieldModel.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\nimport type { ValidationModel } from '../contracts/validationModel.type'\nimport type { CompiledValidationFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\n\nconst CONTEXT = new IdentifierName('ctx')\nconst FILTER = new IdentifierName('filter')\n\n/** Compiler for the validation phase: builds the generated function that runs a step's field and domain validation rules. */\nexport default class StepValidationCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  private readonly fieldCodes: FieldCodeEmitter\n\n  private readonly values: RuntimeValueCompiler\n\n  private readonly templates: ScopedTemplateCompiler\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n    this.fieldCodes = new FieldCodeEmitter(this.expr)\n    this.values = new RuntimeValueCompiler(this.expr, {\n      expressionErrorFallback: literal(undefined),\n      expressionErrorMode: 'throw',\n      omitUndefinedArrayItems: false,\n    })\n    this.templates = new ScopedTemplateCompiler(this.expr)\n  }\n\n  compileStepValidation(model: ValidationModel): CompiledValidationFunction {\n    return compileGeneratedFunction<CompiledValidationFunction>(\n      this.expr,\n      ['ctx', 'filter'],\n      () => this.buildStepValidationSource(model),\n      { phase: CompilationPhase.VALIDATION, label: model.label },\n    )\n  }\n\n  generateStepValidationSource(model: ValidationModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildStepValidationSource(model))\n  }\n\n  private buildStepValidationSource(model: ValidationModel): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx', 'filter'])\n\n    generator.directive('use strict')\n\n    if (model.fields.length === 0 && model.domainRules === undefined) {\n      generator.note('This step declares no validation rules.')\n      generator.return(code`${CONTEXT}.workTasks.stepValidation([], [])`)\n\n      return generator\n    }\n\n    const ruleIsActive = this.compileRuleFilterSetup(generator)\n    const fieldValidations = generator.const('fieldValidations', code`[]`)\n    const domainValidations = generator.const('domainValidations', code`[]`)\n\n    this.templates.compileFieldOccurrences(model.fields, generator, {\n      loopComment: 'Repeated field validations',\n      compileLeaf: field => {\n        this.compileFieldOccurrence(field, fieldValidations, ruleIsActive, generator)\n      },\n    })\n\n    this.compileDomainValidationSlot(model.domainRules, domainValidations, ruleIsActive, generator)\n    generator.blank()\n    generator.return(code`${CONTEXT}.workTasks.stepValidation(${fieldValidations}, ${domainValidations})`)\n\n    return generator\n  }\n\n  private compileFieldOccurrence(\n    field: FieldModel,\n    fieldValidations: IdentifierName,\n    ruleIsActive: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    if (field.iteratorPath.length === 0) {\n      this.compileRegisteredField(field, fieldValidations, ruleIsActive, generator)\n\n      return\n    }\n\n    this.compileTemplateField(field, fieldValidations, ruleIsActive, generator)\n  }\n\n  private compileRegisteredField(\n    field: FieldModel,\n    fieldValidations: IdentifierName,\n    ruleIsActive: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const rules = this.resolveFieldRules(field)\n\n    generator.comment(`Field validation — ${field.label}`)\n    generator.scope(() => {\n      const selfCodeExpression = this.fieldCodes.compileModelExpression(field.code, generator)\n      const blockCode = selfCodeExpression ?? literal(undefined)\n      const dependentWhen = field.dependentWhen === undefined ? undefined : toRawOperand(field.dependentWhen)\n      const functionPrefix = this.compileValidationFunctionPrefix(field)\n\n      this.expr.withSelfCodeExpression(selfCodeExpression, () => {\n        if (dependentWhen !== undefined && this.expr.isCompilableNode(dependentWhen)) {\n          generator.if(this.expr.compileExpressionCode(dependentWhen, generator), () => {\n            this.compileFieldValidationSlot(\n              rules,\n              field.source.id,\n              blockCode,\n              fieldValidations,\n              ruleIsActive,\n              functionPrefix,\n              generator,\n            )\n          })\n\n          return\n        }\n\n        this.compileFieldValidationSlot(\n          rules,\n          field.source.id,\n          blockCode,\n          fieldValidations,\n          ruleIsActive,\n          functionPrefix,\n          generator,\n        )\n      })\n    })\n  }\n\n  private compileTemplateField(\n    field: FieldModel,\n    fieldValidations: IdentifierName,\n    ruleIsActive: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const rules = this.resolveFieldRules(field)\n\n    generator.comment('Template field validation')\n    const codeExpression = this.fieldCodes.compileModelExpression(field.code, generator)\n    const blockCode = codeExpression ?? literal(undefined)\n    const blockId = this.compileTemplateBlockId(field)\n    const functionPrefix = this.compileValidationFunctionPrefix(field)\n\n    this.expr.withSelfCodeExpression(codeExpression, () => {\n      const dependentWhen = field.dependentWhen === undefined ? undefined : toRawOperand(field.dependentWhen)\n\n      if (dependentWhen !== undefined) {\n        generator.if(this.expr.compileOperandCode(dependentWhen, generator), () => {\n          this.compileFieldValidationSlot(\n            rules,\n            blockId,\n            blockCode,\n            fieldValidations,\n            ruleIsActive,\n            functionPrefix,\n            generator,\n          )\n        })\n\n        return\n      }\n\n      this.compileFieldValidationSlot(\n        rules,\n        blockId,\n        blockCode,\n        fieldValidations,\n        ruleIsActive,\n        functionPrefix,\n        generator,\n      )\n    })\n  }\n\n  private compileFieldValidationSlot(\n    rules: ValidationRulesModel,\n    blockId: string | CodeFragment,\n    blockCode: SafeCode,\n    fieldValidations: IdentifierName,\n    ruleIsActive: IdentifierName,\n    functionPrefix: string,\n    generator: CodeGenerator,\n  ): void {\n    const blockIdCode = typeof blockId === 'string' ? literal(blockId) : blockId\n    const taskKey = typeof blockId === 'string' ? literal(`field:${blockId}`) : code`\"field:\" + String(${blockId})`\n\n    generator.comment('Register field validation')\n    generator.scope(() => {\n      const runValidation = this.compileFieldValidationRunFunction(\n        rules,\n        blockIdCode,\n        blockCode,\n        ruleIsActive,\n        functionPrefix,\n        generator,\n      )\n      const props = generator.const(\n        'fieldValidationProps',\n        objectCode([\n          { key: 'blockId', value: blockIdCode },\n          { key: 'blockCode', value: blockCode },\n          { key: 'run', value: runValidation },\n        ]),\n      )\n\n      generator.statement(code`${fieldValidations}.push(${CONTEXT}.workTasks.fieldValidation(${taskKey}, ${props}))`)\n    })\n  }\n\n  private compileDomainValidationSlot(\n    rules: ValidationRulesModel | undefined,\n    domainValidations: IdentifierName,\n    ruleIsActive: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    if (rules === undefined) {\n      return\n    }\n\n    generator.comment('Register step validation')\n    generator.scope(() => {\n      const runValidation = this.compileDomainValidationRunFunction(rules, ruleIsActive, generator)\n      const props = generator.const('domainValidationProps', objectCode([{ key: 'run', value: runValidation }]))\n\n      generator.statement(code`${domainValidations}.push(${CONTEXT}.workTasks.domainValidation(\"domain:0\", ${props}))`)\n    })\n  }\n\n  private compileFieldValidationRunFunction(\n    rules: ValidationRulesModel,\n    blockId: CodeFragment,\n    blockCode: SafeCode,\n    ruleIsActive: IdentifierName,\n    functionPrefix: string,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    let bodyUsesAwait = false\n\n    return generator.function(\n      functionPrefix,\n      [],\n      body => {\n        bodyUsesAwait = this.expr.trackNestedFunctionAwait(() =>\n          this.expr.withGeneratorScope(body, () => {\n            const validationResults = this.compileValidationRules(\n              rules,\n              this.compileValidationEvaluationPrefix(functionPrefix),\n              body,\n            )\n            const fieldIdentity = objectCode([\n              { key: 'blockId', value: blockId },\n              { key: 'blockCode', value: blockCode },\n            ])\n\n            body.blank()\n            this.compileValidationFailuresReturn(\n              'collectFieldValidationFailures',\n              [validationResults, ruleIsActive, fieldIdentity],\n              body,\n            )\n          }),\n        )\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  private compileDomainValidationRunFunction(\n    rules: ValidationRulesModel,\n    ruleIsActive: IdentifierName,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    let bodyUsesAwait = false\n\n    return generator.function(\n      'validateStep',\n      [],\n      body => {\n        bodyUsesAwait = this.expr.trackNestedFunctionAwait(() =>\n          this.expr.withGeneratorScope(body, () => {\n            const validationResults = this.compileValidationRules(rules, 'step', body)\n\n            body.blank()\n            this.compileValidationFailuresReturn(\n              'collectDomainValidationFailures',\n              [validationResults, ruleIsActive],\n              body,\n            )\n          }),\n        )\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  private compileRuleFilterSetup(generator: CodeGenerator): IdentifierName {\n    generator.comment('Active validation groups')\n    generator.note('Use the default group when the request does not select one.')\n    const requestedGroups = generator.const(\n      'requestedGroups',\n      code`${FILTER}.groups.length > 0 ? ${FILTER}.groups : ${arrayCode([literal('default')])}`,\n    )\n    const activeGroups = generator.const('activeGroups', code`new Set(${requestedGroups})`)\n\n    const ruleIsActive = generator.function('ruleIsActive', ['rule'], (body, [rule]) => {\n      body.note('Use the default group when the rule does not declare one.')\n      const ruleGroups = body.const(\n        'ruleGroups',\n        code`Array.isArray(${rule}.groups) && ${rule}.groups.length > 0 ? ${rule}.groups : ${arrayCode([literal('default')])}`,\n      )\n\n      body.note('A rule runs when any of its groups is active.')\n      const isActiveValidationGroup = body.functionExpression(\n        'isActiveValidationGroup',\n        ['group'],\n        (predicateBody, [group]) => {\n          predicateBody.return(code`${activeGroups}.has(${group})`)\n        },\n      )\n      const hasActiveGroup = body.const('hasActiveGroup', callCode(code`${ruleGroups}.some`, [isActiveValidationGroup]))\n\n      body.if(code`!${hasActiveGroup}`, () => body.return(literal(false)))\n\n      body.note('Submission-only rules are skipped unless this validation run includes them.')\n      const submissionOnlyIsIncluded = body.const(\n        'submissionOnlyIsIncluded',\n        code`${FILTER}.includeSubmissionOnly === true`,\n      )\n\n      body.return(code`${rule}.submissionOnly !== true || ${submissionOnlyIsIncluded}`)\n    })\n\n    generator.blank()\n\n    return ruleIsActive\n  }\n\n  /** Emits the run function's return: one MaybeAsync runtime call that evaluates and shapes failures. */\n  private compileValidationFailuresReturn(\n    helperBaseName: string,\n    helperArguments: readonly SafeCode[],\n    generator: CodeGenerator,\n  ): void {\n    const helperCall = callCode(code`_forgeHelpers${propertyCode(helperBaseName)}`, helperArguments)\n\n    generator.return(helperCall)\n  }\n\n  private compileValidationRules(\n    rules: ValidationRulesModel,\n    functionPrefix: string,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    if (rules.kind === ValidationRulesKind.DIRECT) {\n      const validationRules = this.expr.withValidationFunctionPrefix(functionPrefix, () =>\n        rules.rules.map(rule => this.expr.compileOperandCode(rule.node, generator)),\n      )\n\n      generator.comment('Build validation rules')\n\n      return generator.const('validationRules', arrayCode(validationRules))\n    }\n\n    const validationResults = generator.let('validationResults')\n\n    this.expr.withValidationFunctionPrefix(functionPrefix, () => {\n      this.values.compileValue(rules.value, generator, validationResults)\n    })\n\n    return validationResults\n  }\n\n  /** The analysis phase only includes fields that have validation, so a field with no rules here is a bug. */\n  private resolveFieldRules(field: FieldModel): ValidationRulesModel {\n    if (field.validation === undefined) {\n      throw new ForgeInternalError(`Validation model field \"${field.label}\" carries no validation rules`)\n    }\n\n    return field.validation.rules\n  }\n\n  private compileTemplateBlockId(field: FieldModel): string | CodeFragment {\n    if (!isTemplateNode(field.source)) {\n      return field.source.id\n    }\n\n    return this.templates.compileTemplateInstanceIdExpression(field.source)\n  }\n\n  private compileValidationFunctionPrefix(field: FieldModel): string {\n    if (field.code?.kind !== FieldCodeKind.STATIC) {\n      return 'validateField'\n    }\n\n    const namePart = field.code.value.replace(/[^A-Za-z0-9_$]+/g, '_').replace(/^([^A-Za-z_$])/, '_$1')\n\n    return `validate_${namePart || 'field'}`\n  }\n\n  private compileValidationEvaluationPrefix(functionPrefix: string): string {\n    if (functionPrefix === 'validateField') {\n      return 'field'\n    }\n\n    return functionPrefix.replace(/^validate_/, '')\n  }\n}\n","/**\n * Compiles the `validateOnEntry` group selector for one step.\n *\n * This phase doesn't run validation itself. The `request.validities` phase has\n * already validated every step in non-submission mode, so the generated function\n * only decides which validation groups to display on the first GET render.\n *\n * Function calls go through the `FunctionRegistry` (the registry of author-\n * provided functions) because authors supply those implementations. The registry\n * knows whether a function is async, so it controls whether the generated source\n * is sync or async; the runtime awaits both.\n *\n * Generated-function construction failures throw `ForgeCompilationError`. There is\n * no secondary entry-validation execution path.\n */\nimport { StepEntryValidationAST } from '../../../chassis/contracts/ast/structures.type'\nimport { CodeFragment, code, literal } from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport type { ValidationModel } from '../contracts/validationModel.type'\n\nimport type { CompiledEntryValidationFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\n\n/**\n * Compiler for the step-level entry-validation generated function.\n *\n * It builds the source layout that accumulates matching validation groups, and\n * delegates each rule's `when` predicate to the shared expression dispatcher.\n */\nexport default class EntryValidationCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n  }\n\n  /**\n   * Builds the generated group-selector used before rendering a GET request.\n   */\n  compileOnEntryValidation(model: ValidationModel): CompiledEntryValidationFunction {\n    return compileGeneratedFunction<CompiledEntryValidationFunction>(\n      this.expr,\n      ['ctx'],\n      () => this.buildEntryValidationSource(model.entryValidation),\n      { phase: CompilationPhase.ENTRY_VALIDATION, label: model.label },\n    )\n  }\n\n  /**\n   * Produces inspectable entry-validation source for tests and local debugging.\n   */\n  generateOnEntryValidationSource(model: ValidationModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildEntryValidationSource(model.entryValidation))\n  }\n\n  /**\n   * Emits the entry-validation group selector used by GET rendering.\n   */\n  private buildEntryValidationSource(entries: readonly StepEntryValidationAST[]): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n\n    if (entries.length === 0) {\n      generator.note('This step declares no validateOnEntry rules, so no groups are selected.')\n      generator.return(code`[]`)\n\n      return generator\n    }\n\n    const groups = generator.const('groups', code`[]`)\n    const seen = generator.const('seen', code`Object.create(null)`)\n    const addGroup = this.compileEntryValidationGroupAccumulator(groups, seen, generator)\n\n    entries.forEach(entry => this.compileEntryValidationRule(entry, addGroup, generator))\n    generator.return(groups)\n\n    return generator\n  }\n\n  /**\n   * Emits a tiny local helper so repeated entry groups keep their first declaration position.\n   */\n  private compileEntryValidationGroupAccumulator(\n    groups: IdentifierName,\n    seen: IdentifierName,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    generator.comment('Record each matching group once, in first-declared order')\n\n    return generator.function('addGroup', ['group'], (functionGenerator, [group]) => {\n      const groupKey = functionGenerator.const('groupKey', code`String(${group})`)\n\n      functionGenerator.if(code`!${seen}[${groupKey}]`, () => {\n        functionGenerator.assign(code`${seen}[${groupKey}]`, literal(true))\n        functionGenerator.statement(code`${groups}.push(${groupKey})`)\n      })\n    })\n  }\n\n  /**\n   * Emits one validateOnEntry rule, preserving unconditional entries as direct group additions.\n   */\n  private compileEntryValidationRule(\n    entry: StepEntryValidationAST,\n    addGroup: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    generator.comment(`Entry rule — groups ${entry.groups.map(group => `\"${group}\"`).join(', ')}`)\n    generator.scope(() => {\n      if (entry.when === true) {\n        this.compileEntryValidationGroups(entry.groups, addGroup, generator)\n\n        return\n      }\n\n      const when = this.compileEntryValidationWhen(entry.when, generator)\n\n      generator.if(code`${when}`, () => this.compileEntryValidationGroups(entry.groups, addGroup, generator))\n    })\n  }\n\n  /**\n   * Emits a validateOnEntry predicate as a named boolean so generated source reads as a rule guard.\n   */\n  private compileEntryValidationWhen(\n    when: StepEntryValidationAST['when'],\n    generator: CodeGenerator,\n  ): CodeFragment | IdentifierName {\n    if (when === true) {\n      return literal(true)\n    }\n\n    const predicate = this.expr.compileExpressionCode(when, generator)\n\n    return generator.const('entryWhen', code`Boolean(${predicate})`)\n  }\n\n  /**\n   * Emits the declared validateOnEntry groups through addGroup to preserve uniqueness and ordering.\n   */\n  private compileEntryValidationGroups(\n    groups: readonly string[],\n    addGroup: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    groups.forEach(group => {\n      generator.statement(code`${addGroup}(${group})`)\n    })\n  }\n}\n","import { ASTNode } from '../../../chassis/contracts/ast/ast.type'\nimport type { CompiledReachabilityFactsFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport type {\n  ForwardOutcomeGroup,\n  ForwardRedirectOutcome,\n  ReachabilityEntryModel,\n  ReachabilityModel,\n  ReachabilityTieBreakerEntry,\n} from '../contracts/reachabilityModel.type'\nimport {\n  arrayCode,\n  CodeFragment,\n  code,\n  literal,\n  objectCode,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\n\ninterface ReachabilityResultNames {\n  readonly entryResults: IdentifierName\n  readonly outcomeValues: IdentifierName\n  readonly declaredOutcomeValues: IdentifierName\n  readonly tieBreakerPriorities: IdentifierName\n  readonly resumeActive: IdentifierName\n}\n\n/** Builds the generated function that evaluates reachability facts (entry predicates, forward outcomes, and tie-breakers) from the reachability model. */\nexport default class ReachabilityCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n  }\n\n  compileFacts(model: ReachabilityModel): CompiledReachabilityFactsFunction {\n    return compileGeneratedFunction<CompiledReachabilityFactsFunction>(\n      this.expr,\n      ['ctx'],\n      () => this.buildFactsSource(model),\n      { phase: CompilationPhase.REACHABILITY, label: model.label },\n    )\n  }\n\n  generateFactsSource(model: ReachabilityModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildFactsSource(model))\n  }\n\n  private buildFactsSource(model: ReachabilityModel): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n    const resultNames = this.compileReachabilityResult(model, generator)\n\n    generator.return(this.buildReachabilityResultExpression(resultNames))\n\n    return generator\n  }\n\n  private compileReachabilityResult(model: ReachabilityModel, generator: CodeGenerator): ReachabilityResultNames {\n    const stepCount = model.entries.length\n\n    generator.note(this.buildStepOrderNote(model.entries))\n    const entryResults = generator.const('entryResults', code`new Array(${stepCount})`)\n    const outcomeValues = generator.const('outcomeValues', arrayCode(model.entries.map(() => code`[]`)))\n    const declaredOutcomeValues = generator.const('declaredOutcomeValues', arrayCode(model.entries.map(() => code`[]`)))\n    const tieBreakerPriorities = generator.const('tieBreakerPriorities', code`new Array(${stepCount})`)\n\n    this.compileEntryPredicates(model.entries, entryResults, generator)\n    this.compileForwardOutcomes(model.entries, outcomeValues, declaredOutcomeValues, generator)\n    this.compileTieBreakers(model.entries, tieBreakerPriorities, generator)\n    const resumeActive = this.compileResumeCondition(model, generator)\n\n    return { entryResults, outcomeValues, declaredOutcomeValues, tieBreakerPriorities, resumeActive }\n  }\n\n  /** The result arrays are indexed by step position; this map is the reader's only key. */\n  private buildStepOrderNote(entries: readonly ReachabilityEntryModel[]): string {\n    return `Step order: ${entries.map((entry, index) => `${index} \"${this.stepLabel(entry)}\"`).join(', ')}`\n  }\n\n  private stepLabel(entry: ReachabilityEntryModel): string {\n    return entry.code ?? entry.stepId\n  }\n\n  private buildReachabilityResultExpression(names: ReachabilityResultNames): CodeFragment {\n    return objectCode([\n      { key: 'entryResults', value: names.entryResults },\n      { key: 'outcomeValues', value: names.outcomeValues },\n      { key: 'declaredOutcomeValues', value: names.declaredOutcomeValues },\n      { key: 'tieBreakerPriorities', value: names.tieBreakerPriorities },\n      { key: 'resumeActive', value: names.resumeActive },\n    ])\n  }\n\n  private compileEntryPredicates(\n    entries: readonly ReachabilityEntryModel[],\n    entryResults: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    entries.forEach((entry, index) => {\n      const node = entry.entryWhen\n\n      if (node === undefined) {\n        return\n      }\n\n      generator.comment(`Entry predicate — step \"${this.stepLabel(entry)}\"`)\n      generator.assign(\n        code`${entryResults}[${index}]`,\n        code`Boolean(${this.expr.compileExpressionCode(node, generator)})`,\n      )\n    })\n  }\n\n  private compileForwardOutcomes(\n    entries: readonly ReachabilityEntryModel[],\n    outcomeValues: IdentifierName,\n    declaredOutcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    entries.forEach((entry, stepIndex) => {\n      if (entry.forwardOutcomeGroups.length === 0) {\n        return\n      }\n\n      generator.comment(`Forward outcomes — step \"${this.stepLabel(entry)}\"`)\n      entry.forwardOutcomeGroups.forEach(group => {\n        this.compileForwardOutcomeGroup(group, stepIndex, outcomeValues, declaredOutcomeValues, generator)\n      })\n    })\n  }\n\n  private compileForwardOutcomeGroup(\n    group: ForwardOutcomeGroup,\n    stepIndex: number,\n    outcomeValues: IdentifierName,\n    declaredOutcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    group.redirectOutcomes.forEach(outcome => {\n      this.compileDeclaredGotoResolution(outcome.node.properties.goto, stepIndex, declaredOutcomeValues, generator)\n    })\n\n    const emitCascade = () => {\n      if (this.hasOnlyStaticGotos(group)) {\n        this.compileStaticOutcomeChain(group.redirectOutcomes, stepIndex, outcomeValues, generator)\n\n        return\n      }\n\n      const outcomeMatched = generator.let('outcomeMatched', literal(false))\n\n      group.redirectOutcomes.forEach(outcome => {\n        this.compileForwardOutcomeCascade(\n          outcome.node.properties,\n          stepIndex,\n          outcomeMatched,\n          outcome.overApproximatesWhen,\n          outcomeValues,\n          generator,\n        )\n      })\n    }\n\n    const hookWhenNode = group.hookWhen\n\n    if (hookWhenNode !== undefined) {\n      const hookWhen = generator.const(\n        'hookWhen',\n        code`Boolean(${this.expr.compileExpressionCode(hookWhenNode, generator)})`,\n      )\n\n      generator.if(hookWhen, emitCascade)\n\n      return\n    }\n\n    emitCascade()\n  }\n\n  private hasOnlyStaticGotos(group: ForwardOutcomeGroup): boolean {\n    return group.redirectOutcomes.every(outcome => typeof outcome.node.properties.goto === 'string')\n  }\n\n  /**\n   * Emits a cascade of statically-addressed outcomes as an if/else chain: each\n   * guarded outcome falls through to the rest only when its condition fails, an\n   * over-approximated outcome contributes without stopping the cascade, and an\n   * unconditional outcome ends it (anything after it could never run).\n   */\n  private compileStaticOutcomeChain(\n    outcomes: readonly ForwardRedirectOutcome[],\n    stepIndex: number,\n    outcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const [outcome, ...remainingOutcomes] = outcomes\n\n    if (outcome === undefined) {\n      return\n    }\n\n    const { when, goto } = outcome.node.properties\n    const pushGoto = () => generator.statement(code`${outcomeValues}[${stepIndex}].push(${literal(goto)})`)\n\n    if (outcome.overApproximatesWhen) {\n      pushGoto()\n      this.compileStaticOutcomeChain(remainingOutcomes, stepIndex, outcomeValues, generator)\n\n      return\n    }\n\n    if (when !== undefined && this.expr.isCompilableNode(when)) {\n      const outcomeWhen = generator.const(\n        'outcomeWhen',\n        code`Boolean(${this.expr.compileExpressionCode(when, generator)})`,\n      )\n      const emitRemaining =\n        remainingOutcomes.length > 0\n          ? () => this.compileStaticOutcomeChain(remainingOutcomes, stepIndex, outcomeValues, generator)\n          : undefined\n\n      generator.if(outcomeWhen, pushGoto, emitRemaining)\n\n      return\n    }\n\n    pushGoto()\n  }\n\n  private compileForwardOutcomeCascade(\n    properties: { readonly when?: ASTNode; readonly goto: ASTNode | string },\n    stepIndex: number,\n    outcomeMatched: IdentifierName,\n    overApproximateWhen: boolean,\n    outcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    generator.if(code`${outcomeMatched} === false`, () => {\n      const { when, goto } = properties\n\n      if (!overApproximateWhen && when !== undefined && this.expr.isCompilableNode(when)) {\n        const outcomeWhen = generator.const(\n          'outcomeWhen',\n          code`Boolean(${this.expr.compileExpressionCode(when, generator)})`,\n        )\n\n        generator.if(outcomeWhen, () => {\n          this.compileGotoResolution(goto, stepIndex, outcomeMatched, true, outcomeValues, generator)\n        })\n\n        return\n      }\n\n      this.compileGotoResolution(goto, stepIndex, outcomeMatched, !overApproximateWhen, outcomeValues, generator)\n    })\n  }\n\n  private compileDeclaredGotoResolution(\n    goto: ASTNode | string,\n    stepIndex: number,\n    declaredOutcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    if (typeof goto !== 'string') {\n      return\n    }\n\n    generator.statement(code`${declaredOutcomeValues}[${stepIndex}].push(${goto})`)\n  }\n\n  private compileGotoResolution(\n    goto: ASTNode | string,\n    stepIndex: number,\n    outcomeMatched: IdentifierName,\n    marksOutcomeMatched: boolean,\n    outcomeValues: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const gotoExpression = this.compileGotoExpression(goto, generator)\n\n    if (gotoExpression === undefined) {\n      return\n    }\n\n    const gotoValue = generator.const('gotoValue', gotoExpression)\n\n    generator.if(code`${gotoValue} !== undefined`, () => {\n      generator.statement(code`${outcomeValues}[${stepIndex}].push(String(${gotoValue}))`)\n\n      if (marksOutcomeMatched) {\n        generator.assign(outcomeMatched, literal(true))\n      }\n    })\n  }\n\n  private compileGotoExpression(goto: ASTNode | string, generator: CodeGenerator): CodeFragment | undefined {\n    if (typeof goto === 'string') {\n      return literal(goto)\n    }\n\n    return this.expr.isCompilableNode(goto) ? this.expr.compileExpressionCode(goto, generator) : undefined\n  }\n\n  private compileTieBreakers(\n    entries: readonly ReachabilityEntryModel[],\n    tieBreakerPriorities: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    entries.forEach((entry, index) => {\n      if (entry.reachabilityTieBreakers.length === 0) {\n        return\n      }\n\n      generator.comment(`Tie-breaker priority — step \"${this.stepLabel(entry)}\"`)\n      this.compileTieBreakerChain(entry.reachabilityTieBreakers, index, tieBreakerPriorities, generator)\n    })\n  }\n\n  /**\n   * Emits tie-breaker rules as an if/else chain taking the first matching rule's\n   * priority. An unconditional rule ends the chain (later rules could never run);\n   * when no rule matches, the step's slot stays unset.\n   */\n  private compileTieBreakerChain(\n    tieBreakers: readonly ReachabilityTieBreakerEntry[],\n    stepIndex: number,\n    tieBreakerPriorities: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const [tieBreaker, ...remainingTieBreakers] = tieBreakers\n\n    if (tieBreaker === undefined) {\n      return\n    }\n\n    const assignPriority = () =>\n      generator.assign(code`${tieBreakerPriorities}[${stepIndex}]`, literal(tieBreaker.priority))\n\n    if (tieBreaker.when === undefined) {\n      assignPriority()\n\n      return\n    }\n\n    const tieBreakerWhen = generator.const(\n      'tieBreakerWhen',\n      code`Boolean(${this.expr.compileExpressionCode(tieBreaker.when, generator)})`,\n    )\n    const emitRemaining =\n      remainingTieBreakers.length > 0\n        ? () => this.compileTieBreakerChain(remainingTieBreakers, stepIndex, tieBreakerPriorities, generator)\n        : undefined\n\n    generator.if(tieBreakerWhen, assignPriority, emitRemaining)\n  }\n\n  private compileResumeCondition(model: ReachabilityModel, generator: CodeGenerator): IdentifierName {\n    if (model.resumeAlways) {\n      return generator.const('resumeActive', literal(true))\n    }\n\n    if (model.resumeWhen === undefined) {\n      return generator.const('resumeActive', literal(false))\n    }\n\n    return generator.const(\n      'resumeActive',\n      code`Boolean(${this.expr.compileExpressionCode(model.resumeWhen, generator)})`,\n    )\n  }\n}\n","import { NodeId } from '../../../../chassis/contracts/ast/ast.type'\nimport { ReachabilityNode } from '../../contracts/reachabilityEvaluation.type'\n\nexport interface ReachabilityPathAnalysis {\n  canonicalPathRouteTemplatePaths: string[]\n  frontierRouteTemplatePath: string | undefined\n  progressExists: boolean\n}\n\ninterface ProgressPathCandidate {\n  entry: ReachabilityNode\n  path: ReachabilityNode[]\n  progressDepth: number\n}\n\n/**\n * Picks the winning candidate according to reachability tie-breakers.\n *\n * Candidates must be supplied in journey declaration order. The highest\n * compiled priority wins; unmatched candidates fall back to declaration order.\n */\nexport function pickTieBreakerWinner(candidates: ReachabilityNode[]): ReachabilityNode | undefined {\n  if (candidates.length === 0) {\n    return undefined\n  }\n\n  return candidates.reduce((best, candidate) => {\n    const bestPriority = best.tieBreakerPriority ?? -Infinity\n    const candidatePriority = candidate.tieBreakerPriority ?? -Infinity\n\n    return candidatePriority > bestPriority ? candidate : best\n  })\n}\n\nexport function resolveBacklinkRouteTemplatePathForStep(\n  step: ReachabilityNode | undefined,\n  canonicalPathRouteTemplatePaths: string[],\n): string | undefined {\n  if (!step) {\n    return undefined\n  }\n\n  const currentIndex = canonicalPathRouteTemplatePaths.indexOf(step.routeTemplatePath)\n\n  if (currentIndex <= 0) {\n    return undefined\n  }\n\n  return canonicalPathRouteTemplatePaths[currentIndex - 1]\n}\n\nexport default class ReachabilityPathAnalyzer {\n  analyze(\n    steps: ReachabilityNode[],\n    currentStepId: NodeId | undefined,\n    defaultEntryRouteTemplatePath: string | undefined,\n    resumeActive: boolean,\n  ): ReachabilityPathAnalysis {\n    const stepByRouteTemplatePath = new Map(steps.map(step => [step.routeTemplatePath, step]))\n    const progressExists = this.resolveProgressExists(steps)\n    const defaultPath = this.resolvePathFromAnchorRouteTemplatePath(\n      defaultEntryRouteTemplatePath,\n      stepByRouteTemplatePath,\n    )\n    const resumePath = this.resolveResumePath(steps, stepByRouteTemplatePath)\n    const canonicalPath = this.resolveCanonicalPath(\n      steps,\n      currentStepId,\n      resumeActive,\n      defaultPath,\n      resumePath,\n      stepByRouteTemplatePath,\n    )\n\n    return {\n      canonicalPathRouteTemplatePaths: canonicalPath.map(step => step.routeTemplatePath),\n      frontierRouteTemplatePath: this.resolveFrontierRouteTemplatePath(canonicalPath),\n      progressExists,\n    }\n  }\n\n  private resolveCanonicalPath(\n    steps: ReachabilityNode[],\n    currentStepId: NodeId | undefined,\n    resumeActive: boolean,\n    defaultPath: ReachabilityNode[],\n    resumePath: ReachabilityNode[] | undefined,\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    if (resumeActive && resumePath) {\n      return resumePath\n    }\n\n    if (currentStepId !== undefined) {\n      const currentStepPath = this.resolvePathThroughCurrentStep(currentStepId, steps, stepByRouteTemplatePath)\n\n      if (currentStepPath.length > 0) {\n        return currentStepPath\n      }\n    }\n\n    return defaultPath\n  }\n\n  private resolveProgressExists(steps: ReachabilityNode[]): boolean {\n    return steps.some(step => step.isReachable && step.hasValidation && step.isValid)\n  }\n\n  private resolveResumePath(\n    steps: ReachabilityNode[],\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] | undefined {\n    const candidates = steps\n      .filter(step => this.isActiveEntry(step))\n      .map(entry => {\n        const path = this.resolvePathFromAnchorStep(entry, stepByRouteTemplatePath)\n\n        return {\n          entry,\n          path,\n          progressDepth: this.resolveProgressDepth(path),\n        } satisfies ProgressPathCandidate\n      })\n      .filter(candidate => candidate.progressDepth >= 0)\n\n    if (candidates.length === 0) {\n      return undefined\n    }\n\n    const winner = candidates.reduce((best, candidate) => {\n      if (candidate.progressDepth !== best.progressDepth) {\n        return candidate.progressDepth > best.progressDepth ? candidate : best\n      }\n\n      const tieBreakerWinner = pickTieBreakerWinner([best.entry, candidate.entry])\n\n      if (tieBreakerWinner?.routeTemplatePath === candidate.entry.routeTemplatePath) {\n        return candidate\n      }\n\n      return best\n    })\n\n    return winner.path\n  }\n\n  private resolveProgressDepth(path: ReachabilityNode[]): number {\n    let lastProgressIndex = -1\n\n    path.forEach((step, index) => {\n      if (step.isReachable && step.hasValidation && step.isValid) {\n        lastProgressIndex = index\n      }\n    })\n\n    return lastProgressIndex\n  }\n\n  private resolvePathThroughCurrentStep(\n    currentStepId: NodeId,\n    steps: ReachabilityNode[],\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    const currentStep = steps.find(step => step.stepId === currentStepId)\n\n    if (!currentStep?.isReachable) {\n      return []\n    }\n\n    const pathToCurrent = this.resolvePathToCurrentStep(currentStep, stepByRouteTemplatePath)\n    const pathFromCurrent = this.resolveForwardPath(currentStep, stepByRouteTemplatePath)\n\n    return [...pathToCurrent, ...pathFromCurrent.slice(1)]\n  }\n\n  private resolvePathToCurrentStep(\n    step: ReachabilityNode,\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    const path = [step]\n    const visited = new Set([step.routeTemplatePath])\n    let current = step\n\n    while (!this.isActiveEntry(current) && current.predecessorRouteTemplatePaths.length > 0) {\n      const predecessors = current.predecessorRouteTemplatePaths\n        .map(routeTemplatePath => stepByRouteTemplatePath.get(routeTemplatePath))\n        .filter((candidate): candidate is ReachabilityNode => candidate !== undefined)\n\n      const previous = pickTieBreakerWinner(predecessors)\n\n      if (!previous || visited.has(previous.routeTemplatePath)) {\n        break\n      }\n\n      path.unshift(previous)\n      visited.add(previous.routeTemplatePath)\n      current = previous\n    }\n\n    return path\n  }\n\n  private resolvePathFromAnchorRouteTemplatePath(\n    anchorRouteTemplatePath: string | undefined,\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    if (!anchorRouteTemplatePath) {\n      return []\n    }\n\n    const anchor = stepByRouteTemplatePath.get(anchorRouteTemplatePath)\n\n    if (!anchor) {\n      return []\n    }\n\n    if (!anchor.isReachable) {\n      return [anchor]\n    }\n\n    return this.resolvePathFromAnchorStep(anchor, stepByRouteTemplatePath)\n  }\n\n  private resolvePathFromAnchorStep(\n    anchor: ReachabilityNode,\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    if (!anchor.isReachable) {\n      return [anchor]\n    }\n\n    return this.resolveForwardPath(anchor, stepByRouteTemplatePath)\n  }\n\n  private resolveForwardPath(\n    start: ReachabilityNode,\n    stepByRouteTemplatePath: ReadonlyMap<string, ReachabilityNode>,\n  ): ReachabilityNode[] {\n    const path = [start]\n    const visited = new Set([start.routeTemplatePath])\n    let current = start\n\n    while (current.isValid && current.forwardRouteTemplatePaths.length > 0) {\n      const successors = current.forwardRouteTemplatePaths\n        .map(routeTemplatePath => stepByRouteTemplatePath.get(routeTemplatePath))\n        .filter((candidate): candidate is ReachabilityNode => candidate !== undefined && candidate.isReachable)\n\n      const next = pickTieBreakerWinner(successors)\n\n      if (!next || visited.has(next.routeTemplatePath)) {\n        break\n      }\n\n      path.push(next)\n      visited.add(next.routeTemplatePath)\n      current = next\n    }\n\n    return path\n  }\n\n  private resolveFrontierRouteTemplatePath(path: ReachabilityNode[]): string | undefined {\n    const nonEntrySteps = path.filter(step => !this.isActiveEntry(step))\n    const firstInvalid = nonEntrySteps.find(step => !step.isValid)\n\n    if (firstInvalid) {\n      return firstInvalid.routeTemplatePath\n    }\n\n    const hasProgress = nonEntrySteps.some(step => step.hasValidation && step.isValid)\n    const terminal = nonEntrySteps[nonEntrySteps.length - 1]\n\n    if (hasProgress && terminal && !(terminal.hasValidation && terminal.isValid)) {\n      return terminal.routeTemplatePath\n    }\n\n    return undefined\n  }\n\n  private isActiveEntry(step: ReachabilityNode): boolean {\n    return step.isEntryPoint || step.isConditionalEntry\n  }\n}\n","export function resolveRouteTemplateTargetPath(target: string, currentRouteTemplatePath: string): string | undefined {\n  if (target.startsWith('http://') || target.startsWith('https://') || target.startsWith('//')) {\n    return undefined\n  }\n\n  const pathOnly = stripSearchAndHash(target)\n\n  if (pathOnly.startsWith('/')) {\n    return normalizePath(pathOnly, [])\n  }\n\n  return normalizePath(pathOnly, getBaseSegments(currentRouteTemplatePath))\n}\n\nfunction stripSearchAndHash(value: string): string {\n  const queryIndex = value.indexOf('?')\n  const hashIndex = value.indexOf('#')\n  const indexes = [queryIndex, hashIndex].filter(index => index >= 0)\n\n  if (indexes.length === 0) {\n    return value\n  }\n\n  return value.slice(0, Math.min(...indexes))\n}\n\nfunction getBaseSegments(currentRouteTemplatePath: string): string[] {\n  const currentSegments = splitPath(currentRouteTemplatePath)\n\n  if (currentRouteTemplatePath.endsWith('/')) {\n    return currentSegments\n  }\n\n  return currentSegments.slice(0, -1)\n}\n\nfunction normalizePath(path: string, baseSegments: string[]): string {\n  const segments = [...baseSegments]\n\n  splitPath(path).forEach(segment => {\n    if (segment === '.') {\n      return\n    }\n\n    if (segment === '..') {\n      segments.pop()\n\n      return\n    }\n\n    segments.push(segment)\n  })\n\n  return `/${segments.join('/')}`\n}\n\nfunction splitPath(path: string): string[] {\n  return path.split('/').filter(segment => segment.length > 0)\n}\n","import type { ReachabilityStateTableEntry, ReachabilityStateTable } from '../../contracts/reachabilityModel.type'\nimport { pickTieBreakerWinner } from './ReachabilityPathAnalyzer'\nimport type { JourneyRouteTemplateCatalog } from '../../../route/contracts/routeTree.type'\nimport type { NodeId } from '../../../../chassis/contracts/ast/ast.type'\nimport type { ReachabilityNode } from '../../contracts/reachabilityEvaluation.type'\nimport type { CompiledReachabilityResult } from '../../../../chassis/contracts/compiled/compiledFunctions.type'\nimport { resolveRouteTemplateTargetPath } from './routeTemplateTargetResolver'\nimport ForgeInternalError from '../../../../errors/ForgeInternalError'\n\n/**\n * Builds the reachability state for a journey: marks entry points as reachable,\n * walks forward from them through the step graph, and resolves each step's\n * forward, declared-forward, and predecessor route-template paths plus its\n * tie-breaker priority.\n *\n * Entry predicates, forward outcomes, and tie-breaker priorities come from the\n * compiled reachability facts. Per-step validity (whether the step's validation\n * passes in non-submission, default-group mode) is read from the `stepValidities`\n * map; a step absent from the map has no validation and is treated as valid. An\n * invalid step doesn't propagate reachability to its successors.\n */\nexport default class ReachabilityGraphBuilder {\n  private steps!: ReachabilityNode[]\n\n  private compiled!: CompiledReachabilityResult\n\n  private routeTemplateCatalog!: JourneyRouteTemplateCatalog\n\n  private stepValidities!: ReadonlyMap<NodeId, boolean>\n\n  private stateByRouteTemplatePath!: Map<string, ReachabilityNode>\n\n  private stepIndexByStepId!: Map<NodeId, number>\n\n  buildReachableSteps(\n    plan: ReachabilityStateTable,\n    routeTemplateCatalog: JourneyRouteTemplateCatalog,\n    compiledResult: CompiledReachabilityResult,\n    stepValidities: ReadonlyMap<NodeId, boolean>,\n  ): ReachabilityNode[] {\n    this.compiled = compiledResult\n    this.routeTemplateCatalog = routeTemplateCatalog\n    this.stepValidities = stepValidities\n    this.steps = this.createStepStates(plan.entries)\n    this.stateByRouteTemplatePath = new Map(this.steps.map(step => [step.routeTemplatePath, step]))\n    this.stepIndexByStepId = new Map(plan.entries.map((entry, index) => [entry.stepId, index]))\n\n    if (plan.reachabilityDisabled) {\n      this.steps.forEach(step => {\n        step.isReachable = true\n      })\n\n      this.populateDeclaredForwardPaths()\n      this.applyCompiledTieBreakers()\n\n      return this.steps\n    }\n\n    this.seedEntryPoints(plan.entries)\n    this.walkReachabilityGraph()\n    this.populateUnvisitedForwardPaths()\n    this.populateDeclaredForwardPaths()\n    this.applyCompiledTieBreakers()\n\n    return this.steps\n  }\n\n  resolveDefaultEntryRouteTemplatePath(): string | undefined {\n    const activeEntries = this.steps.filter(step => step.isEntryPoint || step.isConditionalEntry)\n    const winner = pickTieBreakerWinner(activeEntries)\n\n    if (winner) {\n      return winner.routeTemplatePath\n    }\n\n    return this.steps[0]?.routeTemplatePath\n  }\n\n  private createStepStates(entries: ReachabilityStateTableEntry[]): ReachabilityNode[] {\n    return entries.map((entry, declarationIndex) => {\n      const routeTemplatePath = this.routeTemplateCatalog.routeTemplatePathByStepId.get(entry.stepId)\n\n      if (!routeTemplatePath) {\n        throw new ForgeInternalError(`Route template path missing for step ${entry.stepId}`)\n      }\n\n      return {\n        stepId: entry.stepId,\n        routeTemplatePath,\n        code: entry.code,\n        declarationIndex,\n        isEntryPoint: entry.isEntryPoint,\n        isConditionalEntry: false,\n        hasValidation: this.stepValidities.has(entry.stepId),\n        isReachable: false,\n        isValid: true,\n        forwardRouteTemplatePaths: [],\n        declaredForwardRouteTemplatePaths: [],\n        predecessorRouteTemplatePaths: [],\n      }\n    })\n  }\n\n  private seedEntryPoints(entries: ReachabilityStateTableEntry[]): void {\n    entries.forEach((entry, index) => {\n      if (entry.isEntryPoint) {\n        this.steps[index].isReachable = true\n      }\n\n      if (this.compiled.entryResults[index] === true) {\n        this.steps[index].isReachable = true\n        this.steps[index].isConditionalEntry = true\n      }\n    })\n  }\n\n  private walkReachabilityGraph(): void {\n    if (this.steps.length === 0) {\n      return\n    }\n\n    const queue = this.steps.filter(step => step.isReachable).map(step => step.routeTemplatePath)\n    const enqueued = new Set(queue)\n    let queueIndex = 0\n\n    while (queueIndex < queue.length) {\n      const current = this.stateByRouteTemplatePath.get(queue[queueIndex])\n\n      queueIndex += 1\n\n      if (!current) {\n        continue\n      }\n\n      this.evaluateStepReachability(current)\n      this.propagateToSuccessors(current, queue, enqueued)\n    }\n  }\n\n  private evaluateStepReachability(step: ReachabilityNode): void {\n    // Absence from the map means the step has no validation, so it is valid and\n    // cannot block forward reachability. The map only carries validity in\n    // reachability mode (non-submission, default group), so `submissionOnly`\n    // rules and off-default-group failures don't block forward propagation.\n    step.isValid = this.stepValidities.get(step.stepId) ?? true\n\n    const entryIndex = this.stepIndexByStepId.get(step.stepId)!\n\n    step.forwardRouteTemplatePaths = this.resolveForwardPaths(step.routeTemplatePath, entryIndex)\n  }\n\n  private propagateToSuccessors(current: ReachabilityNode, queue: string[], enqueued: Set<string>): void {\n    current.forwardRouteTemplatePaths.forEach(forwardRouteTemplatePath => {\n      const next = this.stateByRouteTemplatePath.get(forwardRouteTemplatePath)\n\n      if (!next) {\n        return\n      }\n\n      if (!next.predecessorRouteTemplatePaths.includes(current.routeTemplatePath)) {\n        next.predecessorRouteTemplatePaths.push(current.routeTemplatePath)\n      }\n\n      if (!current.isValid) {\n        return\n      }\n\n      if (!next.isReachable) {\n        next.isReachable = true\n      }\n\n      if (enqueued.has(next.routeTemplatePath)) {\n        return\n      }\n\n      enqueued.add(next.routeTemplatePath)\n      queue.push(next.routeTemplatePath)\n    })\n  }\n\n  private resolveForwardPaths(currentRouteTemplatePath: string, stepIndex: number): string[] {\n    const outcomeStrings = this.compiled.outcomeValues[stepIndex] ?? []\n\n    return this.resolveRouteTemplatePaths(outcomeStrings, currentRouteTemplatePath)\n  }\n\n  private resolveDeclaredForwardPaths(currentRouteTemplatePath: string, stepIndex: number): string[] {\n    const declaredOutcomeStrings = this.compiled.declaredOutcomeValues[stepIndex] ?? []\n\n    if (declaredOutcomeStrings.length === 0) {\n      return this.resolveForwardPaths(currentRouteTemplatePath, stepIndex)\n    }\n\n    return this.resolveRouteTemplatePaths(declaredOutcomeStrings, currentRouteTemplatePath)\n  }\n\n  private resolveRouteTemplatePaths(\n    outcomeStrings: readonly (string | undefined)[],\n    currentRouteTemplatePath: string,\n  ): string[] {\n    const routeTemplatePaths = new Set<string>()\n\n    outcomeStrings.forEach(outcomeStr => {\n      if (outcomeStr === undefined) {\n        return\n      }\n\n      const routeTemplatePath = resolveRouteTemplateTargetPath(outcomeStr, currentRouteTemplatePath)\n\n      if (\n        routeTemplatePath === undefined ||\n        !this.routeTemplateCatalog.stepIdByRouteTemplatePath.has(routeTemplatePath)\n      ) {\n        return\n      }\n\n      routeTemplatePaths.add(routeTemplatePath)\n    })\n\n    return [...routeTemplatePaths]\n  }\n\n  private populateUnvisitedForwardPaths(): void {\n    this.steps.forEach((step, index) => {\n      if (step.forwardRouteTemplatePaths.length > 0) {\n        return\n      }\n\n      step.forwardRouteTemplatePaths = this.resolveForwardPaths(step.routeTemplatePath, index)\n\n      step.forwardRouteTemplatePaths.forEach(forwardPath => {\n        const next = this.stateByRouteTemplatePath.get(forwardPath)\n\n        if (!next || next.predecessorRouteTemplatePaths.includes(step.routeTemplatePath)) {\n          return\n        }\n\n        next.predecessorRouteTemplatePaths.push(step.routeTemplatePath)\n      })\n    })\n  }\n\n  private populateDeclaredForwardPaths(): void {\n    this.steps.forEach((step, index) => {\n      step.declaredForwardRouteTemplatePaths = this.resolveDeclaredForwardPaths(step.routeTemplatePath, index)\n    })\n  }\n\n  private applyCompiledTieBreakers(): void {\n    for (let index = 0; index < this.steps.length; index++) {\n      if (!this.steps[index].isReachable) {\n        continue\n      }\n\n      this.steps[index].tieBreakerPriority = this.compiled.tieBreakerPriorities[index]\n    }\n  }\n}\n","import { resolvePathParams } from '../../../../../shared/routePath'\nimport {\n  JourneyReachabilityProjection,\n  StepReachabilityProjection,\n} from '../../contracts/journeyReachabilityProjection.type'\nimport { ReachabilityEvaluation, ReachabilityNode } from '../../contracts/reachabilityEvaluation.type'\nimport { resolveBacklinkRouteTemplatePathForStep } from './ReachabilityPathAnalyzer'\nimport { StepFieldInventory } from '../../../answer-cleardown/contracts/stepFieldInventory.type'\n\nexport default class ReachabilityStateProjector {\n  project(\n    evaluation: ReachabilityEvaluation,\n    fieldInventory: StepFieldInventory[],\n    params: Record<string, string>,\n  ): JourneyReachabilityProjection {\n    const inventoryByStepId = new Map(fieldInventory.map(inv => [inv.stepId, inv]))\n    const reachableSteps: StepReachabilityProjection[] = []\n    const unreachableSteps: StepReachabilityProjection[] = []\n\n    evaluation.steps.forEach(step => {\n      const inventory = inventoryByStepId.get(step.stepId)\n      const projectedStep = this.projectStep(step, inventory, params, evaluation.canonicalPathRouteTemplatePaths)\n\n      if (step.isReachable) {\n        reachableSteps.push(projectedStep)\n      } else {\n        unreachableSteps.push(projectedStep)\n      }\n    })\n\n    return {\n      reachableSteps,\n      unreachableSteps,\n    }\n  }\n\n  private projectStep(\n    step: ReachabilityNode,\n    inventory: StepFieldInventory | undefined,\n    params: Record<string, string>,\n    canonicalPathRouteTemplatePaths: string[],\n  ): StepReachabilityProjection {\n    const projectedStep: StepReachabilityProjection = { path: resolvePathParams(step.routeTemplatePath, params) }\n\n    if (step.code) {\n      projectedStep.code = step.code\n    }\n\n    const fieldCodes = inventory?.fieldCodes ?? []\n    const cleardownFieldCodes = inventory?.cleardownFieldCodes ?? []\n\n    if (fieldCodes.length > 0) {\n      projectedStep.fieldCodes = fieldCodes\n    }\n\n    if (cleardownFieldCodes.length > 0) {\n      projectedStep.cleardownFieldCodes = cleardownFieldCodes\n    }\n\n    const backPath = resolveBacklinkRouteTemplatePathForStep(step, canonicalPathRouteTemplatePaths)\n\n    if (backPath) {\n      projectedStep.backPath = resolvePathParams(backPath, params)\n    }\n\n    return projectedStep\n  }\n}\n","import ReachabilityPathAnalyzer from './ReachabilityPathAnalyzer'\nimport ReachabilityGraphBuilder from './ReachabilityGraphBuilder'\nimport ReachabilityStateProjector from './ReachabilityStateProjector'\nimport type { ReachabilityStateTable } from '../../contracts/reachabilityModel.type'\nimport type { NodeId } from '../../../../chassis/contracts/ast/ast.type'\nimport type {\n  ReachabilityEvaluation,\n  ReachabilityNode,\n  ResumeOutcome,\n} from '../../contracts/reachabilityEvaluation.type'\nimport type {\n  ReachabilityStateInput,\n  ReachabilityEvaluationResult,\n} from '../../contracts/generatedReachabilityEvaluation.type'\n\n/**\n * The body of the compiled reachability state function. From precomputed facts\n * (the evaluated expression results) and per-step validation results, it marks\n * entry points as reachable, walks forward through the step graph, resolves the\n * default entry and canonical path, finds the frontier (the furthest reachable\n * step), derives the resume outcome, and builds the consumer-facing reachability\n * state when field inventory and params are available.\n *\n * It owns no state across calls. The lowering stage (which turns analysis models\n * into generated JavaScript) binds the static `plan` into a closure so the\n * runtime can call this with only request-time inputs.\n */\nexport function evaluateReachabilityState(\n  plan: ReachabilityStateTable,\n  input: ReachabilityStateInput,\n): ReachabilityEvaluationResult {\n  const builder = new ReachabilityGraphBuilder()\n  const steps = builder.buildReachableSteps(plan, input.routeTemplateCatalog, input.facts, input.stepValidities)\n  const defaultEntryRouteTemplatePath = builder.resolveDefaultEntryRouteTemplatePath()\n  const resumeActive = input.facts.resumeActive\n  const pathAnalysis = new ReachabilityPathAnalyzer().analyze(\n    steps,\n    input.currentStepId,\n    defaultEntryRouteTemplatePath,\n    resumeActive,\n  )\n\n  const evaluation: ReachabilityEvaluation = {\n    currentStepId: input.currentStepId,\n    steps,\n    defaultEntryRouteTemplatePath,\n    frontierRouteTemplatePath: pathAnalysis.frontierRouteTemplatePath,\n    canonicalPathRouteTemplatePaths: pathAnalysis.canonicalPathRouteTemplatePaths,\n    progressExists: pathAnalysis.progressExists,\n    resumeActive,\n    resumeOutcome: resolveResumeOutcome(\n      steps,\n      input.currentStepId,\n      resumeActive,\n      pathAnalysis.progressExists,\n      pathAnalysis.frontierRouteTemplatePath,\n    ),\n    unreachableRedirect: plan.unreachableRedirect,\n  }\n\n  if (input.fieldInventory === undefined || input.params === undefined) {\n    return { evaluation }\n  }\n\n  return {\n    evaluation,\n    reachability: new ReachabilityStateProjector().project(evaluation, input.fieldInventory, input.params),\n  }\n}\n\nfunction resolveResumeOutcome(\n  steps: ReachabilityNode[],\n  currentStepId: NodeId | undefined,\n  resumeActive: boolean,\n  progressExists: boolean,\n  frontierRouteTemplatePath: string | undefined,\n): ResumeOutcome {\n  if (!resumeActive || !progressExists || !frontierRouteTemplatePath) {\n    return 'no-op'\n  }\n\n  if (currentStepId === undefined) {\n    return 'redirect'\n  }\n\n  const currentStep = steps.find(step => step.stepId === currentStepId)\n\n  if (!currentStep) {\n    return 'no-op'\n  }\n\n  return currentStep.routeTemplatePath === frontierRouteTemplatePath ? 'no-op' : 'redirect'\n}\n","import { code, literal, objectCode } from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport { FieldCodeKind, type StaticFieldCode } from '../../../chassis/contracts/models/fieldModel.type'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport FieldCodeEmitter from '../../../chassis/compilation/lowering/emitters/FieldCodeEmitter'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport ScopedTemplateCompiler from '../../../chassis/compilation/lowering/structures/ScopedTemplateCompiler'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport type { CleardownModel, CleardownStepModel } from '../contracts/cleardownModel.type'\nimport type { CompiledFieldInventoryFunction } from '../contracts/compiledFieldInventory.type'\n\n/**\n * Compiles the possible field codes for each step in a journey's navigation plan.\n *\n * Static field codes come straight from field blocks, including dynamic code\n * expressions. Fields inside MAP iterators (repeating template sections) are\n * expanded inline using the same scoped-iteration model that answer preparation,\n * validation, and render use.\n */\nexport default class StepFieldInventoryCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  private readonly fieldCodes: FieldCodeEmitter\n\n  private readonly templates: ScopedTemplateCompiler\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n    this.fieldCodes = new FieldCodeEmitter(this.expr)\n    this.templates = new ScopedTemplateCompiler(this.expr)\n  }\n\n  /**\n   * Builds the generated inventory function that the answer-cleardown phase\n   * (which removes stale answers) and the reachability state projector both call\n   * at runtime.\n   */\n  compile(model: CleardownModel): CompiledFieldInventoryFunction {\n    return compileGeneratedFunction<CompiledFieldInventoryFunction>(this.expr, ['ctx'], () => this.buildSource(model), {\n      phase: CompilationPhase.FIELD_INVENTORY,\n      label: model.label,\n    })\n  }\n\n  /** Produces inspectable generated source for tests and local debugging. */\n  generateSource(model: CleardownModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildSource(model))\n  }\n\n  /** Emits the full field inventory source, accumulating one inventory entry per step. */\n  private buildSource(model: CleardownModel): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n\n    generator.comment('Field inventory, one entry per step')\n    const fieldInventory = generator.const('fieldInventory', code`[]`)\n\n    model.steps.forEach(step => this.compileStep(step, fieldInventory, generator))\n    generator.return(fieldInventory)\n\n    return generator\n  }\n\n  /** Emits one step's static and iterator-expanded field codes into a de-duplicated result. */\n  private compileStep(step: CleardownStepModel, fieldInventory: IdentifierName, generator: CodeGenerator): void {\n    if (this.hasOnlyStaticFieldCodes(step)) {\n      this.compileStaticStep(step, fieldInventory, generator)\n\n      return\n    }\n\n    generator.comment(\"Collect one step's possible field codes\")\n    generator.scope(() => {\n      const fieldCodes = generator.const('fieldCodes', code`[]`)\n\n      this.templates.compileFieldOccurrences(step.fields, generator, {\n        loopComment: 'Field codes produced by an iterator',\n        compileLeaf: field => {\n          const codeExpression = this.fieldCodes.compileModelExpression(field.code, generator)\n\n          if (codeExpression === undefined) {\n            return\n          }\n\n          generator.statement(code`${fieldCodes}.push(${codeExpression})`)\n        },\n      })\n\n      generator.statement(\n        code`${fieldInventory}.push(${objectCode([\n          { key: 'stepId', value: literal(step.stepId) },\n          { key: 'fieldCodes', value: code`Array.from(new Set(${fieldCodes}))` },\n          { key: 'cleardownFieldCodes', value: literal(step.cleardownFieldCodes) },\n        ])})`,\n      )\n    })\n  }\n\n  private hasOnlyStaticFieldCodes(step: CleardownStepModel): boolean {\n    return step.fields.every(\n      field =>\n        field.iteratorPath.length === 0 && (field.code === undefined || field.code.kind === FieldCodeKind.STATIC),\n    )\n  }\n\n  /** Emits a step whose field codes are all compile-time constants as one literal entry, deduplicated here. */\n  private compileStaticStep(step: CleardownStepModel, fieldInventory: IdentifierName, generator: CodeGenerator): void {\n    const staticFieldCodes = step.fields\n      .map(field => field.code)\n      .filter((fieldCode): fieldCode is StaticFieldCode => fieldCode?.kind === FieldCodeKind.STATIC)\n      .map(fieldCode => fieldCode.value)\n\n    generator.statement(\n      code`${fieldInventory}.push(${objectCode([\n        { key: 'stepId', value: literal(step.stepId) },\n        { key: 'fieldCodes', value: literal([...new Set(staticFieldCodes)]) },\n        { key: 'cleardownFieldCodes', value: literal(step.cleardownFieldCodes) },\n      ])})`,\n    )\n  }\n}\n","import { BlockType } from '../../../../authoring/types/enums'\nimport { isTemplateNode } from '../../../chassis/contracts/ast/nodes'\nimport type { TemplateNode } from '../../../chassis/contracts/ast/template.type'\nimport {\n  AuthoredValueKind,\n  toRawOperand,\n  type AuthoredValue,\n  type BlockValue,\n  type RecordEntryValue,\n} from '../../../chassis/contracts/models/authoredValue.type'\nimport {\n  CodeFragment,\n  code,\n  literal,\n  objectCode,\n  structuredLiteralCode,\n  SafeCode,\n  ObjectCodeProperty,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport FieldCodeEmitter from '../../../chassis/compilation/lowering/emitters/FieldCodeEmitter'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport RuntimeValueCompiler from '../../../chassis/compilation/lowering/structures/RuntimeValueCompiler'\nimport ScopedTemplateCompiler from '../../../chassis/compilation/lowering/structures/ScopedTemplateCompiler'\nimport type { CompiledResolveFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport type {\n  ResolveAncestorModel,\n  ResolveBlockModel,\n  ResolveModel,\n  ResolvePropertyModel,\n} from '../contracts/resolveModel.type'\n\ninterface ResolveResultNames {\n  readonly blocks: IdentifierName\n  readonly step: IdentifierName\n  readonly ancestors: IdentifierName\n}\n\n/** Everything one block-props construction needs, shared by top-level, template, and nested blocks. */\ninterface BlockPropsCompilation {\n  readonly properties: readonly ResolvePropertyModel[]\n  readonly blockType: string\n  readonly variant: string\n  readonly resolvesFieldValue: boolean\n  readonly blockId: SafeCode\n  readonly codeExpression: SafeCode | undefined\n  readonly namePrefix: string\n}\n\nconst CONTEXT = new IdentifierName('ctx')\nconst HELPERS = new IdentifierName(GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM)\n\n/** Compiler for the resolve phase: builds the generated function that prepares a step's blocks, metadata, and ancestors for rendering. */\nexport default class StepResolveCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  private readonly fieldCodes: FieldCodeEmitter\n\n  private readonly templates: ScopedTemplateCompiler\n\n  private readonly values: RuntimeValueCompiler\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n    this.fieldCodes = new FieldCodeEmitter(this.expr)\n    this.templates = new ScopedTemplateCompiler(this.expr)\n    this.values = new RuntimeValueCompiler(this.expr, {\n      expressionErrorFallback: literal(undefined),\n      expressionErrorMode: 'throw',\n      omitUndefinedArrayItems: true,\n      compileBlockValue: (block, generator, nameHint) => this.compileNestedBlockValue(block, generator, nameHint),\n    })\n  }\n\n  compile(model: ResolveModel): CompiledResolveFunction {\n    return compileGeneratedFunction<CompiledResolveFunction>(this.expr, ['ctx'], () => this.buildSource(model), {\n      phase: CompilationPhase.RESOLVE,\n      label: model.label,\n    })\n  }\n\n  generateSource(model: ResolveModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildSource(model))\n  }\n\n  private buildSource(model: ResolveModel): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n    const names: ResolveResultNames = {\n      blocks: generator.const('blocks', code`[]`),\n      step: generator.const('step', this.staticPropertiesLiteral(model.step)),\n      ancestors: generator.const('ancestors', code`[]`),\n    }\n\n    this.compileDynamicProperties(model.step, names.step, generator)\n    this.compileAncestorMetadata(model.ancestors, names.ancestors, generator)\n    this.compileBlocks(model.blocks, names.blocks, generator)\n    this.compileIterateBlocks(model, names.blocks, generator)\n    generator.return(this.compileResolveBlocksWorkTaskExpression(names))\n\n    return generator\n  }\n\n  private staticPropertiesLiteral(properties: readonly ResolvePropertyModel[]): CodeFragment {\n    return objectCode(this.staticPropertyEntries(properties))\n  }\n\n  private staticPropertyEntries(properties: readonly ResolvePropertyModel[]): ObjectCodeProperty[] {\n    return properties.flatMap(property =>\n      property.value.kind === AuthoredValueKind.STATIC\n        ? [{ key: property.key, value: structuredLiteralCode(property.value.value) }]\n        : [],\n    )\n  }\n\n  private compileDynamicProperties(\n    properties: readonly ResolvePropertyModel[],\n    target: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    properties\n      .filter(property => property.value.kind !== AuthoredValueKind.STATIC)\n      .forEach(property => this.compilePropertyAssignment(property.value, target, property.key, generator))\n  }\n\n  private compileAncestorMetadata(\n    ancestors: readonly ResolveAncestorModel[],\n    ancestorsName: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    if (ancestors.length === 0) {\n      return\n    }\n\n    generator.comment('Ancestor journeys')\n\n    // When every ancestor path is a plain string the full path was built at\n    // compile time (during analysis); otherwise the generated code rebuilds\n    // the whole chain per request.\n    if (ancestors.every(ancestor => ancestor.composedPath !== undefined)) {\n      ancestors.forEach(ancestorModel => {\n        this.compileComposedAncestor(ancestorModel, ancestorsName, generator)\n      })\n\n      return\n    }\n\n    const composedPath = generator.let('composedPath', literal(''))\n\n    ancestors.forEach(ancestorModel => {\n      const ancestor = generator.const('ancestor', this.staticPropertiesLiteral(ancestorModel.properties))\n\n      this.compileDynamicProperties(ancestorModel.properties, ancestor, generator)\n      generator.assign(\n        composedPath,\n        code`\"/\" + (${composedPath} + \"/\" + ${ancestor}.path).split(\"/\").filter(Boolean).join(\"/\")`,\n      )\n      generator.assign(code`${ancestor}.path`, composedPath)\n      generator.statement(code`${ancestorsName}.push(${ancestor})`)\n      generator.blank()\n    })\n  }\n\n  /**\n   * Pushes one ancestor whose full path was composed at analysis: the\n   * authored relative path never appears — the composed path takes its place\n   * in the literal.\n   */\n  private compileComposedAncestor(\n    ancestorModel: ResolveAncestorModel,\n    ancestorsName: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const staticEntries = this.staticPropertyEntries(ancestorModel.properties).map(entry =>\n      entry.key === 'path' ? { key: 'path', value: literal(ancestorModel.composedPath) } : entry,\n    )\n    const entries = staticEntries.some(entry => entry.key === 'path')\n      ? staticEntries\n      : [...staticEntries, { key: 'path', value: literal(ancestorModel.composedPath) }]\n    const dynamicProperties = ancestorModel.properties.filter(\n      property => property.value.kind !== AuthoredValueKind.STATIC,\n    )\n\n    if (dynamicProperties.length === 0) {\n      generator.statement(code`${ancestorsName}.push(${objectCode(entries)})`)\n\n      return\n    }\n\n    const ancestor = generator.const('ancestor', objectCode(entries))\n\n    dynamicProperties.forEach(property =>\n      this.compilePropertyAssignment(property.value, ancestor, property.key, generator),\n    )\n    generator.statement(code`${ancestorsName}.push(${ancestor})`)\n  }\n\n  private compileBlocks(\n    blocks: readonly ResolveBlockModel[],\n    targetBlocks: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    blocks.forEach(block => {\n      this.compileBlock(block, targetBlocks, generator)\n      generator.blank()\n    })\n  }\n\n  private compileBlock(block: ResolveBlockModel, targetBlocks: IdentifierName, generator: CodeGenerator): void {\n    const blockId = literal(block.id)\n    const props = this.compileBlockProperties(\n      this.toBlockPropsCompilation(block, blockId, undefined, this.toBlockPropsName(block.variant)),\n      generator,\n      `Block — ${block.variant} (${block.label})`,\n    )\n\n    this.pushResolveBlockWorkTask(targetBlocks, blockId, block.variant, block.blockType, props, generator)\n  }\n\n  private compileIterateBlocks(model: ResolveModel, blocks: IdentifierName, generator: CodeGenerator): void {\n    model.standaloneIterateBlocks.forEach(iterateModel => {\n      generator.comment('Iterator blocks')\n      this.templates.compileMapIterator(iterateModel.node, generator, () => {\n        iterateModel.templateBlocks.forEach(templateBlock => {\n          const codeExpression = this.templates.compileTemplateCodeExpression(\n            templateBlock.source as TemplateNode,\n            generator,\n          )\n\n          this.compileTemplateBlock(templateBlock, codeExpression, blocks, generator)\n        })\n      })\n      generator.blank()\n    })\n  }\n\n  private compileTemplateBlock(\n    block: ResolveBlockModel,\n    codeExpression: SafeCode | undefined,\n    blocks: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const blockId = generator.const(\n      'resolveBlockId',\n      this.templates.compileTemplateInstanceIdExpression(block.source as TemplateNode),\n    )\n    const props = this.compileBlockProperties(\n      this.toBlockPropsCompilation(block, blockId, codeExpression, this.toBlockPropsName(block.variant)),\n      generator,\n      `Template block — ${block.variant} (${block.label})`,\n    )\n\n    this.pushResolveBlockWorkTask(blocks, blockId, block.variant, block.blockType, props, generator)\n  }\n\n  private toBlockPropsCompilation(\n    block: ResolveBlockModel,\n    blockId: SafeCode,\n    codeExpression: SafeCode | undefined,\n    namePrefix: string,\n  ): BlockPropsCompilation {\n    return {\n      properties: block.properties,\n      blockType: block.blockType,\n      variant: block.variant,\n      resolvesFieldValue: block.resolvesFieldValue,\n      blockId,\n      codeExpression,\n      namePrefix,\n    }\n  }\n\n  private compileBlockProperties(\n    plan: BlockPropsCompilation,\n    generator: CodeGenerator,\n    comment: string,\n  ): IdentifierName {\n    const visibleWhen = plan.properties.find(property => property.key === 'visibleWhen')\n\n    if (visibleWhen === undefined) {\n      return this.compileUngatedBlockProps(plan, generator, comment)\n    }\n\n    generator.comment(comment)\n\n    return this.compileVisibilityGatedBlockProps(plan, visibleWhen, generator)\n  }\n\n  /**\n   * The common shape: one props literal per block with every expressible\n   * property inline. Values that need statements — nested blocks especially —\n   * hoist into their own named units above the literal, so the block's\n   * comment sits directly on its props const, after any hoisted children.\n   */\n  private compileUngatedBlockProps(\n    plan: BlockPropsCompilation,\n    generator: CodeGenerator,\n    comment: string,\n  ): IdentifierName {\n    const boundPlan = this.toSelfBoundPlan(plan, generator)\n\n    return this.expr.withSelfCodeExpression(boundPlan.codeExpression, () => {\n      const entries = this.compileBlockPropEntries(boundPlan, generator)\n\n      generator.comment(comment)\n      const props = generator.const(boundPlan.namePrefix, objectCode(entries))\n\n      this.compileFieldResolution(boundPlan, props, generator)\n\n      return props\n    })\n  }\n\n  /**\n   * Resolves a FIELD block's code expression ahead of property compilation so\n   * `Self()` references in the block's properties can bind to it. Hoisted once\n   * outside the `withSelfCodeExpression` scope, so the code expression itself\n   * never self-resolves.\n   */\n  private toSelfBoundPlan(plan: BlockPropsCompilation, generator: CodeGenerator): BlockPropsCompilation {\n    if (plan.blockType !== BlockType.FIELD || plan.codeExpression !== undefined) {\n      return plan\n    }\n\n    const codeProperty = plan.properties.find(property => property.key === 'code')\n\n    if (codeProperty === undefined) {\n      return plan\n    }\n\n    return {\n      ...plan,\n      codeExpression: this.fieldCodes.compileRegisteredExpression(toRawOperand(codeProperty.value), generator),\n    }\n  }\n\n  private compileBlockPropEntries(plan: BlockPropsCompilation, generator: CodeGenerator): ObjectCodeProperty[] {\n    return plan.properties.flatMap(property => {\n      if (plan.blockType === BlockType.FIELD && property.key === 'code') {\n        const codeExpression =\n          plan.codeExpression ?? this.fieldCodes.compileRegisteredInlineExpression(toRawOperand(property.value))\n\n        return codeExpression === undefined ? [] : [{ key: 'code', value: codeExpression }]\n      }\n\n      return [{ key: property.key, value: this.values.compileValueExpression(property.value, generator, property.key) }]\n    })\n  }\n\n  /**\n   * A `visibleWhen` block evaluates its predicate first and only materialises\n   * the remaining properties when the block is visible, so those assignments\n   * stay statement-per-property inside the gate.\n   */\n  private compileVisibilityGatedBlockProps(\n    plan: BlockPropsCompilation,\n    visibleWhen: ResolvePropertyModel,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    const boundPlan = this.toSelfBoundPlan(plan, generator)\n\n    return this.expr.withSelfCodeExpression(boundPlan.codeExpression, () => {\n      const props = generator.const(boundPlan.namePrefix, code`{}`)\n      const hoistedKeys = new Set<string>(['visibleWhen'])\n      const codeProperty = boundPlan.properties.find(property => property.key === 'code')\n\n      this.compilePropertyAssignment(visibleWhen.value, props, 'visibleWhen', generator)\n\n      if (boundPlan.blockType === BlockType.FIELD && codeProperty !== undefined) {\n        this.fieldCodes.assignProperty(\n          toRawOperand(codeProperty.value),\n          generator,\n          props,\n          'code',\n          boundPlan.codeExpression,\n        )\n        hoistedKeys.add('code')\n      }\n\n      generator.if(code`${props}.visibleWhen !== false`, () => {\n        boundPlan.properties\n          .filter(property => !hoistedKeys.has(property.key))\n          .forEach(property => this.compileBlockPropAssignment(property, boundPlan, props, generator))\n        this.compileFieldResolution(boundPlan, props, generator)\n      })\n\n      return props\n    })\n  }\n\n  private compileBlockPropAssignment(\n    property: ResolvePropertyModel,\n    plan: BlockPropsCompilation,\n    props: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    if (plan.blockType === BlockType.FIELD && property.key === 'code') {\n      this.fieldCodes.assignProperty(toRawOperand(property.value), generator, props, property.key, plan.codeExpression)\n\n      return\n    }\n\n    this.compilePropertyAssignment(property.value, props, property.key, generator)\n  }\n\n  private compileFieldResolution(plan: BlockPropsCompilation, props: IdentifierName, generator: CodeGenerator): void {\n    if (plan.blockType !== BlockType.FIELD) {\n      return\n    }\n\n    if (plan.resolvesFieldValue) {\n      generator.statement(code`${HELPERS}.resolveFieldValue(${CONTEXT}, ${props})`)\n    }\n\n    generator.statement(\n      code`${HELPERS}.resolveFieldFailures(${CONTEXT}, ${plan.blockId}, ${literal(plan.variant)}, ${props})`,\n    )\n  }\n\n  private compilePropertyAssignment(\n    value: AuthoredValue,\n    targetObject: IdentifierName,\n    key: string,\n    generator: CodeGenerator,\n  ): void {\n    this.values.compileAssignment(value, generator, targetObject, key)\n  }\n\n  /**\n   * Emits a nested block as its own named unit — comment, props const,\n   * resolve const — and returns the const so the parent literal references\n   * it by name. Children therefore always appear above their parent.\n   */\n  private compileNestedBlockValue(block: BlockValue, generator: CodeGenerator, nameHint: string): SafeCode {\n    if (isTemplateNode(block.source)) {\n      return this.compileTemplateNestedBlock(block, block.source, nameHint, generator)\n    }\n\n    return this.compileNestedBlock(block, nameHint, generator)\n  }\n\n  private compileNestedBlock(block: BlockValue, nameHint: string, generator: CodeGenerator): IdentifierName {\n    const blockName = this.toNestedBlockName(block, nameHint)\n    const blockId = literal(block.id)\n    const props = this.compileUngatedBlockProps(\n      this.toNestedBlockPropsCompilation(block, blockId, `${blockName}Props`),\n      generator,\n      this.toNestedBlockComment(block, nameHint),\n    )\n    const result = generator.const(\n      blockName,\n      this.compileResolveBlockWorkTaskExpression(blockId, block.variant, block.blockType, props),\n    )\n\n    generator.blank()\n\n    return result\n  }\n\n  private compileTemplateNestedBlock(\n    block: BlockValue,\n    source: TemplateNode,\n    nameHint: string,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    const blockName = this.toNestedBlockName(block, nameHint)\n    const blockId = generator.const('resolveBlockId', this.templates.compileTemplateInstanceIdExpression(source))\n    const props = this.compileUngatedBlockProps(\n      this.toNestedBlockPropsCompilation(block, blockId, `${blockName}Props`),\n      generator,\n      this.toNestedBlockComment(block, nameHint),\n    )\n    const result = generator.const(\n      blockName,\n      this.compileResolveBlockWorkTaskExpression(blockId, block.variant, block.blockType, props),\n    )\n\n    generator.blank()\n\n    return result\n  }\n\n  private toNestedBlockPropsCompilation(\n    block: BlockValue,\n    blockId: SafeCode,\n    namePrefix: string,\n  ): BlockPropsCompilation {\n    return {\n      properties: block.entries,\n      blockType: block.blockType,\n      variant: block.variant,\n      resolvesFieldValue: this.nestedBlockResolvesFieldValue(block.entries),\n      blockId,\n      codeExpression: undefined,\n      namePrefix,\n    }\n  }\n\n  /** Returns true when the block has no explicit `value` property, matching the authored block's own `properties.value === undefined` check. */\n  private nestedBlockResolvesFieldValue(entries: readonly RecordEntryValue[]): boolean {\n    const valueEntry = entries.find(entry => entry.key === 'value')\n\n    return valueEntry === undefined ||\n      (valueEntry.value.kind === AuthoredValueKind.STATIC && valueEntry.value.value === undefined)\n  }\n\n  private pushResolveBlockWorkTask(\n    targetBlocks: IdentifierName,\n    blockId: SafeCode,\n    variant: string,\n    blockType: string,\n    props: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    generator.statement(\n      code`${targetBlocks}.push(${this.compileResolveBlockWorkTaskExpression(blockId, variant, blockType, props)})`,\n    )\n  }\n\n  private compileResolveBlockWorkTaskExpression(\n    blockId: SafeCode,\n    variant: string,\n    blockType: string,\n    props: IdentifierName,\n  ): CodeFragment {\n    return code`${CONTEXT}.workTasks.resolveBlock(${blockId}, ${variant}, ${blockType}, ${props})`\n  }\n\n  private compileResolveBlocksWorkTaskExpression(names: ResolveResultNames): CodeFragment {\n    return code`${CONTEXT}.workTasks.resolveBlocks(${names.blocks}, ${names.step}, ${names.ancestors})`\n  }\n\n  private toBlockPropsName(variant: string): string {\n    return `${this.toVariantName(variant)}Props`\n  }\n\n  private toVariantName(variant: string): string {\n    return this.camelise(variant.replace(/^(govuk|moj)-?/i, ''))\n  }\n\n  /**\n   * Names a nested block unit: the authored field code when it is a static\n   * string, otherwise the slot or property the block lives under plus the\n   * last word of the variant (`basic-example` + `templateWrapper` becomes\n   * `basicExampleWrapper`).\n   */\n  private toNestedBlockName(block: BlockValue, nameHint: string): string {\n    const staticCode = this.staticFieldCode(block)\n\n    if (staticCode !== undefined) {\n      const name = this.camelise(staticCode)\n\n      if (name.length > 0) {\n        return `nestedBlock${name.charAt(0).toUpperCase()}${name.slice(1)}`\n      }\n    }\n\n    const base = this.camelise(nameHint)\n\n    if (base.length === 0) {\n      return this.toVariantName(block.variant)\n    }\n\n    const tail = this.variantTail(block.variant)\n\n    return base.toLowerCase().endsWith(tail.toLowerCase()) ? base : `${base}${tail}`\n  }\n\n  private toNestedBlockComment(block: BlockValue, nameHint: string): string {\n    const staticCode = this.staticFieldCode(block)\n\n    if (staticCode !== undefined) {\n      return `Block — ${block.variant} \"${staticCode}\"`\n    }\n\n    return nameHint.length > 0 ? `Block — ${block.variant} (${nameHint})` : `Block — ${block.variant}`\n  }\n\n  private staticFieldCode(block: BlockValue): string | undefined {\n    const codeEntry = block.entries.find(entry => entry.key === 'code')\n\n    if (\n      codeEntry !== undefined &&\n      codeEntry.value.kind === AuthoredValueKind.STATIC &&\n      typeof codeEntry.value.value === 'string'\n    ) {\n      return codeEntry.value.value\n    }\n\n    return undefined\n  }\n\n  private variantTail(variant: string): string {\n    const words = variant.match(/[A-Z]?[a-z0-9]+|[A-Z]+/g) ?? [variant]\n    const lastWord = words[words.length - 1]\n\n    return `${lastWord.charAt(0).toUpperCase()}${lastWord.slice(1)}`\n  }\n\n  private camelise(value: string): string {\n    const words = value.match(/[A-Za-z0-9]+/g) ?? []\n\n    if (words.length === 0) {\n      return ''\n    }\n\n    const firstWord = words[0] ?? ''\n    const restWords = words.slice(1)\n    const name = `${firstWord.charAt(0).toLowerCase()}${firstWord.slice(1)}${restWords\n      .map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)\n      .join('')}`\n\n    return /^[A-Za-z_$]/.test(name) ? name : `block${name.charAt(0).toUpperCase()}${name.slice(1)}`\n  }\n}\n","import {\n  callCode,\n  CodeFragment,\n  code,\n  literal,\n  objectCode,\n  ObjectCodeProperty,\n  SafeCode,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport FieldCodeEmitter from '../../../chassis/compilation/lowering/emitters/FieldCodeEmitter'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport RuntimeValueCompiler from '../../../chassis/compilation/lowering/structures/RuntimeValueCompiler'\nimport ScopedTemplateCompiler from '../../../chassis/compilation/lowering/structures/ScopedTemplateCompiler'\nimport { toRawOperand, type AuthoredValue } from '../../../chassis/contracts/models/authoredValue.type'\nimport type { FieldModel, TransformerPipeline } from '../../../chassis/contracts/models/fieldModel.type'\nimport type { AnswerPreparationModel } from '../contracts/answerPreparationModel.type'\nimport type { CompiledAnswerPreparationFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\n\nconst CONTEXT = new IdentifierName('ctx')\nconst HELPERS = new IdentifierName(GENERATED_FUNCTION_RUNTIME_LIBRARY_PARAM)\n\n/** Compiles GET/POST answer preparation for one generated step function. */\nexport default class StepAnswerPreparationCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  private readonly fieldCodes: FieldCodeEmitter\n\n  private readonly values: RuntimeValueCompiler\n\n  private readonly templates: ScopedTemplateCompiler\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n    this.fieldCodes = new FieldCodeEmitter(this.expr)\n    this.values = new RuntimeValueCompiler(this.expr, {\n      expressionErrorFallback: literal(undefined),\n      expressionErrorMode: 'throw',\n      omitUndefinedArrayItems: false,\n    })\n    this.templates = new ScopedTemplateCompiler(this.expr)\n  }\n\n  compile(model: AnswerPreparationModel): CompiledAnswerPreparationFunction {\n    return compileGeneratedFunction<CompiledAnswerPreparationFunction>(\n      this.expr,\n      ['ctx'],\n      () => this.buildSource(model),\n      { phase: CompilationPhase.ANSWER_PREPARATION, label: model.label },\n    )\n  }\n\n  generateSource(model: AnswerPreparationModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildSource(model))\n  }\n\n  private buildSource(model: AnswerPreparationModel): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n\n    if (model.fields.length === 0) {\n      generator.note('This step declares no form fields, so there is nothing to prepare.')\n      const fieldPreparations = generator.const('fieldPreparations', code`[]`)\n\n      generator.return(code`${CONTEXT}.workTasks.answerPreparation(${fieldPreparations})`)\n\n      return generator\n    }\n\n    const mode = generator.const('answerPreparationMode', code`${CONTEXT}.request.method === \"POST\" ? \"POST\" : \"GET\"`)\n    const fieldDefinitions = generator.const('fieldDefinitions', code`[]`)\n\n    this.compileFieldDefinitions(model.fields, fieldDefinitions, generator)\n    const prepareFieldAnswer = this.compileFieldPreparationSelector(mode, generator)\n    const fieldPreparations = this.compileFieldPreparationTasks(fieldDefinitions, mode, prepareFieldAnswer, generator)\n\n    generator.return(code`${CONTEXT}.workTasks.answerPreparation(${fieldPreparations})`)\n\n    return generator\n  }\n\n  private compileFieldDefinitions(\n    fields: readonly FieldModel[],\n    fieldDefinitions: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    generator.comment('Field definitions')\n\n    this.templates.compileFieldOccurrences(fields, generator, {\n      loopComment: 'Fields produced by an iterator',\n      compileLeaf: field => {\n        this.compileFieldDefinitionEntry(field, fieldDefinitions, generator)\n      },\n    })\n  }\n\n  private compileFieldDefinitionEntry(\n    field: FieldModel,\n    fieldDefinitions: IdentifierName,\n    generator: CodeGenerator,\n  ): void {\n    const isRegistered = field.iteratorPath.length === 0\n\n    generator.comment(isRegistered ? `Field — ${field.label}` : `Template field — ${field.label}`)\n    const codeExpression = this.fieldCodes.compileModelExpression(field.code, generator)\n\n    // A registered field without a resolvable code cannot store an answer;\n    // template fields keep their entry so iterator counts stay aligned.\n    if (isRegistered && codeExpression === undefined) {\n      return\n    }\n\n    // Bind @self for the field's formatters, parsers, dependentWhen, and\n    // defaultValue; the code expression itself compiles above, unbound.\n    this.expr.withSelfCodeExpression(codeExpression, () => {\n      generator.statement(\n        callCode(code`${fieldDefinitions}.push`, [\n          this.compileFieldDefinition(field, codeExpression ?? literal(undefined), generator),\n        ]),\n      )\n    })\n  }\n\n  private compileFieldDefinition(field: FieldModel, codeExpression: SafeCode, generator: CodeGenerator): CodeFragment {\n    const definitionProperties: ObjectCodeProperty[] = [\n      { key: 'code', value: codeExpression },\n      { key: 'component', value: literal(field.component.variant) },\n      { key: 'acceptsMultipleValues', value: literal(field.component.acceptsMultipleValues) },\n      { key: 'validatesInput', value: literal(field.component.validatesInput) },\n    ]\n\n    this.addOptionalDefinitionProperty(\n      definitionProperties,\n      'formatSubmittedValue',\n      this.compileTransformerCallback('formatSubmittedValue', field.formatters, generator),\n    )\n    this.addOptionalDefinitionProperty(\n      definitionProperties,\n      'evaluateDependentWhen',\n      this.compileDependentWhenCallback(field.dependentWhen, generator),\n    )\n    this.addOptionalDefinitionProperty(\n      definitionProperties,\n      'resolveDefaultValue',\n      this.compileDefaultValueCallback(field.defaultValue, generator),\n    )\n    this.addOptionalDefinitionProperty(\n      definitionProperties,\n      'parseStoredValue',\n      this.compileTransformerCallback('parseStoredValue', field.parsers, generator),\n    )\n\n    return objectCode(definitionProperties)\n  }\n\n  private addOptionalDefinitionProperty(\n    properties: ObjectCodeProperty[],\n    key: string,\n    value: CodeFragment | undefined,\n  ): void {\n    if (value === undefined) {\n      return\n    }\n\n    properties.push({ key, value })\n  }\n\n  private compileTransformerCallback(\n    functionName: string,\n    transformers: TransformerPipeline | undefined,\n    generator: CodeGenerator,\n  ): CodeFragment | undefined {\n    if (transformers === undefined) {\n      return undefined\n    }\n\n    let bodyUsesAwait = false\n\n    return generator.functionExpression(\n      functionName,\n      ['value'],\n      (body, [value]) => {\n        bodyUsesAwait = this.expr.trackNestedFunctionAwait(() => {\n          this.expr.withGeneratorScope(body, () => {\n            const transformedValue = body.let('transformedValue', value)\n\n            body.tryCatch(\n              () => {\n                transformers.forEach(transformer => {\n                  const transformerResult = body.const(\n                    'transformerResult',\n                    this.compileTransformerCall(transformer, transformedValue, body),\n                  )\n\n                  body.if(code`${transformerResult} !== undefined`, () => {\n                    body.assign(transformedValue, transformerResult)\n                  })\n                })\n              },\n              'error',\n              error => {\n                body.if(code`${HELPERS}.isTransformerTypeError(${error})`, () => {\n                  body.return(value)\n                })\n                body.throw(error)\n              },\n            )\n            body.return(transformedValue)\n          })\n        })\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  private compileDependentWhenCallback(\n    dependentWhen: AuthoredValue | undefined,\n    generator: CodeGenerator,\n  ): CodeFragment | undefined {\n    if (dependentWhen === undefined) {\n      return undefined\n    }\n\n    return this.compileFunctionExpression('evaluateDependentWhen', generator, body => {\n      const dependentWhenResult = body.let('dependentWhenResult')\n\n      this.values.compileValue(dependentWhen, body, dependentWhenResult, {\n        expressionErrorFallback: literal(true),\n      })\n      body.return(dependentWhenResult)\n    })\n  }\n\n  private compileDefaultValueCallback(\n    defaultValue: AuthoredValue | undefined,\n    generator: CodeGenerator,\n  ): CodeFragment | undefined {\n    if (defaultValue === undefined) {\n      return undefined\n    }\n\n    return this.compileFunctionExpression('resolveDefaultValue', generator, body => {\n      const resolvedDefaultValue = body.let('defaultValue')\n\n      this.values.compileValue(defaultValue, body, resolvedDefaultValue)\n      body.return(resolvedDefaultValue)\n    })\n  }\n\n  private compileFunctionExpression(\n    prefix: string,\n    generator: CodeGenerator,\n    buildBody: (generator: CodeGenerator) => void,\n  ): CodeFragment {\n    let bodyUsesAwait = false\n\n    return generator.functionExpression(\n      prefix,\n      [],\n      body => {\n        bodyUsesAwait = this.expr.trackNestedFunctionAwait(() =>\n          this.expr.withGeneratorScope(body, () => buildBody(body)),\n        )\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  private compileFieldPreparationSelector(mode: IdentifierName, generator: CodeGenerator): IdentifierName {\n    generator.comment('Select preparation using the request method')\n\n    return generator.const(\n      'prepareFieldAnswer',\n      code`${mode} === \"POST\" ? ${HELPERS}.preparePostedFieldAnswerGroup : ${HELPERS}.prepareStoredFieldAnswerGroup`,\n    )\n  }\n\n  private compileFieldPreparationTasks(\n    fieldDefinitions: IdentifierName,\n    mode: IdentifierName,\n    prepareFieldAnswer: IdentifierName,\n    generator: CodeGenerator,\n  ): IdentifierName {\n    generator.comment('Create one preparation task per field; same-code fields form one variant group')\n    const createFieldPreparation = generator.functionExpression(\n      'createFieldPreparation',\n      ['fieldGroup'],\n      (body, [fieldGroup]) => {\n        const fieldCode = body.const('fieldCode', code`${fieldGroup}[0].code`)\n        const run = body.functionExpression('runFieldPreparation', [], runBody => {\n          runBody.return(callCode(prepareFieldAnswer, [CONTEXT, fieldGroup]))\n        })\n        const props = body.const(\n          'fieldAnswerPreparationProps',\n          objectCode([\n            { key: 'code', value: fieldCode },\n            { key: 'mode', value: mode },\n            { key: 'run', value: run },\n          ]),\n        )\n\n        body.return(\n          callCode(code`${CONTEXT}.workTasks.fieldAnswerPreparation`, [code`\"field:\" + String(${fieldCode})`, props]),\n        )\n      },\n    )\n    const fieldGroups = generator.const(\n      'fieldGroups',\n      callCode(code`${HELPERS}.groupFieldDefinitionsByCode`, [code`${fieldDefinitions}`]),\n    )\n\n    return generator.const('fieldPreparations', callCode(code`${fieldGroups}.map`, [createFieldPreparation]))\n  }\n\n  private compileTransformerCall(\n    transformer: TransformerPipeline[number],\n    value: IdentifierName,\n    generator: CodeGenerator,\n  ): CodeFragment {\n    const argumentsCode = transformer.arguments.map(argument =>\n      this.expr.compileOperandCode(toRawOperand(argument), generator),\n    )\n\n    return this.expr.compileFunctionCallCode(\n      transformer.name,\n      [code`${value}`, ...argumentsCode],\n      transformer.node.node,\n    )\n  }\n\n}\n","import {\n  CodeFragment,\n  ObjectCodeProperty,\n  arrayCode,\n  code,\n  literal,\n  objectCode,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport { toRawOperand, type ExpressionValue } from '../../../chassis/contracts/models/authoredValue.type'\nimport type { CompiledAccessLifecycleFunction, CompiledSubmitHooksFunction } from '../contracts/hookLifecycle.type'\nimport type {\n  AccessHookModel,\n  AccessLifecycleModel,\n  EffectCall,\n  HookOutcomeModel,\n  RedirectOutcomeModel,\n  SubmitBranchModel,\n  SubmitHookModel,\n  SubmitHooksModel,\n  ThrowErrorOutcomeModel,\n} from '../contracts/hookModel.type'\nimport { HookOutcomeKind } from '../contracts/hookModel.type'\n\nconst CONTEXT = new IdentifierName('ctx')\n\n/** Compiles the access-lifecycle and submit-hook functions from the hook models. */\nexport default class HookLifecycleCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n  }\n\n  compileAccessLifecycle(model: AccessLifecycleModel): CompiledAccessLifecycleFunction {\n    return compileGeneratedFunction<CompiledAccessLifecycleFunction>(\n      this.expr,\n      ['ctx'],\n      () => this.buildAccessSource(model),\n      { phase: CompilationPhase.HOOKS, label: model.label },\n    )\n  }\n\n  compileSubmitHooks(model: SubmitHooksModel): CompiledSubmitHooksFunction {\n    return compileGeneratedFunction<CompiledSubmitHooksFunction>(\n      this.expr,\n      ['ctx'],\n      () => this.buildSubmitSource(model),\n      { phase: CompilationPhase.HOOKS, label: model.label },\n    )\n  }\n\n  generateAccessSource(model: AccessLifecycleModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildAccessSource(model))\n  }\n\n  generateSubmitSource(model: SubmitHooksModel): string {\n    return renderGeneratedSource(this.expr, () => this.buildSubmitSource(model))\n  }\n\n  private buildAccessSource(model: AccessLifecycleModel): CodeGenerator {\n    const generator = this.createGenerator()\n    const hookNames = model.hooks.map(hook => this.compileAccessHookTask(hook, generator))\n\n    generator.return(code`${CONTEXT}.workTasks.accessLifecycle(${arrayCode(hookNames)})`)\n\n    return generator\n  }\n\n  private buildSubmitSource(model: SubmitHooksModel): CodeGenerator {\n    const generator = this.createGenerator()\n    const hookNames = model.hooks.map(hook => this.compileSubmitHookTask(hook, generator))\n\n    generator.return(code`${CONTEXT}.workTasks.submitLifecycle(${arrayCode(hookNames)})`)\n\n    return generator\n  }\n\n  private createGenerator(): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n\n    generator.directive('use strict')\n\n    return generator\n  }\n\n  /**\n   * Emits one access hook as a named unit: effect consts first, then the hook\n   * const holding the work task. Only authored parts appear in the props —\n   * an absent `when`, empty effects, or no outcomes are simply not emitted.\n   */\n  private compileAccessHookTask(hook: AccessHookModel, generator: CodeGenerator): IdentifierName {\n    generator.comment(`Access hook — ${hook.label}`)\n    const effectNames = hook.effects.map(effect => this.compileEffectTask(effect, generator))\n    const entries: ObjectCodeProperty[] = []\n\n    if (hook.when !== undefined) {\n      entries.push({ key: 'when', value: this.compileAccessWhenTask(hook.when, `${hook.key}-when`, generator) })\n    }\n\n    if (effectNames.length > 0) {\n      entries.push({ key: 'effects', value: arrayCode(effectNames) })\n    }\n\n    if (hook.outcomes.length > 0) {\n      entries.push({ key: 'next', value: this.compileNextFunction('resolveAccessHookNext', hook.outcomes, generator) })\n    }\n\n    const hookName = generator.const(\n      this.camelise(hook.key),\n      code`${CONTEXT}.workTasks.accessHook(${hook.key}, ${objectCode(entries)})`,\n    )\n\n    generator.blank()\n\n    return hookName\n  }\n\n  /**\n   * Emits one submit hook as a named unit. Branch effects hoist into named\n   * consts above the hook const; unauthored predicates and empty branches are\n   * not emitted, matching the optional work-task props.\n   */\n  private compileSubmitHookTask(hook: SubmitHookModel, generator: CodeGenerator): IdentifierName {\n    generator.comment(`Submit hook — ${hook.label}`)\n    const entries: ObjectCodeProperty[] = []\n\n    if (hook.when !== undefined) {\n      entries.push({\n        key: 'when',\n        value: this.compileSubmitPredicateTask(hook.when, `${hook.key}-when`, 'when', generator),\n      })\n    }\n\n    if (hook.guards !== undefined) {\n      entries.push({\n        key: 'guards',\n        value: this.compileSubmitPredicateTask(hook.guards, `${hook.key}-guards`, 'guards', generator),\n      })\n    }\n\n    this.appendSubmitBranchEntry(entries, hook.branches.onAlways, `${hook.key}-onAlways`, 'onAlways', generator)\n\n    if (hook.validate) {\n      entries.push({\n        key: 'validation',\n        value: this.compileCurrentStepValidationTask(`${hook.key}-validation`, hook.validationGroups),\n      })\n    }\n\n    this.appendSubmitBranchEntry(entries, hook.branches.onValid, `${hook.key}-onValid`, 'onValid', generator)\n    this.appendSubmitBranchEntry(entries, hook.branches.onInvalid, `${hook.key}-onInvalid`, 'onInvalid', generator)\n\n    const hookName = generator.const(\n      this.camelise(hook.key),\n      code`${CONTEXT}.workTasks.submitHook(${hook.key}, ${objectCode(entries)})`,\n    )\n\n    generator.blank()\n\n    return hookName\n  }\n\n  private appendSubmitBranchEntry(\n    entries: ObjectCodeProperty[],\n    branch: SubmitBranchModel | undefined,\n    key: string,\n    name: 'onAlways' | 'onValid' | 'onInvalid',\n    generator: CodeGenerator,\n  ): void {\n    if (branch === undefined || (branch.effects.length === 0 && branch.outcomes.length === 0)) {\n      return\n    }\n\n    const effectNames = branch.effects.map(effect => this.compileEffectTask(effect, generator))\n    const branchEntries: ObjectCodeProperty[] = [{ key: 'name', value: literal(name) }]\n\n    if (effectNames.length > 0) {\n      branchEntries.push({ key: 'effects', value: arrayCode(effectNames) })\n    }\n\n    if (branch.outcomes.length > 0) {\n      branchEntries.push({\n        key: 'next',\n        value: this.compileNextFunction(\n          `resolveSubmit${this.toFunctionNamePart(name)}Next`,\n          branch.outcomes,\n          generator,\n        ),\n      })\n    }\n\n    entries.push({ key: name, value: code`${CONTEXT}.workTasks.submitBranch(${key}, ${objectCode(branchEntries)})` })\n  }\n\n  private compileEffectTask(effect: EffectCall, generator: CodeGenerator): IdentifierName {\n    const effectNamePart = this.toFunctionNamePart(this.camelise(effect.name))\n    const run = this.compileFunctionExpression(`run${effectNamePart}`, generator, body => {\n      body.return(this.compileEffectCall(effect, body))\n    })\n\n    return generator.const(\n      `hookEffect${effectNamePart}`,\n      code`${CONTEXT}.workTasks.hookEffect(${effect.key}, ${objectCode([\n        { key: 'name', value: literal(effect.name) },\n        { key: 'run', value: run },\n      ])})`,\n    )\n  }\n\n  private compileAccessWhenTask(when: ExpressionValue, key: string, generator: CodeGenerator): CodeFragment {\n    const evaluate = this.compileFunctionExpression('evaluateAccessHookWhen', generator, body => {\n      body.return(code`Boolean(${this.expr.compileOperandCode(when.node, body)})`)\n    })\n\n    return code`${CONTEXT}.workTasks.accessHookWhen(${key}, ${objectCode([{ key: 'evaluate', value: evaluate }])})`\n  }\n\n  private compileSubmitPredicateTask(\n    predicate: ExpressionValue,\n    key: string,\n    name: string,\n    generator: CodeGenerator,\n  ): CodeFragment {\n    const evaluate = this.compileFunctionExpression(\n      `evaluateSubmit${this.toFunctionNamePart(name)}`,\n      generator,\n      body => {\n        body.return(code`Boolean(${this.expr.compileOperandCode(predicate.node, body)})`)\n      },\n    )\n\n    return code`${CONTEXT}.workTasks.submitPredicate(${key}, ${objectCode([\n      { key: 'name', value: literal(name) },\n      { key: 'evaluate', value: evaluate },\n    ])})`\n  }\n\n  private compileCurrentStepValidationTask(key: string, groups: readonly string[]): CodeFragment {\n    return code`${CONTEXT}.workTasks.currentStepValidation(${key}, ${objectCode([\n      { key: 'groups', value: literal(groups) },\n      { key: 'includeSubmissionOnly', value: literal(true) },\n    ])})`\n  }\n\n  /**\n   * Compiles a `next` function that walks the authored outcomes in order and\n   * returns the first that applies. Outcomes after an unconditional one are\n   * unreachable and never emitted.\n   */\n  private compileNextFunction(\n    prefix: string,\n    outcomes: readonly HookOutcomeModel[],\n    generator: CodeGenerator,\n  ): CodeFragment {\n    return this.compileFunctionExpression(prefix, generator, body => {\n      this.reachableOutcomes(outcomes).forEach(outcome => this.compileOutcome(outcome, body))\n    })\n  }\n\n  private reachableOutcomes(outcomes: readonly HookOutcomeModel[]): readonly HookOutcomeModel[] {\n    const terminalIndex = outcomes.findIndex(outcome => this.isUnconditionalTerminalOutcome(outcome))\n\n    return terminalIndex === -1 ? outcomes : outcomes.slice(0, terminalIndex + 1)\n  }\n\n  /**\n   * True when the outcome always returns: no `when` guard, and a value that\n   * cannot resolve to undefined (a dynamic redirect target can, so a dynamic\n   * redirect may still fall through to later outcomes).\n   */\n  private isUnconditionalTerminalOutcome(outcome: HookOutcomeModel): boolean {\n    if (outcome.when !== undefined) {\n      return false\n    }\n\n    return outcome.kind === HookOutcomeKind.THROW_ERROR || typeof outcome.goto === 'string'\n  }\n\n  private compileOutcome(outcome: HookOutcomeModel, generator: CodeGenerator): void {\n    const emitReturn =\n      outcome.kind === HookOutcomeKind.REDIRECT\n        ? () => this.compileRedirectReturn(outcome, generator)\n        : () => this.compileThrowErrorReturn(outcome, generator)\n\n    if (outcome.when === undefined) {\n      emitReturn()\n\n      return\n    }\n\n    const outcomeWhen = generator.const(\n      'outcomeWhen',\n      code`Boolean(${this.expr.compileOperandCode(outcome.when.node, generator)})`,\n    )\n\n    generator.if(outcomeWhen, emitReturn)\n  }\n\n  private compileRedirectReturn(redirect: RedirectOutcomeModel, generator: CodeGenerator): void {\n    if (typeof redirect.goto === 'string') {\n      generator.return(this.redirectResult(literal(redirect.goto)))\n\n      return\n    }\n\n    const gotoValue = generator.const('gotoValue', this.expr.compileOperandCode(redirect.goto.node, generator))\n\n    generator.if(code`${gotoValue} !== undefined`, () => {\n      generator.return(this.redirectResult(code`String(${gotoValue})`))\n    })\n  }\n\n  private redirectResult(value: CodeFragment): CodeFragment {\n    return objectCode([\n      { key: 'type', value: literal('redirect') },\n      { key: 'value', value },\n    ])\n  }\n\n  private compileThrowErrorReturn(errorOutcome: ThrowErrorOutcomeModel, generator: CodeGenerator): void {\n    generator.return(\n      objectCode([\n        { key: 'type', value: literal('error') },\n        {\n          key: 'value',\n          value: objectCode([\n            { key: 'status', value: literal(errorOutcome.status) },\n            { key: 'message', value: this.compileErrorMessage(errorOutcome.message, generator) },\n          ]),\n        },\n      ]),\n    )\n  }\n\n  private compileErrorMessage(message: string | ExpressionValue, generator: CodeGenerator): CodeFragment {\n    if (typeof message === 'string') {\n      return literal(message)\n    }\n\n    const messageValue = generator.const('messageValue', this.expr.compileOperandCode(message.node, generator))\n\n    return code`${messageValue} !== undefined ? String(${messageValue}) : \"\"`\n  }\n\n  private compileEffectCall(effect: EffectCall, generator: CodeGenerator): CodeFragment {\n    const argExprs = effect.arguments.map(arg => this.expr.compileOperandCode(toRawOperand(arg), generator))\n\n    return this.expr.compileFunctionCallCode(\n      effect.name,\n      [code`${CONTEXT}.effectFunctionContext`, ...argExprs],\n      effect.node.node,\n    )\n  }\n\n  /**\n   * Emits a named function expression that is async only when its body awaits\n   * — nested callbacks own their awaits without making the enclosing generated\n   * function async.\n   */\n  private compileFunctionExpression(\n    prefix: string,\n    generator: CodeGenerator,\n    buildBody: (generator: CodeGenerator) => void,\n  ): CodeFragment {\n    let bodyUsesAwait = false\n\n    return generator.functionExpression(\n      prefix,\n      [],\n      body => {\n        bodyUsesAwait = this.expr.trackNestedFunctionAwait(() =>\n          this.expr.withGeneratorScope(body, () => buildBody(body)),\n        )\n      },\n      { async: () => bodyUsesAwait },\n    )\n  }\n\n  private camelise(value: string): string {\n    const words = value.match(/[A-Z]?[a-z0-9]+|[A-Z]+/g) ?? []\n    const firstWord = (words[0] ?? 'hook').toLowerCase()\n\n    return `${firstWord}${words\n      .slice(1)\n      .map(word => this.toFunctionNamePart(word.toLowerCase()))\n      .join('')}`\n  }\n\n  private toFunctionNamePart(value: string): string {\n    return `${value.charAt(0).toUpperCase()}${value.slice(1)}`\n  }\n}\n","import {\n  code,\n  literal,\n  objectCode,\n  ObjectCodeProperty,\n} from '../../../chassis/compilation/lowering/codegen/fragments/CodeFragment'\nimport CodeGenerator from '../../../chassis/compilation/lowering/codegen/CodeGenerator'\nimport IdentifierName from '../../../chassis/compilation/lowering/codegen/fragments/IdentifierName'\nimport ExpressionDispatcher from '../../../chassis/compilation/lowering/expressions/ExpressionDispatcher'\nimport {\n  CompilationPhase,\n  compileGeneratedFunction,\n  renderGeneratedSource,\n} from '../../../chassis/compilation/lowering/GeneratedFunctionCompiler'\nimport RuntimeValueCompiler from '../../../chassis/compilation/lowering/structures/RuntimeValueCompiler'\nimport type { CompilationDependencies } from '../../../chassis/compilation/lowering/compilationDependencies.type'\nimport type { CompiledRouteMetadataFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport type { RouteMetadataModel } from '../contracts/routeMetadataModel.type'\n\n/**\n * Compiles the package-level route-metadata function for the route-tree phase.\n *\n * Journey authors can set title, description, and metadata as expressions, so\n * their values can't be fixed on the route tree at mount time. This compiler\n * turns every step's and journey's metadata into one generated function that\n * evaluates them at request time and returns the results keyed by node ID. The\n * route-tree runtime phase calls it and merges the result onto the static\n * route topology.\n *\n * Unlike per-step compilers this is compiled once at package scope (the route\n * tree spans every node), then shared across every compiled step and journey.\n */\nexport default class RouteMetadataCompiler {\n  private readonly expr: ExpressionDispatcher\n\n  private readonly values: RuntimeValueCompiler\n\n  constructor(dependencies: CompilationDependencies) {\n    this.expr = new ExpressionDispatcher(dependencies)\n    this.values = new RuntimeValueCompiler(this.expr, {\n      expressionErrorFallback: literal(undefined),\n      expressionErrorMode: 'throw',\n      omitUndefinedArrayItems: false,\n    })\n  }\n\n  /**\n   * Compiles the collected route-metadata inputs into one evaluator.\n   *\n   * The generated function returns resolved metadata keyed by node ID. Whether it\n   * is sync or async depends on whether any metadata expression calls a registered\n   * async function.\n   */\n  compile(inputs: Iterable<RouteMetadataModel>): CompiledRouteMetadataFunction {\n    return compileGeneratedFunction<CompiledRouteMetadataFunction>(this.expr, ['ctx'], () => this.buildSource(inputs), {\n      phase: CompilationPhase.ROUTE_TREE,\n    })\n  }\n\n  /**\n   * Builds inspectable generated source without constructing a Function.\n   */\n  generateSource(inputs: Iterable<RouteMetadataModel>): string {\n    return renderGeneratedSource(this.expr, () => this.buildSource(inputs))\n  }\n\n  /**\n   * Emits `routeMetadata[nodeId] = { title, description?, metadata? }` for every node.\n   */\n  private buildSource(inputs: Iterable<RouteMetadataModel>): CodeGenerator {\n    const generator = CodeGenerator.forFunction(['ctx'])\n    const entries = [...inputs]\n\n    generator.directive('use strict')\n    generator.comment('Resolved route metadata, keyed by node id')\n    const routeMetadata = generator.const('routeMetadata', code`{}`)\n\n    entries.forEach(input => this.compileEntry(input, routeMetadata, generator))\n    generator.return(routeMetadata)\n\n    return generator\n  }\n\n  /**\n   * Emits the resolved metadata object for one node. Static values sit inline\n   * in the literal; expression-backed values hoist into named consts just above.\n   */\n  private compileEntry(input: RouteMetadataModel, routeMetadata: IdentifierName, generator: CodeGenerator): void {\n    const properties: ObjectCodeProperty[] = [\n      { key: 'title', value: this.values.compileValueExpression(input.title, generator, 'title') },\n    ]\n\n    if (input.description !== undefined) {\n      properties.push({\n        key: 'description',\n        value: this.values.compileValueExpression(input.description, generator, 'description'),\n      })\n    }\n\n    if (input.metadata !== undefined) {\n      properties.push({\n        key: 'metadata',\n        value: this.values.compileValueExpression(input.metadata, generator, 'metadata'),\n      })\n    }\n\n    generator.assign(code`${routeMetadata}[${input.nodeId}]`, objectCode(properties))\n  }\n}\n","import type { NodeId } from '../../contracts/ast/engine.type'\nimport type {\n  CompiledJourneyFunctions,\n  CompiledPackageFunctions,\n  CompiledStepFunctions,\n} from '../../contracts/plans/compilationArtefacts.type'\nimport type {\n  CompiledStaticDataFunction,\n  CompiledValidationFunction,\n} from '../../contracts/compiled/compiledFunctions.type'\nimport type { CompilationDependencies } from './compilationDependencies.type'\nimport type { JourneyModel, StepModel } from '../../contracts/models/compilationModel.type'\nimport type { RouteMetadataModel } from '../../../concerns/route/contracts/routeMetadataModel.type'\nimport StepValidationCompiler from '../../../concerns/validation/lowering/StepValidationCompiler'\nimport EntryValidationCompiler from '../../../concerns/validation/lowering/EntryValidationCompiler'\nimport ReachabilityCompiler from '../../../concerns/reachability/lowering/ReachabilityCompiler'\nimport { evaluateReachabilityState } from '../../../concerns/reachability/lowering/graph/evaluateReachabilityState'\nimport StepFieldInventoryCompiler from '../../../concerns/answer-cleardown/lowering/StepFieldInventoryCompiler'\nimport StepResolveCompiler from '../../../concerns/resolve/lowering/StepResolveCompiler'\nimport StepAnswerPreparationCompiler from '../../../concerns/answer-preparation/lowering/StepAnswerPreparationCompiler'\nimport HookLifecycleCompiler from '../../../concerns/hooks/lowering/HookLifecycleCompiler'\nimport RouteMetadataCompiler from '../../../concerns/route/lowering/RouteMetadataCompiler'\n\nexport default class CodegenOrchestrator {\n  constructor(private readonly dependencies: CompilationDependencies) {}\n\n  compilePackageFunctions(routeMetadata: ReadonlyMap<NodeId, RouteMetadataModel>): CompiledPackageFunctions {\n    const routeMetadataCompiler = new RouteMetadataCompiler(this.dependencies)\n\n    return {\n      compiledRouteMetadata: routeMetadataCompiler.compile(routeMetadata.values()),\n    }\n  }\n\n  compileStepFunctions(\n    step: StepModel,\n    journeyValidation: CompiledValidationFunction | undefined,\n  ): CompiledStepFunctions {\n    const hookCompiler = new HookLifecycleCompiler(this.dependencies)\n    const answerPrepCompiler = new StepAnswerPreparationCompiler(this.dependencies)\n    const validationCompiler = new StepValidationCompiler(this.dependencies)\n    const entryValidationCompiler = new EntryValidationCompiler(this.dependencies)\n    const resolveCompiler = new StepResolveCompiler(this.dependencies)\n\n    return {\n      compiledStaticData: this.compileStaticData(step.staticData),\n      compiledAccessLifecycle: hookCompiler.compileAccessLifecycle(step.hooks.access),\n      compiledSubmitHooks: hookCompiler.compileSubmitHooks(step.hooks.submit),\n      compiledAnswerPreparation: answerPrepCompiler.compile(step.answerPreparation),\n      compiledValidation: journeyValidation ?? validationCompiler.compileStepValidation(step.validation),\n      compiledEntryValidation: entryValidationCompiler.compileOnEntryValidation(step.validation),\n      compiledResolve: resolveCompiler.compile(step.resolve),\n    }\n  }\n\n  compileJourneyFunctions(journey: JourneyModel): CompiledJourneyFunctions {\n    const { stateTable } = journey.reachability\n    const reachabilityCompiler = new ReachabilityCompiler(this.dependencies)\n    const fieldInventoryCompiler = new StepFieldInventoryCompiler(this.dependencies)\n    const hookCompiler = new HookLifecycleCompiler(this.dependencies)\n    const answerPrepCompiler = new StepAnswerPreparationCompiler(this.dependencies)\n\n    return {\n      compiledReachabilityFacts: reachabilityCompiler.compileFacts(journey.reachability),\n      compiledReachabilityState: input => evaluateReachabilityState(stateTable, input),\n      compiledFieldInventory: fieldInventoryCompiler.compile(journey.cleardown),\n      compiledStaticData: this.compileStaticData(journey.staticData),\n      compiledAccessLifecycle: hookCompiler.compileAccessLifecycle(journey.hooks.access),\n      compiledAnswerPreparation: answerPrepCompiler.compile(journey.answerPreparation),\n      compiledStepValidations: this.compileJourneyValidationIndex(journey),\n    }\n  }\n\n  // When reachability checks are enabled, a step has eager validation when it\n  // carries validating field blocks or a domain `validWhen`.\n  private compileJourneyValidationIndex(journey: JourneyModel): ReadonlyMap<NodeId, CompiledValidationFunction> {\n    if (journey.reachability.stateTable.reachabilityDisabled) {\n      return new Map()\n    }\n\n    const validationCompiler = new StepValidationCompiler(this.dependencies)\n    const compiledStepValidations = new Map<NodeId, CompiledValidationFunction>()\n\n    journey.steps.forEach((step, stepId) => {\n      if (!step.validation.hasValidation) {\n        return\n      }\n\n      compiledStepValidations.set(stepId, validationCompiler.compileStepValidation(step.validation))\n    })\n\n    return compiledStepValidations\n  }\n\n  private compileStaticData(staticData: Record<string, unknown>): CompiledStaticDataFunction {\n    return () => structuredClone(staticData)\n  }\n}\n","import type { NodeId } from '../../contracts/ast/engine.type'\nimport type { CompiledJourneyFunctions } from '../../contracts/plans/compilationArtefacts.type'\nimport type { JourneyModel, StepModel } from '../../contracts/models/compilationModel.type'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../contracts/work/work.type'\nimport { createWorkTask } from '../../work/workTask'\nimport type CompilationState from '../pipeline/CompilationState'\nimport CodegenOrchestrator from './CodegenOrchestrator'\n\nexport interface JourneyCodegenWorkProps {\n  readonly journeyId: NodeId\n  readonly journey: JourneyModel\n}\n\nexport interface StepCodegenWorkProps {\n  readonly stepId: NodeId\n  readonly step: StepModel\n  readonly journeyFunctions: CompiledJourneyFunctions\n}\n\n/**\n * The lowering phase as work: the phase task fans out into one\n * `codegen.package-functions` task plus one `codegen.journey` task per\n * journey, and each journey task fans out into its `codegen.step` tasks.\n */\nexport const COMPILATION_LOWERING_WORK_HANDLER: WorkHandler<'compilation.lowering', undefined> = {\n  kind: 'compilation.lowering',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n\n    const journeyTasks = [...state.model.journeys.entries()]\n      // A container journey owns no steps and has never produced a compiled\n      // journey; emitting one would change the compiled package surface.\n      .filter(([, journey]) => journey.steps.size > 0)\n      .map(([journeyId, journey]) =>\n        createWorkTask(\n          `journey:${journeyId}`,\n          JOURNEY_CODEGEN_WORK_HANDLER,\n          { journeyId, journey },\n          JOURNEY_CODEGEN_WORK_INSTRUMENTATION,\n        ),\n      )\n\n    return {\n      groups: [\n        {\n          mode: 'sequential' as const,\n          children: [createWorkTask('package-functions', PACKAGE_FUNCTIONS_WORK_HANDLER, undefined), ...journeyTasks],\n        },\n      ],\n    }\n  },\n}\n\nexport const PACKAGE_FUNCTIONS_WORK_HANDLER: WorkHandler<'codegen.package-functions', undefined> = {\n  kind: 'codegen.package-functions',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n    const orchestrator = new CodegenOrchestrator(state.dependencies)\n\n    state.recordPackageFunctions(orchestrator.compilePackageFunctions(state.model.routeMetadata))\n\n    return { output: undefined }\n  },\n}\n\nexport const JOURNEY_CODEGEN_WORK_INSTRUMENTATION: WorkInstrumentation<JourneyCodegenWorkProps, undefined> = {\n  resolveTraceMetadataAtStart: ctx => ({ nodeId: ctx.props.journeyId }),\n  resolveTraceMetadataAtFinish: () => undefined,\n}\n\nexport const JOURNEY_CODEGEN_WORK_HANDLER: WorkHandler<'codegen.journey', JourneyCodegenWorkProps> = {\n  kind: 'codegen.journey',\n\n  begin(ctx: WorkContextContract<CompilationState, JourneyCodegenWorkProps>) {\n    const state = ctx.state\n    const { journeyId, journey } = ctx.props\n    const orchestrator = new CodegenOrchestrator(state.dependencies)\n    const journeyFunctions = orchestrator.compileJourneyFunctions(journey)\n\n    state.journeys.set(journeyId, {\n      mountInfo: journey.mountInfo,\n      ...journeyFunctions,\n      ...state.packageFunctions,\n    })\n\n    const stepTasks = [...journey.steps.entries()].map(([stepId, step]) =>\n      createWorkTask(\n        `step:${stepId}`,\n        STEP_CODEGEN_WORK_HANDLER,\n        { stepId, step, journeyFunctions },\n        STEP_CODEGEN_WORK_INSTRUMENTATION,\n      ),\n    )\n\n    return { groups: [{ mode: 'sequential' as const, children: stepTasks }] }\n  },\n}\n\nexport const STEP_CODEGEN_WORK_INSTRUMENTATION: WorkInstrumentation<StepCodegenWorkProps, undefined> = {\n  resolveTraceMetadataAtStart: ctx => ({ nodeId: ctx.props.stepId }),\n  resolveTraceMetadataAtFinish: () => undefined,\n}\n\nexport const STEP_CODEGEN_WORK_HANDLER: WorkHandler<'codegen.step', StepCodegenWorkProps> = {\n  kind: 'codegen.step',\n\n  begin(ctx: WorkContextContract<CompilationState, StepCodegenWorkProps>) {\n    const state = ctx.state\n    const { stepId, step, journeyFunctions } = ctx.props\n    const orchestrator = new CodegenOrchestrator(state.dependencies)\n    const stepFunctions = orchestrator.compileStepFunctions(step, journeyFunctions.compiledStepValidations.get(stepId))\n\n    state.steps.set(stepId, {\n      mountInfo: step.mountInfo,\n      compiledReachabilityFacts: journeyFunctions.compiledReachabilityFacts,\n      compiledReachabilityState: journeyFunctions.compiledReachabilityState,\n      compiledFieldInventory: journeyFunctions.compiledFieldInventory,\n      compiledStepValidations: journeyFunctions.compiledStepValidations,\n      ...stepFunctions,\n      ...state.packageFunctions,\n    })\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationLoweringTask() {\n  return createWorkTask('lowering', COMPILATION_LOWERING_WORK_HANDLER, undefined)\n}\n","import type { JourneyASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport type { ASTNode, NodeId } from '../../../chassis/contracts/ast/engine.type'\nimport type { JourneyRouteIndex, StepRouteIndex } from '../contracts/routeDescriptors.type'\n\n/**\n * Builds the static route indexes for a compiled package: one descriptor per\n * step and journey, keyed by NodeId, carrying the authored path and the chain\n * of ancestor journey IDs derived from AST `parent` links. The mount registry\n * later joins these against the compiled artifacts to mount URLs.\n */\nexport default class RouteIndexBuilder {\n  buildJourneyRouteIndex(journeyNodes: JourneyASTNode[]): JourneyRouteIndex {\n    return new Map(\n      journeyNodes.map(node => [\n        node.id,\n        {\n          nodeId: node.id,\n          path: node.properties.path,\n          ancestorJourneyIds: this.ancestorJourneyIds(node),\n        },\n      ]),\n    )\n  }\n\n  buildStepRouteIndex(stepNodes: StepASTNode[]): StepRouteIndex {\n    return new Map(\n      stepNodes.map(node => [\n        node.id,\n        {\n          nodeId: node.id,\n          path: node.properties.path,\n          ancestorJourneyIds: this.ancestorJourneyIds(node.parent),\n        },\n      ]),\n    )\n  }\n\n  /** Journey NodeIds from the outermost ancestor down, walking `parent` from `start`. */\n  private ancestorJourneyIds(start: ASTNode | undefined): NodeId[] {\n    const ids: NodeId[] = []\n    let current = start\n\n    while (current !== undefined) {\n      ids.push(current.id)\n      current = current.parent\n    }\n\n    ids.reverse()\n\n    return ids\n  }\n}\n","import type { WorkContextContract, WorkHandler } from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { JourneyASTNode, StepASTNode } from '../../../chassis/contracts/ast/structures.type'\nimport { ASTNodeType } from '../../../chassis/contracts/ast/enums'\nimport type CompilationState from '../../../chassis/compilation/pipeline/CompilationState'\nimport RouteIndexBuilder from './RouteIndexBuilder'\n\nexport const COMPILATION_ROUTES_WORK_HANDLER: WorkHandler<'compilation.routes', undefined> = {\n  kind: 'compilation.routes',\n\n  begin(ctx: WorkContextContract<CompilationState, undefined>) {\n    const state = ctx.state\n    const routeIndexBuilder = new RouteIndexBuilder()\n\n    const stepNodes = state.ast.nodeIndex.findByType<StepASTNode>(ASTNodeType.STEP)\n    const journeyNodes = state.ast.nodeIndex.findByType<JourneyASTNode>(ASTNodeType.JOURNEY)\n\n    state.recordRouteIndexes({\n      stepRouteIndex: routeIndexBuilder.buildStepRouteIndex(stepNodes),\n      journeyRouteIndex: routeIndexBuilder.buildJourneyRouteIndex(journeyNodes),\n    })\n\n    return { output: undefined }\n  },\n}\n\nexport function createCompilationRoutesTask() {\n  return createWorkTask('routes', COMPILATION_ROUTES_WORK_HANDLER, undefined)\n}\n","import type { JourneyDefinition } from '../../../../authoring/types/structures.type'\nimport type FunctionRegistry from '../../registries/FunctionRegistry'\nimport type ComponentRegistry from '../../registries/ComponentRegistry'\nimport type { WorkTask } from '../../contracts/work/work.type'\nimport CompilationState from './CompilationState'\nimport { createCompilationPipelineTask } from './CompilationPipelineWorkHandler'\nimport { createCompilationDslValidationTask } from '../../../concerns/dsl-validation/CompilationDslValidationWorkHandler'\nimport { createCompilationAstTask } from '../ast/CompilationAstWorkHandler'\nimport { createCompilationSemanticAnalysisTask } from '../../../concerns/semantic-analysis/CompilationSemanticAnalysisWorkHandler'\nimport { createCompilationAnalysisTask } from '../analysis/CompilationAnalysisWorkHandler'\nimport { createCompilationLoweringTask } from '../lowering/CompilationLoweringWorkHandler'\nimport { createCompilationRoutesTask } from '../../../concerns/route/analysis/CompilationRoutesWorkHandler'\n\nexport interface CompilationPipelineConfig {\n  readonly journeyDefinition: JourneyDefinition\n  readonly functionRegistry: FunctionRegistry\n  readonly componentRegistry: ComponentRegistry\n}\n\n/**\n * The single source of compilation phase order. The phase tasks carry no props\n * because all data flows through the shared `CompilationState`.\n */\nexport default class CompilationPipelineBootstrap {\n  constructor(private readonly config: CompilationPipelineConfig) {}\n\n  buildPipelineElement(): WorkTask {\n    return createCompilationPipelineTask({\n      phases: this.buildPhases(),\n    })\n  }\n\n  buildExecutionContext(): CompilationState {\n    const { journeyDefinition, functionRegistry, componentRegistry } = this.config\n\n    return new CompilationState(journeyDefinition, { functionRegistry, componentRegistry })\n  }\n\n  private buildPhases(): readonly WorkTask[] {\n    return [\n      createCompilationDslValidationTask(),\n      createCompilationAstTask(),\n      createCompilationSemanticAnalysisTask(),\n      createCompilationAnalysisTask(),\n      createCompilationLoweringTask(),\n      createCompilationRoutesTask(),\n    ]\n  }\n}\n","import type { JourneyDefinition } from '../../../../authoring/types/structures.type'\nimport type { CompiledPackage } from '../../contracts/plans/compilationArtefacts.type'\nimport type { ForgeInstrumentation } from '../../tracing/ForgeTraceSinkDispatcher'\nimport type TraceSpan from '../../tracing/TraceSpan'\nimport FunctionRegistry from '../../registries/FunctionRegistry'\nimport ComponentRegistry from '../../registries/ComponentRegistry'\nimport WorkExecutor from '../../work/WorkExecutor'\nimport WorkContext from '../../work/WorkContext'\nimport WorkExecutionError from '../../work/WorkExecutionError'\nimport CompilationPipelineTraceProjector from './CompilationPipelineTraceProjector'\nimport CompilationState from './CompilationState'\nimport CompilationPipelineBootstrap from './CompilationPipelineBootstrap'\n\nexport interface CompilationPipelineOptions {\n  readonly functionRegistry: FunctionRegistry\n  readonly componentRegistry: ComponentRegistry\n  readonly instrumentation?: ForgeInstrumentation\n}\n\n/**\n * Compiles a journey definition by running the `compilation.pipeline` task tree\n * through the work executor — the same controller that runs the request\n * pipeline. Compilation handlers are all synchronous, so the tree executes\n * via `executeSyncWithUnit` and `compile()` stays synchronous end to end.\n */\nexport default class CompilationPipeline {\n  private readonly traceProjector = new CompilationPipelineTraceProjector()\n\n  constructor(private readonly options: CompilationPipelineOptions) {}\n\n  compile(journeyDefinition: JourneyDefinition): CompiledPackage {\n    const traceEnabled = this.options.instrumentation?.enabled === true\n    const bootstrap = new CompilationPipelineBootstrap({\n      journeyDefinition,\n      functionRegistry: this.options.functionRegistry,\n      componentRegistry: this.options.componentRegistry,\n    })\n    const state = bootstrap.buildExecutionContext()\n    const executor = new WorkExecutor(traceEnabled)\n    const pipelineElement = bootstrap.buildPipelineElement()\n\n    try {\n      const { traceSpan } = executor.executeSyncWithUnit(pipelineElement, new WorkContext(state))\n\n      this.emitTrace(state, { root: traceSpan, outcome: 'compiled' })\n\n      return this.assemblePackage(state)\n    } catch (error) {\n      const original = error instanceof WorkExecutionError ? error.original : error\n      const root = error instanceof WorkExecutionError ? error.traceSpan : undefined\n\n      this.emitTrace(state, { root, outcome: 'error', error: original })\n\n      throw original\n    }\n  }\n\n  private assemblePackage(state: CompilationState): CompiledPackage {\n    return {\n      journeyCode: state.ast.rootNode.properties.code,\n      ...state.routeIndexes,\n      steps: state.steps,\n      journeys: state.journeys,\n    }\n  }\n\n  private emitTrace(\n    state: CompilationState,\n    result: { root: TraceSpan | undefined; outcome: 'compiled' | 'error'; error?: unknown },\n  ): void {\n    const { instrumentation } = this.options\n\n    if (instrumentation === undefined) {\n      return\n    }\n\n    this.traceProjector.emit({\n      instrumentation,\n      root: result.root,\n      journeyCode: state.journeyCode,\n      outcome: result.outcome,\n      error: result.error,\n    })\n  }\n}\n","import type { JourneyDefinition } from '../authoring/types/structures.type'\nimport type { ForgePackageRegistration, PackageDependencies, NodeId } from './chassis/contracts/ast/engine.type'\nimport { createFunctionsRegistry } from '../authoring/utils/deprecated/createFunctionsRegistry'\nimport { isFunctionRegistry } from '../authoring/registries/BaseFunctionRegistry'\nimport ComponentRegistry from './chassis/registries/ComponentRegistry'\nimport FunctionRegistry from './chassis/registries/FunctionRegistry'\nimport ScopedComponentRegistry from './chassis/registries/ScopedComponentRegistry'\nimport ScopedFunctionRegistry from './chassis/registries/ScopedFunctionRegistry'\nimport CompilationPipeline from './chassis/compilation/pipeline/CompilationPipeline'\nimport type { ForgeInstrumentation } from './chassis/tracing/ForgeTraceSinkDispatcher'\n\nimport type {\n  CompiledJourney,\n  CompiledStep,\n  CompiledPackage,\n} from './chassis/contracts/plans/compilationArtefacts.type'\nimport type { JourneyRouteIndex, StepRouteIndex } from './concerns/route/contracts/routeDescriptors.type'\nimport ForgeInternalError from './errors/ForgeInternalError'\n\nexport interface PackageInstanceOptions<TDeps> {\n  readonly functionRegistry: FunctionRegistry\n  readonly componentRegistry: ComponentRegistry\n  readonly functionDependencies?: TDeps\n  readonly instrumentation: ForgeInstrumentation\n}\n\nexport default class PackageInstance {\n  private readonly dependencies: PackageDependencies\n\n  private readonly compilation: CompiledPackage\n\n  private readonly rawConfiguration: JourneyDefinition\n\n  constructor(pkg: ForgePackageRegistration<any>, options: PackageInstanceOptions<any>) {\n    this.dependencies = {\n      functionRegistry: PackageInstance.resolveFunctionRegistry(pkg, options),\n      componentRegistry: PackageInstance.resolveComponentRegistry(pkg, options.componentRegistry),\n    }\n\n    const pipeline = new CompilationPipeline({\n      functionRegistry: this.dependencies.functionRegistry,\n      componentRegistry: this.dependencies.componentRegistry,\n      instrumentation: options.instrumentation,\n    })\n\n    // The pipeline validates the definition in its dsl-validation phase and\n    // emits the compilation trace (success or error) before rethrowing.\n    this.rawConfiguration = pkg.journey\n    this.compilation = pipeline.compile(pkg.journey)\n  }\n\n  getDependencies(): PackageDependencies {\n    return this.dependencies\n  }\n\n  getCompiledStep(stepId: NodeId): CompiledStep {\n    const step = this.compilation.steps.get(stepId)\n\n    if (!step) {\n      throw new ForgeInternalError(`Step \"${stepId}\" not found in compiled journey`)\n    }\n\n    return step\n  }\n\n  getCompiledSteps(): ReadonlyMap<NodeId, CompiledStep> {\n    return this.compilation.steps\n  }\n\n  getStepRouteIndex(): StepRouteIndex {\n    return new Map(this.compilation.stepRouteIndex)\n  }\n\n  getJourneyRouteIndex(): JourneyRouteIndex {\n    return new Map(this.compilation.journeyRouteIndex)\n  }\n\n  getCompiledJourney(journeyId: NodeId): CompiledJourney | undefined {\n    return this.compilation.journeys.get(journeyId)\n  }\n\n  getConfiguration(): JourneyDefinition {\n    return this.rawConfiguration\n  }\n\n  getJourneyCode(): string {\n    return this.compilation.journeyCode\n  }\n\n  private static resolveFunctionRegistry(\n    pkg: ForgePackageRegistration<any>,\n    options: PackageInstanceOptions<any>,\n  ): FunctionRegistry {\n    if (!pkg.functions) {\n      return options.functionRegistry\n    }\n\n    const resolvedDeps = options.functionDependencies ?? {}\n    const scopedFunctionRegistry = new ScopedFunctionRegistry(options.functionRegistry)\n\n    const { functions } = pkg\n\n    if (isFunctionRegistry(functions)) {\n      scopedFunctionRegistry.register(functions.build(resolvedDeps))\n    } else if (Array.isArray(functions)) {\n      functions.forEach(registry => {\n        scopedFunctionRegistry.register(registry.build(resolvedDeps))\n      })\n    } else {\n      // deprecated: old implementations-map path\n      scopedFunctionRegistry.register(createFunctionsRegistry(functions, resolvedDeps))\n    }\n\n    return scopedFunctionRegistry\n  }\n\n  private static resolveComponentRegistry(\n    pkg: ForgePackageRegistration<any>,\n    componentRegistry: ComponentRegistry,\n  ): ComponentRegistry {\n    if (!pkg.components) {\n      return componentRegistry\n    }\n\n    const scopedComponentRegistry = new ScopedComponentRegistry(componentRegistry)\n\n    scopedComponentRegistry.registerMany(pkg.components)\n\n    return scopedComponentRegistry\n  }\n}\n","import type { ConditionFunctionExpr, Resolvable } from '../types/expressions.type'\nimport { FunctionType } from '../types/enums'\nimport { BaseFunctionRegistry, CONDITION_OUTPUT_SCHEMA, type RegistrationOptions } from './BaseFunctionRegistry'\n\nexport default class ConditionRegistry<TDeps = Record<string, never>> extends BaseFunctionRegistry<TDeps> {\n  constructor() {\n    super(FunctionType.CONDITION, CONDITION_OUTPUT_SCHEMA)\n  }\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions & {\n      factory: (deps: TDeps) => (value: any, ...args: TArgs) => boolean | PromiseLike<boolean>\n    },\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ConditionFunctionExpr\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => boolean | PromiseLike<boolean>,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ConditionFunctionExpr\n\n  register<TArgs extends any[]>(\n    name: string,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => boolean | PromiseLike<boolean>,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ConditionFunctionExpr\n\n  register<TArgs extends any[]>(\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => boolean | PromiseLike<boolean>,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ConditionFunctionExpr\n\n  register<TArgs extends any[]>(\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => boolean | PromiseLike<boolean>,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ConditionFunctionExpr\n\n  register(\n    first: string | RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    second?: RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    third?: (deps: TDeps) => (...args: any[]) => any,\n  ): (...args: any[]) => ConditionFunctionExpr {\n    const { name, options, factory } = this.parseArgs(first, second, third)\n\n    this.store(name, options, factory)\n\n    return this.buildExpressionHandle(name, options.prepare) as any\n  }\n}\n","import ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst generalConditions = new ConditionRegistry()\n\nexport const GeneralConditions = {\n  /** Checks if a value is not empty/null/undefined */\n  IsRequired: generalConditions.register('IsRequired', {\n    factory: () => (value: unknown) =>\n      !(\n        value === null ||\n        value === undefined ||\n        (typeof value === 'string' && value.trim() === '') ||\n        (Array.isArray(value) && value.length === 0)\n      ),\n  }),\n\n  /** Checks if a value is strictly equal to an expected value */\n  Equals: generalConditions.register('Equals', {\n    factory: () => (value: unknown, expected: unknown) => value === expected,\n  }),\n}\n\nexport { generalConditions as generalConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst stringSchema = z.string()\nconst stringArgsSchema = z.tuple([z.string()])\nconst nonNegativeNumberArgsSchema = z.tuple([z.number().nonnegative()])\n\nconst stringConditions = new ConditionRegistry()\n\nexport const StringConditions = {\n  /** Checks if a string matches a regular expression pattern */\n  MatchesRegex: stringConditions.register('String.MatchesRegex', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, pattern: string) => {\n      try {\n        return new RegExp(pattern).test(value)\n      } catch {\n        throw new Error(`Condition.String.MatchesRegex: Invalid regex pattern \"${pattern}\"`)\n      }\n    },\n  }),\n\n  /** Checks if a string has at least the minimum specified length */\n  HasMinLength: stringConditions.register('String.HasMinLength', {\n    inputSchema: stringSchema,\n    argumentsSchema: nonNegativeNumberArgsSchema,\n    factory: () => (value: string, min: number) => value.length >= min,\n  }),\n\n  /** Checks if a string does not exceed the maximum specified length */\n  HasMaxLength: stringConditions.register('String.HasMaxLength', {\n    inputSchema: stringSchema,\n    argumentsSchema: nonNegativeNumberArgsSchema,\n    factory: () => (value: string, max: number) => value.length <= max,\n  }),\n\n  /** Checks if a string has exactly the specified length */\n  HasExactLength: stringConditions.register('String.HasExactLength', {\n    inputSchema: stringSchema,\n    argumentsSchema: nonNegativeNumberArgsSchema,\n    factory: () => (value: string, len: number) => value.length === len,\n  }),\n\n  /** Checks if a string contains at most the specified number of words */\n  HasMaxWords: stringConditions.register('String.HasMaxWords', {\n    inputSchema: stringSchema,\n    argumentsSchema: nonNegativeNumberArgsSchema,\n    factory: () => (value: string, maxWords: number) => {\n      const trimmed = value.trim()\n\n      if (trimmed === '') {\n        return maxWords >= 0\n      }\n\n      return trimmed.split(/\\s+/).length <= maxWords\n    },\n  }),\n\n  /** Contains only letters (A-Z, a-z) */\n  LettersOnly: stringConditions.register('String.LettersOnly', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z]+$/.test(value),\n  }),\n\n  /** Contains only digits (0-9) */\n  DigitsOnly: stringConditions.register('String.DigitsOnly', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[0-9]+$/.test(value),\n  }),\n\n  /** Contains only letters and common punctuation */\n  LettersWithCommonPunctuation: stringConditions.register('String.LettersWithCommonPunctuation', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z.,'\"()\\-!? ]+$/.test(value),\n  }),\n\n  /** Contains only letters, spaces, dashes, and apostrophes */\n  LettersWithSpaceDashApostrophe: stringConditions.register('String.LettersWithSpaceDashApostrophe', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z\\s\\-']+$/.test(value),\n  }),\n\n  /** Contains only letters and digits (alphanumeric) */\n  LettersAndDigitsOnly: stringConditions.register('String.LettersAndDigitsOnly', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z0-9]+$/.test(value),\n  }),\n\n  /** Contains only alphanumeric characters and common punctuation */\n  AlphanumericWithCommonPunctuation: stringConditions.register('String.AlphanumericWithCommonPunctuation', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z0-9.,'\"()\\-!? ]+$/.test(value),\n  }),\n\n  /** Contains only alphanumeric characters and safe symbols */\n  AlphanumericWithAllSafeSymbols: stringConditions.register('String.AlphanumericWithAllSafeSymbols', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => /^[A-Za-z0-9 .,;:'\"()\\-!?@#$%^&*]+$/.test(value),\n  }),\n\n  /** Checks if a string starts with the specified prefix */\n  StartsWith: stringConditions.register('String.StartsWith', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, prefix: string) => value.startsWith(prefix),\n  }),\n\n  /** Checks if a string ends with the specified suffix */\n  EndsWith: stringConditions.register('String.EndsWith', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, suffix: string) => value.endsWith(suffix),\n  }),\n\n  /** Checks if a string contains the specified substring */\n  Contains: stringConditions.register('String.Contains', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, substring: string) => value.includes(substring),\n  }),\n}\n\nexport { stringConditions as stringConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst addressConditions = new ConditionRegistry()\n\nexport const AddressConditions = {\n  /** Validates if a string is a valid UK postcode format */\n  IsValidPostcode: addressConditions.register('Address.IsValidPostcode', {\n    inputSchema: z.string(),\n    factory: () => (value: string) => /^([A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}| ?0A{2})$/i.test(value),\n  }),\n}\n\nexport { addressConditions as addressConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst emailConditions = new ConditionRegistry()\n\n// Domain labels use the unambiguous form `[a-z0-9](?:[a-z0-9-]*[a-z0-9])?` so any span\n// matches exactly one way - no nested overlapping quantifiers, so no catastrophic\n// backtracking. TLD is widened to the DNS label max (63) so real TLDs like `.engineering`\n// pass. Kept strict: the lookahead still rejects consecutive dots.\nconst emailRegex =\n  /^(?!.*\\.\\.)[a-z0-9_%+-](?:[a-z0-9._%+-]*[a-z0-9_%+-])?@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n// RFC 5321 caps a full address at 254 characters. Rejecting anything longer before the\n// regex runs bounds the input the pattern ever sees.\nconst MAX_EMAIL_LENGTH = 254\n\nexport const EmailConditions = {\n  /** Validates if a string is a properly formatted email address */\n  IsValidEmail: emailConditions.register('Email.IsValidEmail', {\n    inputSchema: z.string(),\n    factory: () => (value: string) => {\n      if (value.length > MAX_EMAIL_LENGTH) {\n        return false\n      }\n\n      return emailRegex.test(value)\n    },\n  }),\n}\n\nexport { emailConditions as emailConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nfunction parseISODate(value: unknown): { year: number; month: number; day: number } | null {\n  if (typeof value !== 'string') {\n    return null\n  }\n\n  const dateMatch = value.match(/^(\\d{4})-(\\d{2})-(\\d{2})$/)\n  if (!dateMatch) {\n    return null\n  }\n\n  const year = parseInt(dateMatch[1], 10)\n  const month = parseInt(dateMatch[2], 10)\n  const day = parseInt(dateMatch[3], 10)\n\n  if (month < 1 || month > 12 || day < 1 || day > 31) {\n    return null\n  }\n\n  return { year, month, day }\n}\n\nconst stringSchema = z.string()\nconst stringArgsSchema = z.tuple([z.string()])\n\nconst dateConditions = new ConditionRegistry()\n\nexport const DateConditions = {\n  /** Checks if a value is a valid ISO-8601 date string (YYYY-MM-DD) */\n  IsValid: dateConditions.register('Date.IsValid', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        return false\n      }\n\n      const date = new Date(parsed.year, parsed.month - 1, parsed.day)\n\n      return !Number.isNaN(date.getTime()) &&\n        date.getFullYear() === parsed.year &&\n        date.getMonth() === parsed.month - 1 &&\n        date.getDate() === parsed.day\n    },\n  }),\n\n  /** Validates if an ISO date string has a valid year component (1000-9999) */\n  IsValidYear: dateConditions.register('Date.IsValidYear', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        return false\n      }\n\n      return parsed.year >= 1000 && parsed.year <= 9999\n    },\n  }),\n\n  /** Validates if an ISO date string has a valid month component (1-12) */\n  IsValidMonth: dateConditions.register('Date.IsValidMonth', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        return false\n      }\n\n      return parsed.month >= 1 && parsed.month <= 12\n    },\n  }),\n\n  /** Validates if a date string has a valid day component for its specific month/year */\n  IsValidDay: dateConditions.register('Date.IsValidDay', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const dateMatch = value.match(/^(\\d{4})-(\\d{2})-(\\d{2})$/)\n      if (!dateMatch) {\n        return false\n      }\n\n      const year = parseInt(dateMatch[1], 10)\n      const month = parseInt(dateMatch[2], 10)\n      const day = parseInt(dateMatch[3], 10)\n\n      if (month < 1 || month > 12) {\n        return false\n      }\n\n      const daysInMonth = new Date(year, month, 0).getDate()\n\n      return day >= 1 && day <= daysInMonth\n    },\n  }),\n\n  /** Checks if an ISO date string is before another ISO date string */\n  IsBefore: dateConditions.register('Date.IsBefore', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, dateStr: string) => {\n      const valueParsed = parseISODate(value)\n      const compareParsed = parseISODate(dateStr)\n\n      if (!valueParsed) {\n        throw new Error(`Condition.Date.IsBefore: Invalid date string \"${value}\"`)\n      }\n      if (!compareParsed) {\n        throw new Error(`Condition.Date.IsBefore: Invalid comparison date string \"${dateStr}\"`)\n      }\n\n      const valueDate = new Date(valueParsed.year, valueParsed.month - 1, valueParsed.day)\n      const compareDate = new Date(compareParsed.year, compareParsed.month - 1, compareParsed.day)\n\n      return valueDate < compareDate\n    },\n  }),\n\n  /** Checks if an ISO date string is after another ISO date string */\n  IsAfter: dateConditions.register('Date.IsAfter', {\n    inputSchema: stringSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: string, dateStr: string) => {\n      const valueParsed = parseISODate(value)\n      if (!valueParsed) {\n        throw new Error(`Condition.Date.IsAfter: Invalid date string \"${value}\"`)\n      }\n\n      const compareParsed = parseISODate(dateStr)\n      if (!compareParsed) {\n        throw new Error(`Condition.Date.IsAfter: Invalid comparison date string \"${dateStr}\"`)\n      }\n\n      const valueDate = new Date(valueParsed.year, valueParsed.month - 1, valueParsed.day)\n      const compareDate = new Date(compareParsed.year, compareParsed.month - 1, compareParsed.day)\n\n      return valueDate > compareDate\n    },\n  }),\n\n  /** Checks if an ISO date string is in the future (after today) */\n  IsFutureDate: dateConditions.register('Date.IsFutureDate', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        throw new Error(`Condition.Date.IsFutureDate: Invalid date string \"${value}\"`)\n      }\n\n      const valueDate = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day))\n      const today = new Date()\n      const todayUTC = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()))\n\n      return valueDate > todayUTC\n    },\n  }),\n\n  /** Checks if an ISO date string is in the past (before today) */\n  IsPastDate: dateConditions.register('Date.IsPastDate', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        throw new Error(`Condition.Date.IsPastDate: Invalid date string \"${value}\"`)\n      }\n\n      const valueDate = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day))\n      const today = new Date()\n      const todayUTC = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()))\n\n      return valueDate < todayUTC\n    },\n  }),\n\n  /** Checks if an ISO date string is today */\n  IsToday: dateConditions.register('Date.IsToday', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const parsed = parseISODate(value)\n      if (!parsed) {\n        throw new Error(`Condition.Date.IsToday: Invalid date string \"${value}\"`)\n      }\n\n      const valueDate = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day))\n      const today = new Date()\n      const todayUTC = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()))\n\n      return valueDate.getTime() === todayUTC.getTime()\n    },\n  }),\n}\n\nexport { dateConditions as dateConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst numberSchema = z.number()\nconst numberArgsSchema = z.tuple([z.number()])\nconst numberRangeArgsSchema = z.tuple([z.number(), z.number()])\n\nconst numberConditions = new ConditionRegistry()\n\nexport const NumberConditions = {\n  /** Checks if a value is a number (not NaN, not a string, not undefined) */\n  IsNumber: numberConditions.register('Number.IsNumber', {\n    factory: () => (value: unknown) => typeof value === 'number' && !Number.isNaN(value),\n  }),\n\n  /** Checks if a value is an integer (whole number) */\n  IsInteger: numberConditions.register('Number.IsInteger', {\n    factory: () => (value: unknown) => typeof value === 'number' && !Number.isNaN(value) && Number.isInteger(value),\n  }),\n\n  /** Checks if a number is greater than a threshold value */\n  GreaterThan: numberConditions.register('Number.GreaterThan', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, threshold: number) => value > threshold,\n  }),\n\n  /** Checks if a number is greater than or equal to a threshold value */\n  GreaterThanOrEqual: numberConditions.register('Number.GreaterThanOrEqual', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, threshold: number) => value >= threshold,\n  }),\n\n  /** Checks if a number is less than a threshold value */\n  LessThan: numberConditions.register('Number.LessThan', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, threshold: number) => value < threshold,\n  }),\n\n  /** Checks if a number is less than or equal to a threshold value */\n  LessThanOrEqual: numberConditions.register('Number.LessThanOrEqual', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, threshold: number) => value <= threshold,\n  }),\n\n  /** Checks if a number is between two values (inclusive) */\n  Between: numberConditions.register('Number.Between', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberRangeArgsSchema,\n    factory: () => (value: number, min: number, max: number) => value >= min && value <= max,\n  }),\n}\n\nexport { numberConditions as numberConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst phoneConditions = new ConditionRegistry()\n\nexport const PhoneConditions = {\n  /** Validates if a string is a valid phone number format (7-20 digits) */\n  IsValidPhoneNumber: phoneConditions.register('Phone.IsValidPhoneNumber', {\n    inputSchema: z.string(),\n    factory: () => (value: string) => /^\\+?[0-9\\s().-]{7,20}$/.test(value),\n  }),\n\n  /** Validates if a string is a valid UK mobile phone number */\n  IsValidUKMobile: phoneConditions.register('Phone.IsValidUKMobile', {\n    inputSchema: z.string(),\n    factory: () => (value: string) => /^(\\+44\\s?7\\d{3}|\\(?07\\d{3}\\)?)\\s?\\d{3}\\s?\\d{3}$/.test(value),\n  }),\n}\n\nexport { phoneConditions as phoneConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\nconst arraySchema = z.array(z.unknown())\nconst arrayArgsSchema = z.tuple([z.array(z.unknown())])\n\nconst arrayConditions = new ConditionRegistry()\n\nexport const ArrayConditions = {\n  /** Checks if a value is an array */\n  IsArray: arrayConditions.register('Array.IsArray', { factory: () => (value: unknown) => Array.isArray(value) }),\n\n  /** Checks if a value exists within an array of options */\n  IsIn: arrayConditions.register('Array.IsIn', {\n    argumentsSchema: arrayArgsSchema,\n    factory: () => (value: unknown, expected: unknown[]) => expected.some(item => item === value),\n  }),\n\n  /** Checks if an array contains a specific value */\n  Contains: arrayConditions.register('Array.Contains', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[], expected: unknown) => value.includes(expected),\n  }),\n\n  /** Checks if an array contains any of the items from another array */\n  ContainsAny: arrayConditions.register('Array.ContainsAny', {\n    inputSchema: arraySchema,\n    argumentsSchema: arrayArgsSchema,\n    factory: () => (value: unknown[], expected: unknown[]) => {\n      if (value.length === 0 && expected.length === 0) {\n        return true\n      }\n\n      return expected.some(item => value.includes(item))\n    },\n  }),\n\n  /** Checks if all items in the value array exist in the expected array */\n  ContainsAll: arrayConditions.register('Array.ContainsAll', {\n    inputSchema: arraySchema,\n    argumentsSchema: arrayArgsSchema,\n    factory: () => (value: unknown[], expected: unknown[]) => {\n      if (value.length === 0 && expected.length === 0) {\n        return true\n      }\n\n      return value.every(item => expected.includes(item))\n    },\n  }),\n}\n\nexport { arrayConditions as arrayConditionsRegistry }\n","import { z } from 'zod'\nimport ConditionRegistry from '../../../authoring/registries/ConditionRegistry'\n\n/** Gets a value from an object using a dot-notation path (e.g. 'user.profile.name') */\nfunction getByPath(obj: unknown, path: string): unknown {\n  if (obj == null) {\n    return undefined\n  }\n\n  if (path === '') {\n    return obj\n  }\n\n  return path.split('.').reduce<unknown>((current, key) => {\n    if (current == null || typeof current !== 'object') {\n      return undefined\n    }\n\n    return (current as Record<string, unknown>)[key]\n  }, obj)\n}\n\nconst isEmpty = (value: unknown): boolean =>\n  value === null || value === undefined || (typeof value === 'string' && value.trim() === '')\n\nconst objectSchema = z.custom<Record<string, unknown>>(v => v !== null && typeof v === 'object' && !Array.isArray(v))\nconst stringArgsSchema = z.tuple([z.string()])\n\nconst objectConditions = new ConditionRegistry()\n\nexport const ObjectConditions = {\n  /** Checks if a value is a plain object (not null, not array) */\n  IsObject: objectConditions.register('Object.IsObject', {\n    factory: () => (value: unknown) => value !== null && typeof value === 'object' && !Array.isArray(value),\n  }),\n\n  /** Checks if an object has a property at the given path */\n  HasProperty: objectConditions.register('Object.HasProperty', {\n    inputSchema: objectSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: unknown, path: string) => getByPath(value, path) !== undefined,\n  }),\n\n  /** Checks if an object property at the given path is empty */\n  PropertyIsEmpty: objectConditions.register('Object.PropertyIsEmpty', {\n    inputSchema: objectSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: unknown, path: string) => isEmpty(getByPath(value, path)),\n  }),\n\n  /** Checks if an object property at the given path has a value (not empty) */\n  PropertyHasValue: objectConditions.register('Object.PropertyHasValue', {\n    inputSchema: objectSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: unknown, path: string) => !isEmpty(getByPath(value, path)),\n  }),\n}\n\nexport { objectConditions as objectConditionsRegistry }\n","import { GeneralConditions, generalConditionsRegistry } from './generalConditions'\nimport { StringConditions, stringConditionsRegistry } from './stringConditions'\nimport { AddressConditions, addressConditionsRegistry } from './addressConditions'\nimport { EmailConditions, emailConditionsRegistry } from './emailConditions'\nimport { DateConditions, dateConditionsRegistry } from './dateConditions'\nimport { NumberConditions, numberConditionsRegistry } from './numberConditions'\nimport { PhoneConditions, phoneConditionsRegistry } from './phoneConditions'\nimport { ArrayConditions, arrayConditionsRegistry } from './arrayConditions'\nimport { ObjectConditions, objectConditionsRegistry } from './objectConditions'\n\n// TypeScript declaration emit drops JSDoc when it structurally expands a type\n// imported from another file, so the built .d.ts would lose every per-function\n// doc comment. Annotating with `typeof` references makes the emitter print a\n// reference instead of expanding, keeping the docs on each group's own declaration.\ninterface ConditionGroups {\n  /** Conditions for handling strings */\n  String: typeof StringConditions\n\n  /** Conditions for handling emails */\n  Email: typeof EmailConditions\n\n  /** Conditions for handling phone/mobile numbers */\n  Phone: typeof PhoneConditions\n\n  /** Conditions for handling addresses */\n  Address: typeof AddressConditions\n\n  /** Conditions for handling dates */\n  Date: typeof DateConditions\n\n  /** Conditions for handling numbers */\n  Number: typeof NumberConditions\n\n  /** Conditions for handling arrays */\n  Array: typeof ArrayConditions\n\n  /** Conditions for handling objects */\n  Object: typeof ObjectConditions\n}\n\nexport const Condition: typeof GeneralConditions & ConditionGroups = {\n  ...GeneralConditions,\n\n  /** Conditions for handling strings */\n  String: StringConditions,\n\n  /** Conditions for handling emails */\n  Email: EmailConditions,\n\n  /** Conditions for handling phone/mobile numbers */\n  Phone: PhoneConditions,\n\n  /** Conditions for handling addresses */\n  Address: AddressConditions,\n\n  /** Conditions for handling dates */\n  Date: DateConditions,\n\n  /** Conditions for handling numbers */\n  Number: NumberConditions,\n\n  /** Conditions for handling arrays */\n  Array: ArrayConditions,\n\n  /** Conditions for handling objects */\n  Object: ObjectConditions,\n}\n\nexport const ConditionsRegistry = {\n  ...generalConditionsRegistry.build(),\n  ...stringConditionsRegistry.build(),\n  ...emailConditionsRegistry.build(),\n  ...phoneConditionsRegistry.build(),\n  ...addressConditionsRegistry.build(),\n  ...dateConditionsRegistry.build(),\n  ...numberConditionsRegistry.build(),\n  ...arrayConditionsRegistry.build(),\n  ...objectConditionsRegistry.build(),\n}\n","import type { Resolvable } from '../types/expressions.type'\nimport type { ChainableGenerator } from '../builders/types'\nimport { FunctionType } from '../types/enums'\nimport { BaseFunctionRegistry, type RegistrationOptions } from './BaseFunctionRegistry'\n\nexport default class GeneratorRegistry<TDeps = Record<string, never>> extends BaseFunctionRegistry<TDeps> {\n  constructor() {\n    super(FunctionType.GENERATOR)\n  }\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions & { factory: (deps: TDeps) => (...args: TArgs) => any },\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ChainableGenerator\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ChainableGenerator\n\n  register<TArgs extends any[]>(\n    name: string,\n    factory: (deps: TDeps) => (...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ChainableGenerator\n\n  register<TArgs extends any[]>(\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ChainableGenerator\n\n  register<TArgs extends any[]>(\n    factory: (deps: TDeps) => (...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => ChainableGenerator\n\n  register(\n    first: string | RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    second?: RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    third?: (deps: TDeps) => (...args: any[]) => any,\n  ): (...args: any[]) => ChainableGenerator {\n    const { name, options, factory } = this.parseArgs(first, second, third)\n\n    this.store(name, options, factory)\n\n    return this.buildExpressionHandle(name, options.prepare) as any\n  }\n}\n","import { z } from 'zod'\nimport GeneratorRegistry from '../../../authoring/registries/GeneratorRegistry'\n\nconst noArgsSchema = z.tuple([])\n\nconst dateGenerators = new GeneratorRegistry()\n\nexport const DateGenerators = {\n  /** Generates the current date and time */\n  Now: dateGenerators.register('Date.Now', {\n    argumentsSchema: noArgsSchema,\n    factory: () => () => new Date(),\n  }),\n\n  /** Generates today's date at midnight */\n  Today: dateGenerators.register('Date.Today', {\n    argumentsSchema: noArgsSchema,\n    factory: () => () => {\n      const now = new Date()\n\n      return new Date(now.getFullYear(), now.getMonth(), now.getDate())\n    },\n  }),\n}\n\nexport { dateGenerators as dateGeneratorsRegistry }\n","import { z } from 'zod'\nimport GeneratorRegistry from '../../../authoring/registries/GeneratorRegistry'\n\nexport const FORMAT_STRING_GENERATOR_NAME = 'FormatString'\n\nconst formatGenerators = new GeneratorRegistry()\n\nexport const FormatGenerators = {\n  /** Generates a string from a template with %1-style positional placeholders */\n  FormatString: formatGenerators.register(FORMAT_STRING_GENERATOR_NAME, {\n    argumentsSchema: z.tuple([z.string()], z.unknown()),\n    factory:\n      () =>\n      (template: string, ...replacements: unknown[]) =>\n        formatString(template, replacements),\n  }),\n}\n\nexport { formatGenerators as formatGeneratorsRegistry }\n\nfunction formatString(template: string, replacements: readonly unknown[]): string {\n  return template.replace(/%([1-9]\\d*)(?!\\d)/g, (placeholder, indexValue) =>\n    replaceFormatPlaceholder(placeholder, indexValue, replacements),\n  )\n}\n\nfunction replaceFormatPlaceholder(placeholder: string, indexValue: string, replacements: readonly unknown[]): string {\n  const index = Number(indexValue) - 1\n\n  if (!Number.isInteger(index) || index < 0 || index >= replacements.length) {\n    return placeholder\n  }\n\n  return String(replacements[index] ?? '')\n}\n","import { DateGenerators, dateGeneratorsRegistry } from './dateGenerators'\nimport { FormatGenerators, formatGeneratorsRegistry } from './formatGenerators'\n\n// TypeScript declaration emit drops JSDoc when it structurally expands a type\n// imported from another file, so the built .d.ts would lose every per-function\n// doc comment. Annotating with `typeof` references makes the emitter print a\n// reference instead of expanding, keeping the docs on each group's own declaration.\ninterface GeneratorGroups {\n  /** Generators for producing formatted string values */\n  FormatString: typeof FormatGenerators.FormatString\n\n  /** Generators for producing date values */\n  Date: typeof DateGenerators\n}\n\nexport const Generator: GeneratorGroups = {\n  /** Generators for producing formatted string values */\n  FormatString: FormatGenerators.FormatString,\n\n  /** Generators for producing date values */\n  Date: DateGenerators,\n}\n\nexport const GeneratorsRegistry = {\n  ...formatGeneratorsRegistry.build(),\n  ...dateGeneratorsRegistry.build(),\n}\n","import type { Resolvable, TransformerFunctionExpr } from '../types/expressions.type'\nimport { FunctionType } from '../types/enums'\nimport { BaseFunctionRegistry, type RegistrationOptions } from './BaseFunctionRegistry'\n\nexport default class TransformerRegistry<TDeps = Record<string, never>> extends BaseFunctionRegistry<TDeps> {\n  constructor() {\n    super(FunctionType.TRANSFORMER)\n  }\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions & { factory: (deps: TDeps) => (value: any, ...args: TArgs) => any },\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => TransformerFunctionExpr\n\n  register<TArgs extends any[]>(\n    name: string,\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => TransformerFunctionExpr\n\n  register<TArgs extends any[]>(\n    name: string,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => TransformerFunctionExpr\n\n  register<TArgs extends any[]>(\n    options: RegistrationOptions,\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => TransformerFunctionExpr\n\n  register<TArgs extends any[]>(\n    factory: (deps: TDeps) => (value: any, ...args: TArgs) => any,\n  ): (...args: { [K in keyof TArgs]: Resolvable<TArgs[K]> }) => TransformerFunctionExpr\n\n  register(\n    first: string | RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    second?: RegistrationOptions | ((deps: TDeps) => (...args: any[]) => any),\n    third?: (deps: TDeps) => (...args: any[]) => any,\n  ): (...args: any[]) => TransformerFunctionExpr {\n    const { name, options, factory } = this.parseArgs(first, second, third)\n\n    this.store(name, options, factory)\n\n    return this.buildExpressionHandle(name, options.prepare) as any\n  }\n}\n","import { z } from 'zod'\nimport TransformerRegistry from '../../../authoring/registries/TransformerRegistry'\n\nconst arraySchema = z.array(z.unknown())\n\nconst arrayTransformers = new TransformerRegistry()\n\nexport const ArrayTransformers = {\n  /**\n   * Returns the length of the array\n   * @example\n   * // Length() applied to [1, 2, 3, 4] returns 4\n   */\n  Length: arrayTransformers.register('Array.Length', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => value.length,\n  }),\n\n  /**\n   * Returns the first element of the array\n   * @example\n   * // First() applied to [1, 2, 3] returns 1\n   */\n  First: arrayTransformers.register('Array.First', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => (value.length > 0 ? value[0] : undefined),\n  }),\n\n  /**\n   * Returns the last element of the array\n   * @example\n   * // Last() applied to [1, 2, 3] returns 3\n   */\n  Last: arrayTransformers.register('Array.Last', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => (value.length > 0 ? value[value.length - 1] : undefined),\n  }),\n\n  /**\n   * Reverses the array (returns a new array)\n   * @example\n   * // Reverse() applied to [1, 2, 3] returns [3, 2, 1]\n   */\n  Reverse: arrayTransformers.register('Array.Reverse', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => [...value].reverse(),\n  }),\n\n  /**\n   * Joins array elements into a string with specified separator\n   * @param separator - Separator to place between elements (defaults to ',')\n   * @example\n   * // Join(\", \") applied to [1, 2, 3] returns \"1, 2, 3\"\n   */\n  Join: arrayTransformers.register('Array.Join', {\n    inputSchema: arraySchema,\n    argumentsSchema: z.tuple([z.string().optional()]),\n    factory:\n      () =>\n      (value: unknown[], separator: string = ',') =>\n        value.join(separator),\n  }),\n\n  /**\n   * Returns a slice of the array from start to end index\n   * @param start - The zero-based index at which to begin extraction\n   * @param end - The zero-based index before which to end extraction (optional)\n   * @example\n   * // Slice(1, 4) applied to [1, 2, 3, 4, 5] returns [2, 3, 4]\n   */\n  Slice: arrayTransformers.register('Array.Slice', {\n    inputSchema: arraySchema,\n    argumentsSchema: z.tuple([z.number(), z.number().optional()]),\n    factory: () => (value: unknown[], start: number, end?: number) => value.slice(start, end),\n  }),\n\n  /**\n   * Concatenates arrays together\n   * @param arrays - Additional arrays to concatenate to the input\n   * @example\n   * // Concat([3, 4]) applied to [1, 2] returns [1, 2, 3, 4]\n   */\n  Concat: arrayTransformers.register('Array.Concat', {\n    inputSchema: arraySchema,\n    argumentsSchema: z.tuple([z.array(z.unknown())], z.array(z.unknown())),\n    factory:\n      () =>\n      (value: unknown[], ...arrays: unknown[][]) =>\n        value.concat(...arrays),\n  }),\n\n  /**\n   * Returns unique elements from the array (removes duplicates)\n   * @example\n   * // Unique() applied to [1, 2, 2, 3, 1] returns [1, 2, 3]\n   */\n  Unique: arrayTransformers.register('Array.Unique', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => [...new Set(value)],\n  }),\n\n  /**\n   * Sorts the array in ascending order (returns a new array)\n   * @example\n   * // Sort() applied to [3, 1, 4, 2] returns [1, 2, 3, 4]\n   */\n  Sort: arrayTransformers.register('Array.Sort', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) =>\n      [...value].sort((a, b) => {\n        if (typeof a === 'number' && typeof b === 'number') {\n          return a - b\n        }\n\n        return String(a).localeCompare(String(b))\n      }),\n  }),\n\n  /**\n   * Filters the array to only include elements that match the specified value\n   * @param filterValue - The value each element is compared against\n   * @example\n   * // Filter(2) applied to [1, 2, 2, 3] returns [2, 2]\n   */\n  Filter: arrayTransformers.register('Array.Filter', {\n    inputSchema: arraySchema,\n    argumentsSchema: z.tuple([z.unknown()]),\n    factory: () => (value: unknown[], filterValue: unknown) => value.filter(item => item === filterValue),\n  }),\n\n  /**\n   * Maps each array element by extracting a property (for objects) or applying an index (for arrays)\n   * @param property - The property name (for objects) or index (for nested arrays) to extract\n   * @example\n   * // Map('name') applied to [{name: 'John'}, {name: 'Jane'}] returns ['John', 'Jane']\n   * // Map(0) applied to [[1, 2], [3, 4]] returns [1, 3]\n   */\n  Map: arrayTransformers.register('Array.Map', {\n    inputSchema: arraySchema,\n    argumentsSchema: z.tuple([z.union([z.string(), z.number()])]),\n    factory: () => (value: unknown[], property: string | number) =>\n      value.map(item => {\n        if (typeof property === 'number' && Array.isArray(item)) {\n          return item[property]\n        }\n\n        if (typeof property === 'string' && typeof item === 'object' && item !== null) {\n          return (item as Record<string, unknown>)[property]\n        }\n\n        return undefined\n      }),\n  }),\n\n  /**\n   * Flattens a nested array by one level\n   * @example\n   * // Flatten() applied to [[1, 2], [3, 4]] returns [1, 2, 3, 4]\n   */\n  Flatten: arrayTransformers.register('Array.Flatten', {\n    inputSchema: arraySchema,\n    factory: () => (value: unknown[]) => value.flat(),\n  }),\n}\n\nexport { arrayTransformers as arrayTransformersRegistry }\n","import { z } from 'zod'\nimport TransformerRegistry from '../../../authoring/registries/TransformerRegistry'\n\nconst formatDate = (date: Date, format: string): string => {\n  const monthNames = [\n    'January',\n    'February',\n    'March',\n    'April',\n    'May',\n    'June',\n    'July',\n    'August',\n    'September',\n    'October',\n    'November',\n    'December',\n  ]\n\n  const getOrdinal = (n: number): string => {\n    const remainder10 = n % 10\n    const remainder100 = n % 100\n\n    if (remainder100 >= 11 && remainder100 <= 13) return `${n}th`\n    if (remainder10 === 1) return `${n}st`\n    if (remainder10 === 2) return `${n}nd`\n    if (remainder10 === 3) return `${n}rd`\n    return `${n}th`\n  }\n\n  const tokens: Record<string, () => string> = {\n    YYYY: () => String(date.getFullYear()),\n    YY: () => String(date.getFullYear()).slice(-2),\n    MMMM: () => monthNames[date.getMonth()],\n    MM: () => String(date.getMonth() + 1).padStart(2, '0'),\n    M: () => String(date.getMonth() + 1),\n    DD: () => String(date.getDate()).padStart(2, '0'),\n    Do: () => getOrdinal(date.getDate()),\n    D: () => String(date.getDate()),\n    HH: () => String(date.getHours()).padStart(2, '0'),\n    H: () => String(date.getHours()),\n    mm: () => String(date.getMinutes()).padStart(2, '0'),\n    m: () => String(date.getMinutes()),\n    ss: () => String(date.getSeconds()).padStart(2, '0'),\n    s: () => String(date.getSeconds()),\n  }\n\n  // Sort by length descending so longer tokens match first (YYYY before YY)\n  const tokenPattern = Object.keys(tokens)\n    .sort((a, b) => b.length - a.length)\n    .join('|')\n\n  return format.replace(new RegExp(tokenPattern, 'g'), match => tokens[match]())\n}\n\nconst dateSchema = z.date()\nconst stringArgsSchema = z.tuple([z.string()])\nconst numberArgsSchema = z.tuple([z.number()])\nconst optionalStringArgsSchema = z.tuple([z.string().optional()])\n\nconst dateTransformers = new TransformerRegistry()\n\nexport const DateTransformers = {\n  /**\n   * Formats a Date object into a string using the specified format\n   *\n   * Supported tokens:\n   * - YYYY: 4-digit year (2024)\n   * - YY: 2-digit year (24)\n   * - MMMM: Full month name (January, February, March, etc.)\n   * - MM: 2-digit month (01-12)\n   * - M: Month (1-12)\n   * - DD: 2-digit day (01-31)\n   * - Do: Day of month (1st, 2nd, 3rd, etc.)\n   * - D: Day (1-31)\n   * - HH: 2-digit hours (00-23)\n   * - H: Hours (0-23)\n   * - mm: 2-digit minutes (00-59)\n   * - m: Minutes (0-59)\n   * - ss: 2-digit seconds (00-59)\n   * - s: Seconds (0-59)\n   *\n   * @param format - Format string using the supported tokens\n   * @example\n   * // Format(\"DD/MM/YYYY\") returns \"15/03/2024\"\n   * // Format(\"YYYY-MM-DD\") returns \"2024-03-15\"\n   * // Format(\"D M YYYY\") returns \"15 3 2024\"\n   * // Format(\"HH:mm:ss\") returns \"14:30:45\"\n   */\n  Format: dateTransformers.register('Date.Format', {\n    inputSchema: dateSchema,\n    argumentsSchema: stringArgsSchema,\n    factory: () => (value: Date, format: string) => formatDate(value, format),\n  }),\n\n  /**\n   * Adds a number of days to a Date\n   * @param days - Number of days to add (negative values subtract)\n   * @example\n   * // AddDays(7) adds one week\n   * // AddDays(-1) subtracts one day\n   */\n  AddDays: dateTransformers.register('Date.AddDays', {\n    inputSchema: dateSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: Date, days: number) => {\n      const result = new Date(value)\n      result.setDate(result.getDate() + days)\n\n      return result\n    },\n  }),\n\n  /**\n   * Subtracts a number of days from a Date\n   * @param days - Number of days to subtract\n   * @example\n   * // SubtractDays(7) subtracts one week\n   */\n  SubtractDays: dateTransformers.register('Date.SubtractDays', {\n    inputSchema: dateSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: Date, days: number) => {\n      const result = new Date(value)\n      result.setDate(result.getDate() - days)\n\n      return result\n    },\n  }),\n\n  /**\n   * Adds a number of months to a Date\n   * @param months - Number of months to add (negative values subtract)\n   * @example\n   * // AddMonths(1) adds one month\n   * // AddMonths(-6) subtracts 6 months\n   */\n  AddMonths: dateTransformers.register('Date.AddMonths', {\n    inputSchema: dateSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: Date, months: number) => {\n      const result = new Date(value)\n      result.setMonth(result.getMonth() + months)\n\n      return result\n    },\n  }),\n\n  /**\n   * Adds a number of years to a Date\n   * @param years - Number of years to add (negative values subtract)\n   * @example\n   * // AddYears(1) adds one year\n   * // AddYears(-18) subtracts 18 years\n   */\n  AddYears: dateTransformers.register('Date.AddYears', {\n    inputSchema: dateSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: Date, years: number) => {\n      const result = new Date(value)\n      result.setFullYear(result.getFullYear() + years)\n\n      return result\n    },\n  }),\n\n  /**\n   * Returns the start of the day (midnight) for a Date\n   * @example\n   * // StartOfDay() returns 2024-03-15T00:00:00.000\n   */\n  StartOfDay: dateTransformers.register('Date.StartOfDay', {\n    inputSchema: dateSchema,\n    factory: () => (value: Date) => {\n      const result = new Date(value)\n      result.setHours(0, 0, 0, 0)\n\n      return result\n    },\n  }),\n\n  /**\n   * Returns the end of the day (23:59:59.999) for a Date\n   * @example\n   * // EndOfDay() returns 2024-03-15T23:59:59.999\n   */\n  EndOfDay: dateTransformers.register('Date.EndOfDay', {\n    inputSchema: dateSchema,\n    factory: () => (value: Date) => {\n      const result = new Date(value)\n      result.setHours(23, 59, 59, 999)\n\n      return result\n    },\n  }),\n\n  /**\n   * Converts a Date to ISO-8601 string format\n   * @example\n   * // ToISOString() returns \"2024-03-15T14:30:45.123Z\"\n   */\n  ToISOString: dateTransformers.register('Date.ToISOString', {\n    inputSchema: dateSchema,\n    factory: () => (value: Date) => value.toISOString(),\n  }),\n\n  /**\n   * Converts a Date to a locale-specific string\n   * @param locale - Optional locale identifier (e.g. 'en-GB', 'en-US')\n   * @example\n   * // ToLocaleString() returns \"15/03/2024, 14:30:45\" (UK locale)\n   * // ToLocaleString('en-US') returns \"3/15/2024, 2:30:45 PM\"\n   */\n  ToLocaleString: dateTransformers.register('Date.ToLocaleString', {\n    inputSchema: dateSchema,\n    argumentsSchema: optionalStringArgsSchema,\n    factory: () => (value: Date, locale?: string) => value.toLocaleString(locale),\n  }),\n\n  /**\n   * Converts a Date to UK long date format (e.g. \"18 March 2026\")\n   * @example\n   * // ToUKLongDate() returns \"18 March 2026\"\n   */\n  ToUKLongDate: dateTransformers.register('Date.ToUKLongDate', {\n    inputSchema: dateSchema,\n    factory: () => (value: Date) =>\n      value.toLocaleDateString('en-GB', {\n        day: 'numeric',\n        month: 'long',\n        year: 'numeric',\n      }),\n  }),\n}\n\nexport { dateTransformers as dateTransformersRegistry }\n","import { z } from 'zod'\nimport TransformerRegistry from '../../../authoring/registries/TransformerRegistry'\n\nconst numberSchema = z.number()\nconst numberArgsSchema = z.tuple([z.number()])\nconst numberRangeArgsSchema = z.tuple([z.number(), z.number()])\n\nconst numberTransformers = new TransformerRegistry()\n\nexport const NumberTransformers = {\n  /**\n   * Adds a number to the input value\n   * @param addend - The number to add\n   * @example\n   * // Add(3) applied to 5 returns 8\n   * // Add(Answer('tax')) applied to Answer('price') - dynamic addition\n   */\n  Add: numberTransformers.register('Number.Add', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, addend: number) => value + addend,\n  }),\n\n  /**\n   * Subtracts a number from the input value\n   * @param subtrahend - The number to subtract\n   * @example\n   * // Subtract(3) applied to 10 returns 7\n   */\n  Subtract: numberTransformers.register('Number.Subtract', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, subtrahend: number) => value - subtrahend,\n  }),\n\n  /**\n   * Multiplies the input value by a number\n   * @param multiplier - The number to multiply by\n   * @example\n   * // Multiply(3) applied to 4 returns 12\n   * // Multiply(Answer('quantity')) applied to Answer('price') - dynamic multiplication\n   */\n  Multiply: numberTransformers.register('Number.Multiply', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, multiplier: number) => value * multiplier,\n  }),\n\n  /**\n   * Divides the input value by a number\n   * @param divisor - The number to divide by\n   * @example\n   * // Divide(3) applied to 15 returns 5\n   */\n  Divide: numberTransformers.register('Number.Divide', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, divisor: number) => {\n      if (divisor === 0) {\n        throw new Error('Division by zero is not allowed in Transformer.Number.Divide')\n      }\n\n      return value / divisor\n    },\n  }),\n\n  /**\n   * Returns the absolute value of the input\n   * @example\n   * // Abs() applied to -5 returns 5\n   */\n  Abs: numberTransformers.register('Number.Abs', {\n    inputSchema: numberSchema,\n    factory: () => (value: number) => Math.abs(value),\n  }),\n\n  /**\n   * Rounds the number to the nearest integer\n   * @example\n   * // Round() applied to 4.7 returns 5\n   */\n  Round: numberTransformers.register('Number.Round', {\n    inputSchema: numberSchema,\n    factory: () => (value: number) => Math.round(value),\n  }),\n\n  /**\n   * Rounds the number down to the nearest integer\n   * @example\n   * // Floor() applied to 4.7 returns 4\n   */\n  Floor: numberTransformers.register('Number.Floor', {\n    inputSchema: numberSchema,\n    factory: () => (value: number) => Math.floor(value),\n  }),\n\n  /**\n   * Rounds the number up to the nearest integer\n   * @example\n   * // Ceil() applied to 4.2 returns 5\n   */\n  Ceil: numberTransformers.register('Number.Ceil', {\n    inputSchema: numberSchema,\n    factory: () => (value: number) => Math.ceil(value),\n  }),\n\n  /**\n   * Rounds the number to a specified number of decimal places\n   * @param decimals - The number of decimal places to round to\n   * @example\n   * // ToFixed(2) applied to 3.14159 returns 3.14\n   */\n  ToFixed: numberTransformers.register('Number.ToFixed', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, decimals: number) => parseFloat(value.toFixed(decimals)),\n  }),\n\n  /**\n   * Returns the maximum of the input value and a comparison value\n   * @param comparison - The value to compare against\n   * @example\n   * // Max(10) applied to 5 returns 10\n   */\n  Max: numberTransformers.register('Number.Max', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, comparison: number) => Math.max(value, comparison),\n  }),\n\n  /**\n   * Returns the minimum of the input value and a comparison value\n   * @param comparison - The value to compare against\n   * @example\n   * // Min(10) applied to 5 returns 5\n   */\n  Min: numberTransformers.register('Number.Min', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, comparison: number) => Math.min(value, comparison),\n  }),\n\n  /**\n   * Raises the input value to the power of the exponent\n   * @param exponent - The exponent to raise the value to\n   * @example\n   * // Power(3) applied to 2 returns 8\n   */\n  Power: numberTransformers.register('Number.Power', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberArgsSchema,\n    factory: () => (value: number, exponent: number) => value ** exponent,\n  }),\n\n  /**\n   * Returns the square root of the input value\n   * @example\n   * // Sqrt() applied to 16 returns 4\n   */\n  Sqrt: numberTransformers.register('Number.Sqrt', {\n    inputSchema: numberSchema,\n    factory: () => (value: number) => {\n      if (value < 0) {\n        throw new Error('Cannot calculate square root of negative number in Transformer.Number.Sqrt')\n      }\n\n      return Math.sqrt(value)\n    },\n  }),\n\n  /**\n   * Clamps the input value between a minimum and maximum range\n   * @param min - The minimum value (inclusive)\n   * @param max - The maximum value (inclusive)\n   * @example\n   * // Clamp(5, 10) applied to 15 returns 10\n   * // Clamp(5, 10) applied to 3 returns 5\n   * // Clamp(5, 10) applied to 7 returns 7\n   */\n  Clamp: numberTransformers.register('Number.Clamp', {\n    inputSchema: numberSchema,\n    argumentsSchema: numberRangeArgsSchema,\n    factory: () => (value: number, min: number, max: number) => Math.min(Math.max(value, min), max),\n  }),\n}\n\nexport { numberTransformers as numberTransformersRegistry }\n","import { z } from 'zod'\nimport TransformerRegistry from '../../../authoring/registries/TransformerRegistry'\n\n/** Gets a value from an object using a dot-notation path (e.g. 'user.profile.name') */\nfunction getByPath<T = unknown>(obj: unknown, path: string): T | undefined {\n  if (obj == null) {\n    return undefined\n  }\n\n  if (path === '') {\n    return obj as T\n  }\n\n  return path.split('.').reduce<unknown>((current, key) => {\n    if (current == null || typeof current !== 'object') {\n      return undefined\n    }\n\n    return (current as Record<string, unknown>)[key]\n  }, obj) as T | undefined\n}\n\nexport interface DateParts {\n  year?: string\n  month?: string\n  day?: string\n}\n\nconst objectSchema = z.looseObject({})\nconst datePartsArgsSchema = z.tuple([\n  z.object({\n    year: z.string().optional(),\n    month: z.string().optional(),\n    day: z.string().optional(),\n  }),\n])\n\nconst objectTransformers = new TransformerRegistry()\n\nexport const ObjectTransformers = {\n  /**\n   * Converts an object with date parts to an ISO 8601 date string\n   * Supports full dates (YYYY-MM-DD), partial dates (YYYY-MM, MM-DD), or single components\n   *\n   * @param paths - Object mapping date components to property paths\n   * @example\n   * // Full date: {day: \"15\", month: \"3\", year: \"2024\"} becomes \"2024-03-15\"\n   * ToISO({year: 'year', month: 'month', day: 'day'})\n   *\n   * @example\n   * // Partial date: {month: \"3\", year: \"2024\"} becomes \"2024-03\"\n   * ToISO({year: 'year', month: 'month'})\n   *\n   * @example\n   * // Nested paths: {date: {y: \"2024\", m: \"3\", d: \"15\"}} becomes \"2024-03-15\"\n   * ToISO({year: 'date.y', month: 'date.m', day: 'date.d'})\n   */\n  ToISO: objectTransformers.register('Object.ToISO', {\n    inputSchema: objectSchema,\n    argumentsSchema: datePartsArgsSchema,\n    factory: () => (value: Record<string, unknown>, paths: DateParts) => {\n      const year = paths.year ? getByPath<string>(value, paths.year) : undefined\n      const month = paths.month ? getByPath<string>(value, paths.month) : undefined\n      const day = paths.day ? getByPath<string>(value, paths.day) : undefined\n\n      // If all three paths are specified (full date expected), require all three values\n      // so field-specific validation can run when any field is empty.\n      if (paths.year && paths.month && paths.day) {\n        if (!year || !month || !day) {\n          throw new TypeError('Transformer.Object.ToISO: Full date requested but not all fields provided')\n        }\n      }\n\n      if (year && !/^\\d{1,4}$/.test(year)) {\n        throw new TypeError(`Transformer.Object.ToISO: Invalid year value \"${year}\"`)\n      }\n\n      if (month && !/^\\d{1,2}$/.test(month)) {\n        throw new TypeError(`Transformer.Object.ToISO: Invalid month value \"${month}\"`)\n      }\n\n      if (day && !/^\\d{1,2}$/.test(day)) {\n        throw new TypeError(`Transformer.Object.ToISO: Invalid day value \"${day}\"`)\n      }\n\n      if (month) {\n        const monthNum = parseInt(month, 10)\n        if (monthNum < 1 || monthNum > 12) {\n          throw new TypeError(`Transformer.Object.ToISO: Month must be between 1 and 12, got \"${month}\"`)\n        }\n      }\n\n      if (day) {\n        const dayNum = parseInt(day, 10)\n        if (dayNum < 1 || dayNum > 31) {\n          throw new TypeError(`Transformer.Object.ToISO: Day must be between 1 and 31, got \"${day}\"`)\n        }\n      }\n\n      if (year && month && day) {\n        const paddedYear = year.padStart(4, '0')\n        const paddedMonth = month.padStart(2, '0')\n        const paddedDay = day.padStart(2, '0')\n        return `${paddedYear}-${paddedMonth}-${paddedDay}`\n      }\n\n      if (year && month) {\n        const paddedYear = year.padStart(4, '0')\n        const paddedMonth = month.padStart(2, '0')\n        return `${paddedYear}-${paddedMonth}`\n      }\n\n      if (month && day) {\n        const paddedMonth = month.padStart(2, '0')\n        const paddedDay = day.padStart(2, '0')\n        return `--${paddedMonth}-${paddedDay}`\n      }\n\n      if (year) {\n        return year.padStart(4, '0')\n      }\n\n      throw new TypeError('Transformer.Object.ToISO: No valid date components found in object')\n    },\n  }),\n\n  /**\n   * Converts an ISO 8601 date string back to an object with date parts.\n   * The inverse of ToISO. Objects are passed through unchanged.\n   *\n   * @param paths - Object mapping date components to output property names\n   * @example\n   * // Full date: \"2024-03-15\" becomes {year: \"2024\", month: \"03\", day: \"15\"}\n   * FromISO({year: 'year', month: 'month', day: 'day'})\n   *\n   * @example\n   * // Year-month: \"2024-03\" becomes {year: \"2024\", month: \"03\"}\n   * FromISO({year: 'year', month: 'month'})\n   */\n  FromISO: objectTransformers.register('Object.FromISO', {\n    argumentsSchema: datePartsArgsSchema,\n    factory: () => (value: unknown, paths: DateParts) => {\n      if (typeof value === 'object' && value !== null) {\n        return value\n      }\n\n      if (typeof value !== 'string' || !value) {\n        return {}\n      }\n\n      const result: Record<string, string> = {}\n      const hasYear = Boolean(paths.year)\n      const hasMonth = Boolean(paths.month)\n      const hasDay = Boolean(paths.day)\n\n      if (hasYear && hasMonth && hasDay) {\n        const match = value.match(/^(\\d{4})-(\\d{2})-(\\d{2})$/)\n\n        if (match) {\n          result[paths.year!] = match[1]\n          result[paths.month!] = match[2]\n          result[paths.day!] = match[3]\n\n          return result\n        }\n      }\n\n      if (hasYear && hasMonth && !hasDay) {\n        const match = value.match(/^(\\d{4})-(\\d{2})$/)\n\n        if (match) {\n          result[paths.year!] = match[1]\n          result[paths.month!] = match[2]\n\n          return result\n        }\n      }\n\n      if (hasMonth && hasDay && !hasYear) {\n        const match = value.match(/^(?:--)?(\\d{2})-(\\d{2})$/)\n\n        if (match) {\n          result[paths.month!] = match[1]\n          result[paths.day!] = match[2]\n\n          return result\n        }\n      }\n\n      if (hasYear && !hasMonth && !hasDay) {\n        const match = value.match(/^(\\d{4})$/)\n\n        if (match) {\n          result[paths.year!] = match[1]\n\n          return result\n        }\n      }\n\n      return {}\n    },\n  }),\n}\n\nexport { objectTransformers as objectTransformersRegistry }\n","/**\n * HTML entity encoding map for XSS prevention\n */\nconst HTML_ENTITY_MAP: Record<string, string> = {\n  '<': '&lt;',\n  '>': '&gt;',\n  '&': '&amp;',\n  '\"': '&quot;',\n  \"'\": '&#39;',\n}\n\n/**\n * Escape HTML entities in a string value to prevent XSS attacks.\n *\n * Converts dangerous characters to their HTML entity equivalents:\n * - < becomes &lt;\n * - > becomes &gt;\n * - & becomes &amp;\n * - \" becomes &quot;\n * - ' becomes &#39;\n *\n * @param value - The string value to sanitize\n * @returns The sanitized string with HTML entities escaped\n */\nexport function escapeHtmlEntities(value: string): string {\n  return value.replace(/[<>&\"']/g, char => HTML_ENTITY_MAP[char])\n}\n","import { z } from 'zod'\nimport TransformerRegistry from '../../../authoring/registries/TransformerRegistry'\nimport { escapeHtmlEntities } from '../../sanitize'\n\nconst DEFAULT_FORMAT_DATE_LOCALE = 'en-GB'\nconst DEFAULT_FORMAT_DATE_TIME_ZONE = 'Europe/London'\nconst DEFAULT_FORMAT_DATE_OPTIONS: StringDateFormatOptions = {\n  dateStyle: 'long',\n}\n\ntype StringDateFormatOptions = Readonly<\n  Intl.DateTimeFormatOptions & {\n    locale?: string\n  }\n>\n\nconst parseDateString = (value: string, functionName: string): Date => {\n  const UK_DATE_RE = /^(\\d{1,2})[/-](\\d{1,2})[/-](\\d{4})$/\n  const ISO_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})(?:$|T)/\n  const trimmed = value.trim()\n\n  if (!trimmed) {\n    throw new TypeError(`${functionName}: \"${value}\" is not a valid date`)\n  }\n\n  const ukMatch = UK_DATE_RE.exec(trimmed)\n\n  if (ukMatch) {\n    const day = Number(ukMatch[1])\n    const month = Number(ukMatch[2])\n    const year = Number(ukMatch[3])\n\n    const date = new Date(year, month - 1, day)\n\n    if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {\n      throw new TypeError(`${functionName}: \"${value}\" is not a valid date`)\n    }\n\n    return date\n  }\n\n  const isoMatch = ISO_DATE_RE.exec(trimmed)\n\n  if (isoMatch) {\n    const year = Number(isoMatch[1])\n    const month = Number(isoMatch[2])\n    const day = Number(isoMatch[3])\n    const dateOnly = new Date(Date.UTC(year, month - 1, day))\n\n    if (dateOnly.getUTCFullYear() !== year || dateOnly.getUTCMonth() !== month - 1 || dateOnly.getUTCDate() !== day) {\n      throw new TypeError(`${functionName}: \"${value}\" is not a valid date`)\n    }\n\n    if (!trimmed.includes('T')) {\n      return dateOnly\n    }\n\n    const dateTime = new Date(trimmed)\n\n    if (Number.isNaN(dateTime.getTime())) {\n      throw new TypeError(`${functionName}: \"${value}\" is not a valid ISO date`)\n    }\n\n    return dateTime\n  }\n\n  throw new TypeError(`${functionName}: \"${value}\" is not a valid date (expected DD/MM/YYYY or YYYY-MM-DD)`)\n}\n\nconst stringSchema = z.string()\nconst formatDateOptionsSchema = z.looseObject({\n  locale: z.string().optional(),\n  timeZone: z.string().optional(),\n})\n\nconst stringTransformers = new TransformerRegistry()\n\nexport const StringTransformers = {\n  /**\n   * Removes whitespace from both ends of a string\n   * @example\n   * // Transforms \"  hello world  \" to \"hello world\"\n   */\n  Trim: stringTransformers.register('String.Trim', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => value.trim(),\n  }),\n\n  /**\n   * Converts string to uppercase\n   * @example\n   * // Transforms \"Hello World\" to \"HELLO WORLD\"\n   */\n  ToUpperCase: stringTransformers.register('String.ToUpperCase', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => value.toUpperCase(),\n  }),\n\n  /**\n   * Converts string to lowercase\n   * @example\n   * // Transforms \"Hello World\" to \"hello world\"\n   */\n  ToLowerCase: stringTransformers.register('String.ToLowerCase', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => value.toLowerCase(),\n  }),\n\n  /**\n   * Capitalizes the first letter of each word\n   * @example\n   * // Transforms \"hello world\" to \"Hello World\"\n   */\n  ToTitleCase: stringTransformers.register('String.ToTitleCase', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) =>\n      value.replace(/\\w\\S*/g, (text: string) => text.charAt(0).toUpperCase() + text.slice(1).toLowerCase()),\n  }),\n\n  /**\n   * Capitalizes the first letter of the string\n   * @example\n   * // Transforms \"hello world\" to \"Hello world\"\n   */\n  Capitalize: stringTransformers.register('String.Capitalize', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      if (value.length === 0) return value\n      return value.charAt(0).toUpperCase() + value.slice(1)\n    },\n  }),\n\n  /**\n   * Converts a name to its possessive form\n   * Names ending in 's' get just an apostrophe, others get 's\n   * @example\n   * // Possessive(\"John\") returns \"John's\"\n   * // Possessive(\"James\") returns \"James'\"\n   * // Possessive(\"Chris\") returns \"Chris'\"\n   */\n  Possessive: stringTransformers.register('String.Possessive', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      if (value.length === 0) return value\n      if (value.toLowerCase().endsWith('s')) {\n        return `${value}'`\n      }\n      return `${value}'s`\n    },\n  }),\n\n  /**\n   * Extracts a substring from start to end position\n   * @param start - The zero-based index at which to begin extraction\n   * @param end - The zero-based index before which to end extraction (optional)\n   * @example\n   * // Substring(1, 4) applied to \"hello\" returns \"ell\"\n   */\n  Substring: stringTransformers.register('String.Substring', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([z.number(), z.number().optional()]),\n    factory: () => (value: string, start: number, end?: number) => value.substring(start, end),\n  }),\n\n  /**\n   * Replaces all occurrences of a search string with a replacement string\n   * @param searchValue - The string to search for\n   * @param replaceValue - The string to replace matches with\n   * @example\n   * // Replace(\"world\", \"universe\") applied to \"hello world\" returns \"hello universe\"\n   */\n  Replace: stringTransformers.register('String.Replace', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([z.string(), z.string()]),\n    factory: () => (value: string, searchValue: string, replaceValue: string) =>\n      value.replaceAll(searchValue, replaceValue),\n  }),\n\n  /**\n   * Pads the string to a specified length with a given string on the left\n   * @param targetLength - The length the string should be padded to\n   * @param padString - The string to pad with (defaults to a single space)\n   * @example\n   * // PadStart(3) applied to \"5\" returns \"  5\"\n   */\n  PadStart: stringTransformers.register('String.PadStart', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([z.number(), z.string().optional()]),\n    factory:\n      () =>\n      (value: string, targetLength: number, padString: string = ' ') =>\n        value.padStart(targetLength, padString),\n  }),\n\n  /**\n   * Pads the string to a specified length with a given string on the right\n   * @param targetLength - The length the string should be padded to\n   * @param padString - The string to pad with (defaults to a single space)\n   * @example\n   * // PadEnd(3) applied to \"5\" returns \"5  \"\n   */\n  PadEnd: stringTransformers.register('String.PadEnd', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([z.number(), z.string().optional()]),\n    factory:\n      () =>\n      (value: string, targetLength: number, padString: string = ' ') =>\n        value.padEnd(targetLength, padString),\n  }),\n\n  // TODO: I wonder if the below transformers should instead be broken off into a `Type` transformer group, like\n  //  `Transformers.Type.ToInt()` - it might be a bit more clear.\n  /**\n   * Converts a string to an integer\n   * Throws on invalid input so the pipeline errors and the original value is preserved.\n   * @example\n   * // ToInt() on \"123\" returns 123\n   * // ToInt() on \"123.45\" returns 123 (truncated)\n   * // ToInt() on \"  123  \" returns 123\n   * // ToInt() on \"\" throws Error\n   * // ToInt() on \"abc\" throws Error\n   * // ToInt() on \"123abc\" throws Error (partial parse rejected)\n   */\n  ToInt: stringTransformers.register('String.ToInt', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const trimmed = value.trim()\n      const parsed = Number(trimmed)\n\n      if (trimmed === '' || Number.isNaN(parsed) || !Number.isFinite(parsed)) {\n        throw new TypeError(`Transformer.String.ToInt: \"${value}\" is not a valid number`)\n      }\n\n      return Math.trunc(parsed)\n    },\n  }),\n\n  /**\n   * Converts a string to a floating-point number\n   * Throws on invalid input so the pipeline errors and the original value is preserved.\n   * @example\n   * // ToFloat() on \"123.45\" returns 123.45\n   * // ToFloat() on \"3.14159\" returns 3.14159\n   * // ToFloat() on \"  123.45  \" returns 123.45\n   * // ToFloat() on \"\" throws Error\n   * // ToFloat() on \"abc\" throws Error\n   * // ToFloat() on \"123abc\" throws Error (partial parse rejected)\n   */\n  ToFloat: stringTransformers.register('String.ToFloat', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const trimmed = value.trim()\n      const parsed = Number(trimmed)\n\n      if (trimmed === '' || Number.isNaN(parsed) || !Number.isFinite(parsed)) {\n        throw new TypeError(`Transformer.String.ToFloat: \"${value}\" is not a valid number`)\n      }\n\n      return parsed\n    },\n  }),\n\n  /**\n   * Splits a string into an array of characters or by a separator\n   * @param separator - Optional separator string; if omitted, splits into individual characters\n   * @example\n   * // ToArray() on \"hello\" returns [\"h\", \"e\", \"l\", \"l\", \"o\"]\n   * // ToArray(\",\") on \"hello,world\" returns [\"hello\", \"world\"]\n   * // ToArray(\"-\") on \"a-b-c\" returns [\"a\", \"b\", \"c\"]\n   */\n  ToArray: stringTransformers.register('String.ToArray', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([z.string().optional()]),\n    factory: () => (value: string, separator?: string) => {\n      if (separator === undefined) {\n        return value.split('')\n      }\n\n      return value.split(separator)\n    },\n  }),\n\n  // TODO: This probably needs to support supplying/choosing a format.\n  /**\n   * Converts a date string to a Date object (local time).\n   * Supports both UK format (DD/MM/YYYY) and ISO-8601 format (YYYY-MM-DD or full ISO with time/timezone).\n   * Throws on invalid input so the pipeline errors and the original value is preserved.\n   *\n   * @example\n   * // ToDate() on \"15/03/2024\" returns 2024-03-15T00:00:00 local\n   * // ToDate() on \"15-03-2024\" returns 2024-03-15T00:00:00 local\n   * // ToDate() on \"2024-03-15\" returns 2024-03-15T00:00:00 local\n   * // ToDate() on \"2024-03-15T14:30:00Z\" returns a Date object with time\n   * // ToDate() on \"\" throws Error\n   */\n  ToDate: stringTransformers.register('String.ToDate', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => parseDateString(value, 'Transformer.String.ToDate'),\n  }),\n\n  /**\n   * Formats a date string using Intl.DateTimeFormat options.\n   * Defaults to UK long date formatting when no options are supplied.\n   *\n   * @param options - Intl.DateTimeFormat options plus optional locale, which defaults to en-GB\n   * @example\n   * // FormatDate() on \"2024-03-15\" returns \"15 March 2024\"\n   * // FormatDate({ dateStyle: 'short' }) on \"2024-03-15\" returns \"15/03/2024\"\n   * // FormatDate({ locale: 'en-US', dateStyle: 'long' }) on \"2024-03-15\" returns \"March 15, 2024\"\n   */\n  FormatDate: stringTransformers.register('String.FormatDate', {\n    inputSchema: stringSchema,\n    argumentsSchema: z.tuple([formatDateOptionsSchema.optional()]),\n    factory: () => (value: string, options?: StringDateFormatOptions) => {\n      const {\n        locale = DEFAULT_FORMAT_DATE_LOCALE,\n        timeZone = DEFAULT_FORMAT_DATE_TIME_ZONE,\n        ...dateTimeFormatOptions\n      } = options ?? DEFAULT_FORMAT_DATE_OPTIONS\n\n      const date = parseDateString(value, 'Transformer.String.FormatDate')\n\n      return new Intl.DateTimeFormat(locale, { ...dateTimeFormatOptions, timeZone }).format(date)\n    },\n  }),\n\n  /**\n   * Converts a UK-formatted date string (DD/MM/YYYY) to ISO-8601 format (YYYY-MM-DD).\n   * Throws on invalid input so the pipeline errors and the original value is preserved.\n   *\n   * Use this with MOJ Date Picker which outputs UK format dates.\n   * @example\n   * // ToISODate() on \"15/03/2024\" returns \"2024-03-15\"\n   * // ToISODate() on \"5/3/2024\" returns \"2024-03-05\"\n   * // ToISODate() on \"15-03-2024\" returns \"2024-03-15\"\n   * // ToISODate() on \"\" throws Error\n   * // ToISODate() on \"31/02/2024\" throws Error (invalid date)\n   */\n  ToISODate: stringTransformers.register('String.ToISODate', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      const UK_DATE_RE = /^(\\d{1,2})[/-](\\d{1,2})[/-](\\d{4})$/\n      const trimmed = value.trim()\n\n      if (!trimmed) {\n        throw new TypeError(`Transformer.String.ToISODate: \"${value}\" is not a valid date`)\n      }\n\n      const match = UK_DATE_RE.exec(trimmed)\n\n      if (!match) {\n        throw new TypeError(`Transformer.String.ToISODate: \"${value}\" is not a valid UK date (expected DD/MM/YYYY)`)\n      }\n\n      const day = Number(match[1])\n      const month = Number(match[2])\n      const year = Number(match[3])\n\n      const date = new Date(year, month - 1, day)\n\n      if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {\n        throw new TypeError(`Transformer.String.ToISODate: \"${value}\" is not a valid date`)\n      }\n\n      const paddedYear = String(year).padStart(4, '0')\n      const paddedMonth = String(month).padStart(2, '0')\n      const paddedDay = String(day).padStart(2, '0')\n\n      return `${paddedYear}-${paddedMonth}-${paddedDay}`\n    },\n  }),\n\n  /**\n   * Converts an epoch millisecond date string to a Date (local time).\n   * Throws on invalid input so the pipeline errors and the original value is preserved.\n   *\n   * @example\n   * // ToTimestampDate() on \"1771429146000\" returns 2026-02-18T15:39:06 local\n   * // ToTimestampDate() on \"\" throws Error\n   */\n  ToTimestampDate: stringTransformers.register('String.ToTimestampDate', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => {\n      if (!/^\\d+$/.test(value)) {\n        throw new TypeError(`Transformer.String.ToTimestampDate: \"${value}\" is not a timestamp`)\n      }\n\n      const epoch = Number(value)\n\n      if (!Number.isSafeInteger(epoch)) {\n        throw new TypeError(`Transformer.String.ToTimestampDate: \"${value}\" is not a valid timestamp`)\n      }\n\n      const date = new Date(epoch)\n\n      if (Number.isNaN(date.getTime())) {\n        throw new TypeError(`Transformer.String.ToTimestampDate: \"${value}\" is not a valid epoch timestamp`)\n      }\n\n      return date\n    },\n  }),\n\n  /**\n   * Escapes HTML entities in a string to prevent XSS attacks.\n   * Use this when piping untrusted data (user input, external API data) into HTML contexts.\n   *\n   * Converts: < > & \" ' to their HTML entity equivalents.\n   *\n   * @example\n   * // EscapeHtml() on '\"><img src=x onerror=alert(1)>' returns '&quot;&gt;&lt;img src=x onerror=alert(1)&gt;'\n   * // Usage: Data('goalTitle').pipe(Transformer.String.EscapeHtml())\n   */\n  EscapeHtml: stringTransformers.register('String.EscapeHtml', {\n    inputSchema: stringSchema,\n    factory: () => (value: string) => escapeHtmlEntities(value),\n  }),\n}\n\nexport { stringTransformers as stringTransformersRegistry }\n","import { ArrayTransformers, arrayTransformersRegistry } from './arrayTransformers'\nimport { DateTransformers, dateTransformersRegistry } from './dateTransformers'\nimport { NumberTransformers, numberTransformersRegistry } from './numberTransformers'\nimport { ObjectTransformers, objectTransformersRegistry } from './objectTransformers'\nimport { StringTransformers, stringTransformersRegistry } from './stringTransformers'\n\n// TypeScript declaration emit drops JSDoc when it structurally expands a type\n// imported from another file, so the built .d.ts would lose every per-function\n// doc comment. Annotating with `typeof` references makes the emitter print a\n// reference instead of expanding, keeping the docs on each group's own declaration.\ninterface TransformerGroups {\n  /** Transformers for handling strings */\n  String: typeof StringTransformers\n\n  /** Transformers for handling numbers */\n  Number: typeof NumberTransformers\n\n  /** Transformers for handling arrays */\n  Array: typeof ArrayTransformers\n\n  /** Transformers for handling objects */\n  Object: typeof ObjectTransformers\n\n  /** Transformers for handling dates */\n  Date: typeof DateTransformers\n}\n\nexport const Transformer: TransformerGroups = {\n  /** Transformers for handling strings */\n  String: StringTransformers,\n\n  /** Transformers for handling numbers */\n  Number: NumberTransformers,\n\n  /** Transformers for handling arrays */\n  Array: ArrayTransformers,\n\n  /** Transformers for handling objects */\n  Object: ObjectTransformers,\n\n  /** Transformers for handling dates */\n  Date: DateTransformers,\n}\n\nexport const TransformersRegistry = {\n  ...stringTransformersRegistry.build(),\n  ...numberTransformersRegistry.build(),\n  ...arrayTransformersRegistry.build(),\n  ...objectTransformersRegistry.build(),\n  ...dateTransformersRegistry.build(),\n}\n","import {\n  ConditionFunctionExpr,\n  FilterIteratorConfig,\n  FindIteratorConfig,\n  IteratorConfig,\n  SomeIteratorConfig,\n  EveryIteratorConfig,\n  CountIteratorConfig,\n  CollectionPredicateExpr,\n  NullishExpr,\n  IterateExpr,\n  ResolvableValue,\n  MapIteratorConfig,\n  PipelineExpr,\n  PredicateTestExpr,\n  ReferenceExpr,\n  TransformerFunctionExpr,\n} from '../types/expressions.type'\nimport { ExpressionType, IteratorType, PredicateType } from '../types/enums'\nimport { ExpressionBuilder } from './ExpressionBuilder'\nimport { IterableBuilder } from './IterableBuilder'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { splitKey } from './utils/splitKey'\n\n/**\n * Immutable builder for ReferenceExpr with path navigation support.\n *\n * Extends the base expression builder pattern with:\n * - .path(key) for nested property access\n *\n * @example\n * Data('user').path('address.city')  // path: ['data', 'user', 'address', 'city']\n * Answer('email').pipe(Transformer.String.Trim).match(Condition.IsRequired())\n *\n * @internal Exposed to authors via the ChainableRef interface.\n */\nexport class ReferenceBuilder {\n  readonly nodeKind = 'forge-builder' as const\n\n  private readonly reference: ReferenceExpr\n\n  private readonly negated: boolean\n\n  private constructor(ref: ReferenceExpr, negate: boolean) {\n    this.reference = ref\n    this.negated = negate\n  }\n\n  /**\n   * Create a builder from path segments.\n   */\n  static create(path: string[]): ReferenceBuilder {\n    return new ReferenceBuilder(\n      {\n        type: ExpressionType.REFERENCE,\n        path,\n      },\n      false,\n    )\n  }\n\n  /**\n   * Get the underlying reference expression.\n   */\n  get expr(): ReferenceExpr {\n    return this.reference\n  }\n\n  /**\n   * Build the final reference expression.\n   * Called automatically by finaliseBuilders().\n   */\n  build(): ReferenceExpr {\n    return this.reference\n  }\n\n  /**\n   * Navigate to a nested property.\n   * Supports dot notation: .path('user.address.city')\n   *\n   * @example\n   * Data('response').path('data.items')\n   * Answer('user').path('address').path('postcode')\n   */\n  path(key: string): ReferenceBuilder {\n    const newRef: ReferenceExpr = {\n      type: ExpressionType.REFERENCE,\n      path: [...this.reference.path, ...splitKey(key)],\n    }\n\n    return new ReferenceBuilder(newRef, false)\n  }\n\n  /**\n   * Transform through a pipeline of transformers.\n   * Returns an ExpressionBuilder wrapping the PipelineExpr.\n   *\n   * @example\n   * Answer('email').pipe(Transformer.String.Trim, Transformer.String.ToLowerCase)\n   */\n  pipe(...steps: TransformerFunctionExpr[]): ExpressionBuilder<PipelineExpr> {\n    return ExpressionBuilder.pipeline(this.reference, steps)\n  }\n\n  /** Uses the fallback only when the value is null or undefined, like `??`. */\n  nullish(fallback: ResolvableValue | undefined): ExpressionBuilder<NullishExpr> {\n    const expression: NullishExpr = {\n      type: ExpressionType.NULLISH,\n      input: this.reference,\n      ...(fallback !== undefined && { fallback }),\n    }\n    const builder = ExpressionBuilder.from(expression)\n\n    stampCallsite(builder, captureCallsite(this.nullish))\n\n    return builder\n  }\n\n  /**\n   * Enter per-item iteration mode with a Find iterator.\n   * Returns an ExpressionBuilder since Find returns a single item, not an array.\n   *\n   * @example\n   * Data('users').each(Iterator.Find(Item().path('id').match(Condition.Equals(Params('userId')))))\n   *   .path('name')  // Navigate into the found item\n   */\n  each(iterator: FindIteratorConfig): ExpressionBuilder<ReferenceExpr>\n\n  /** Test the collection directly as a predicate. */\n  each(iterator: SomeIteratorConfig | EveryIteratorConfig): CollectionPredicateExpr\n\n  /** Count matching items and continue with the resulting number. */\n  each(iterator: CountIteratorConfig): ExpressionBuilder<IterateExpr>\n\n  /**\n   * Enter per-item iteration mode with a Map or Filter iterator.\n   * Returns an IterableBuilder that can chain more .each() calls or exit via .pipe().\n   *\n   * @example\n   * Data('items').each(Iterator.Map({ label: Item().path('name') }))\n   * Data('items').each(Iterator.Filter(...)).each(Iterator.Map(...))\n   */\n  each(iterator: MapIteratorConfig | FilterIteratorConfig): IterableBuilder\n\n  /**\n   * Enter per-item iteration mode with an iterator.\n   */\n  each(\n    iterator: IteratorConfig,\n  ): IterableBuilder | ExpressionBuilder<ReferenceExpr> | ExpressionBuilder<IterateExpr> | CollectionPredicateExpr {\n    if (iterator.type === IteratorType.COUNT) {\n      const expression: IterateExpr = { type: ExpressionType.ITERATE, input: this.reference, iterator }\n      const builder = ExpressionBuilder.from(expression)\n\n      stampCallsite(builder, captureCallsite(this.each))\n\n      return builder\n    }\n\n    if (iterator.type === IteratorType.SOME || iterator.type === IteratorType.EVERY) {\n      const predicate: CollectionPredicateExpr = { type: ExpressionType.ITERATE, input: this.reference, iterator }\n\n      stampCallsite(predicate, captureCallsite(this.each))\n\n      return predicate\n    }\n\n    if (iterator.type === IteratorType.FIND) {\n      // Find returns a single item - wrap in a reference with empty path\n      // so .path() works naturally\n      const iterateExpr = {\n        type: ExpressionType.ITERATE as const,\n        input: this.reference,\n        iterator,\n      }\n      const referenceExpr: ReferenceExpr = {\n        type: ExpressionType.REFERENCE,\n        base: iterateExpr,\n        path: [],\n      }\n\n      return ExpressionBuilder.from(referenceExpr)\n    }\n\n    return IterableBuilder.create(this.reference, iterator)\n  }\n\n  /**\n   * Test against a condition.\n   * Terminal operation - returns a plain PredicateTestExpr.\n   *\n   * @example\n   * Answer('email').match(Condition.Email.IsValid())\n   * Self().not.match(Condition.IsRequired())\n   */\n  match(condition: ConditionFunctionExpr<any>): PredicateTestExpr {\n    const predicate: PredicateTestExpr = {\n      type: PredicateType.TEST,\n      subject: this.reference,\n      negate: this.negated,\n      condition,\n    }\n\n    stampCallsite(predicate, captureCallsite(this.match))\n\n    return predicate\n  }\n\n  /**\n   * Negate the next condition test.\n   * Returns a new builder with toggled negation.\n   *\n   * @example\n   * Self().not.match(Condition.IsRequired())  // negate: true\n   * Answer('x').not.not.match(...)  // negate: false (double negation)\n   */\n  get not(): ReferenceBuilder {\n    return new ReferenceBuilder(this.reference, !this.negated)\n  }\n}\n","import { ReferenceBuilder } from './ReferenceBuilder'\n\n/**\n * Immutable builder for creating references to iterator loop metadata.\n *\n * This mirrors Nunjucks' loop object: Item() references the current item, while\n * Loop references metadata about the current iteration.\n *\n * @internal Exposed to authors via the ChainableLoopRef interface.\n */\nexport class LoopReferenceBuilder {\n  readonly nodeKind = 'forge-builder' as const\n\n  private readonly level: number\n\n  private constructor(level: number) {\n    this.level = level\n  }\n\n  /**\n   * Create a loop reference builder at the specified nesting level.\n   * Level 0 is the current loop, level 1 is the parent loop, etc.\n   */\n  static create(level: number): LoopReferenceBuilder {\n    return new LoopReferenceBuilder(level)\n  }\n\n  /**\n   * Navigate to the parent loop in nested collections.\n   *\n   * @example\n   * Loop.Parent.Index()\n   * Loop.Parent.Parent.Index0()\n   */\n  get Parent(): LoopReferenceBuilder {\n    return new LoopReferenceBuilder(this.level + 1)\n  }\n\n  /**\n   * Get the current iteration position (1-based).\n   *\n   * @example\n   * Loop.Index()  // Returns 1, 2, 3, etc.\n   */\n  Index(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'index'])\n  }\n\n  /**\n   * Get the current iteration index (0-based).\n   *\n   * @example\n   * Loop.Index0()  // Returns 0, 1, 2, etc.\n   */\n  Index0(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'index0'])\n  }\n\n  /**\n   * Get the reverse iteration position (1-based).\n   *\n   * @example\n   * Loop.RevIndex()  // Returns length, length - 1, etc.\n   */\n  RevIndex(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'revindex'])\n  }\n\n  /**\n   * Get the reverse iteration index (0-based).\n   *\n   * @example\n   * Loop.RevIndex0()  // Returns length - 1, length - 2, etc.\n   */\n  RevIndex0(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'revindex0'])\n  }\n\n  /**\n   * Check whether the current item is the first item in the iteration.\n   *\n   * @example\n   * Loop.First()  // true for the first item\n   */\n  First(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'first'])\n  }\n\n  /**\n   * Check whether the current item is the last item in the iteration.\n   *\n   * @example\n   * Loop.Last()  // true for the last item\n   */\n  Last(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'last'])\n  }\n\n  /**\n   * Get the number of items in the iteration.\n   *\n   * @example\n   * Loop.Length()  // Returns the total item count\n   */\n  Length(): ReferenceBuilder {\n    return ReferenceBuilder.create(['@loop', this.level.toString(), 'length'])\n  }\n}\n","import { isFieldBlockDefinition } from '../../components/typeguards'\nimport { ReferenceBuilder } from './ReferenceBuilder'\nimport { ScopedReferenceBuilder } from './ScopedReferenceBuilder'\nimport { LoopReferenceBuilder } from './LoopReferenceBuilder'\nimport { ChainableLoopRef, ChainableRef, ChainableScopedRef } from './types'\nimport { splitKey } from './utils/splitKey'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { FieldBlockDefinition, ResolvableString } from '../../components/types/structures.type'\n\n/**\n * References POST body data from form submission.\n */\nexport function Post(key: string): ChainableRef {\n  const ref = ReferenceBuilder.create(['post', ...splitKey(key)])\n  stampCallsite(ref, captureCallsite(Post))\n  return ref\n}\n\n/**\n * References URL parameters (e.g., /users/:id).\n */\nexport function Params(key: string): ChainableRef {\n  const ref = ReferenceBuilder.create(['params', ...splitKey(key)])\n  stampCallsite(ref, captureCallsite(Params))\n  return ref\n}\n\n/**\n * References query string parameters (e.g., ?search=test).\n */\nexport function Query(key: string): ChainableRef {\n  const ref = ReferenceBuilder.create(['query', ...splitKey(key)])\n  stampCallsite(ref, captureCallsite(Query))\n  return ref\n}\n\n/**\n * References request metadata from the current request context.\n */\nexport const Request = {\n  Url(): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'url'])\n    stampCallsite(ref, captureCallsite(Request.Url))\n    return ref\n  },\n\n  Path(): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'path'])\n    stampCallsite(ref, captureCallsite(Request.Path))\n    return ref\n  },\n\n  Method(): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'method'])\n    stampCallsite(ref, captureCallsite(Request.Method))\n    return ref\n  },\n\n  Headers(name: string): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'headers', name])\n    stampCallsite(ref, captureCallsite(Request.Headers))\n    return ref\n  },\n\n  Cookies(name: string): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'cookies', name])\n    stampCallsite(ref, captureCallsite(Request.Cookies))\n    return ref\n  },\n\n  State(key: string): ChainableRef {\n    const ref = ReferenceBuilder.create(['request', 'state', ...splitKey(key)])\n    stampCallsite(ref, captureCallsite(Request.State))\n    return ref\n  },\n}\n\n/**\n * References data defined for the step.\n */\nexport function Data(key: string): ChainableRef {\n  const ref = ReferenceBuilder.create(['data', ...splitKey(key)])\n  stampCallsite(ref, captureCallsite(Data))\n  return ref\n}\n\n/**\n * References server-side session data from the current request context.\n */\nexport function Session(key: string): ChainableRef {\n  const ref = ReferenceBuilder.create(['session', ...splitKey(key)])\n  stampCallsite(ref, captureCallsite(Session))\n  return ref\n}\n\n/**\n * References an answer using its target field or a string code.\n *\n * @example\n * Answer('email')  // Reference by code string\n * Answer(emailField)  // Reference by field definition\n * Answer('user.address.postcode')  // Nested path\n */\nexport function Answer(target: FieldBlockDefinition | ResolvableString): ChainableRef {\n  const callsite = captureCallsite(Answer)\n\n  const create = (ref: ChainableRef): ChainableRef => {\n    stampCallsite(ref, callsite)\n    return ref\n  }\n\n  // If it's a field block definition, use its code property\n  if (isFieldBlockDefinition(target)) {\n    const { code } = target\n\n    // String code - split dot notation\n    if (typeof code === 'string') {\n      return create(ReferenceBuilder.create(['answers', ...splitKey(code)]))\n    }\n\n    // Dynamic code (expression) - pass through\n    return create(ReferenceBuilder.create(['answers', code as any]))\n  }\n\n  // String target - split dot notation\n  if (typeof target === 'string') {\n    return create(ReferenceBuilder.create(['answers', ...splitKey(target)]))\n  }\n\n  // Otherwise, use the target directly (expression types like Format)\n  return create(ReferenceBuilder.create(['answers', target as any]))\n}\n\n/**\n * References the current collection item when inside a collection scope.\n *\n * @example\n * Item().path('name')  // Access item.name\n * Item().value()  // Access the whole item\n * Item().parent.path('groupId')  // Access parent item's property\n */\nexport function Item(): ChainableScopedRef {\n  const ref = ScopedReferenceBuilder.create(0)\n  stampCallsite(ref, captureCallsite(Item))\n  return ref\n}\n\nconst createLoop = (): ChainableLoopRef => {\n  return LoopReferenceBuilder.create(0)\n}\n\n/**\n * References metadata for the current collection loop.\n *\n * @example\n * Loop.Index()  // 1-based iteration position\n * Loop.Index0()  // 0-based iteration index\n * Loop.Parent.Index()  // Parent loop position in nested iterations\n */\nexport const Loop: ChainableLoopRef = createLoop()\n\n/**\n * References the block/field it's in scope of.\n *\n * @example\n * Self().match(Condition.IsRequired())\n * Self().not.match(Condition.String.IsEmpty())\n * Self().pipe(Transformer.String.Trim).match(Condition.IsRequired())\n */\nexport function Self(): ChainableRef {\n  const ref = ReferenceBuilder.create(['answers', '@self'])\n  stampCallsite(ref, captureCallsite(Self))\n  return ref\n}\n","import ForgeAuthoringError from '../../../engine/errors/ForgeAuthoringError'\nimport DSLSourceLocator from '../../../shared/diagnostics/DSLSourceLocator'\nimport type { DSLPathSegment } from '../../../shared/diagnostics/sourceLocation.type'\nimport { stampCallsite } from './captureCallsite'\n\nconst carryCallsite = (from: object, to: unknown): void => {\n  const callsite = Object.getOwnPropertyDescriptor(from, '__callsite')?.value\n\n  if (callsite) {\n    stampCallsite(to, callsite)\n  }\n}\n\ninterface Buildable {\n  build(): unknown\n}\n\nconst isBuildable = (value: unknown): value is Buildable => {\n  return value !== null &&\n    typeof value === 'object' &&\n    (value as any).nodeKind === 'forge-builder' &&\n    'build' in value &&\n    typeof (value as any).build === 'function'\n}\n\nconst describePath = (path: readonly DSLPathSegment[]): string => (path.length === 0 ? '<root>' : path.join('.'))\n\nconst finalise = (value: unknown, path: DSLPathSegment[], ancestors: Set<object>): unknown => {\n  if (value === null || typeof value !== 'object') {\n    return value\n  }\n\n  if (ancestors.has(value)) {\n    throw new ForgeAuthoringError({\n      message:\n        `Circular reference detected in form configuration at \"${describePath(path)}\". ` +\n        'Configuration objects must form a tree; an object cannot contain itself.',\n    })\n  }\n\n  ancestors.add(value)\n  try {\n    if (Array.isArray(value)) {\n      return value.map((item, index) => finalise(item, [...path, index], ancestors))\n    }\n\n    if (isBuildable(value)) {\n      // Recurse into the built output at the same path so shared builder\n      // instances produce a fresh copy per tree position.\n      const built = value.build()\n      carryCallsite(value, built)\n      return finalise(built, path, ancestors)\n    }\n\n    const prototype = Object.getPrototypeOf(value)\n\n    if (prototype !== Object.prototype && prototype !== null) {\n      return value\n    }\n\n    const result: Record<string, unknown> = {}\n    Object.entries(value).forEach(([key, entry]) => {\n      result[key] = finalise(entry, [...path, key], ancestors)\n    })\n    carryCallsite(value, result)\n    return result\n  } finally {\n    ancestors.delete(value)\n  }\n}\n\nconst stampSource = (node: unknown, path: DSLPathSegment[], locator: DSLSourceLocator): void => {\n  if (node === null || typeof node !== 'object') {\n    return\n  }\n\n  if (Array.isArray(node)) {\n    node.forEach((item, index) => stampSource(item, [...path, index], locator))\n    return\n  }\n\n  // configurable + writable so an outer finaliseBuilders() walk can re-stamp\n  // nodes that were already stamped by an earlier, narrower walk.\n  Object.defineProperty(node, '__source', {\n    value: locator.fromPath(path),\n    enumerable: false,\n    configurable: true,\n    writable: true,\n  })\n\n  Object.entries(node).forEach(([key, entry]) => {\n    stampSource(entry, [...path, key], locator)\n  })\n}\n\n/**\n * Convert form configuration from builders into JSON.\n * Recursively processes objects and arrays, calling build() on any Buildable instances.\n *\n * Every object node in the output is stamped with a non-enumerable `__source`\n * ({ path, formattedPath }) describing its position in the finalised tree.\n * Stamping happens in a second pass over the fully finalised tree so that\n * formatted paths resolve context (step codes, block variants) against final\n * values rather than un-built builders.\n *\n * Shared builder instances are finalised once per tree position: each position\n * gets its own built copy so per-position `__source` stamps are possible.\n * Circular references in the input throw.\n *\n * @param input - Objects, arrays that contain builders\n */\nexport const finaliseBuilders = <T>(input: T): unknown => {\n  const result = finalise(input, [], new Set())\n  stampSource(result, [], new DSLSourceLocator(result))\n  return result\n}\n","import { finaliseBuilders } from './utils/finaliseBuilders'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { BlockDefinition, FieldBlockDefinition } from '../../components/types/structures.type'\nimport { JourneyDefinition, StepDefinition } from '../types/structures.type'\nimport { ForgePackage, RegisteredForgePackage } from '../types/package.type'\nimport { BlockType, StructureType } from '../types/enums'\n\n/**\n * Creates a presentational (non-field) block for a step.\n * Use for headings, paragraphs, inset text, and other non-interactive content.\n */\nexport function block<D extends BlockDefinition>(definition: Omit<D, 'type' | 'blockType'>): D {\n  const result = finaliseBuilders({\n    ...definition,\n    type: StructureType.BLOCK,\n    blockType: BlockType.BASIC,\n  }) as D\n  stampCallsite(result, captureCallsite(block))\n  return result\n}\n\n/**\n * Creates a field block that captures user input.\n * Fields have a `code` for storing answers and support `validWhen`, `dependentWhen`,\n * `defaultValue`, and `formatters`.\n */\nexport function field<D extends FieldBlockDefinition>(definition: Omit<D, 'type' | 'blockType'>): D {\n  const result = finaliseBuilders({\n    ...definition,\n    type: StructureType.BLOCK,\n    blockType: BlockType.FIELD,\n  }) as D\n  stampCallsite(result, captureCallsite(field))\n  return result\n}\n\n/**\n * Creates a step (page) within a journey.\n * Steps contain blocks and define lifecycle hooks for access, submission, and actions.\n */\nexport function step<D extends StepDefinition>(definition: Omit<D, 'type'>): D {\n  const result = finaliseBuilders({\n    ...definition,\n    type: StructureType.STEP,\n  }) as D\n  stampCallsite(result, captureCallsite(step))\n  return result\n}\n\n/**\n * Creates a journey definition - a complete form flow containing steps.\n */\nexport function journey<D extends JourneyDefinition>(definition: Omit<D, 'type'>): D {\n  const result = finaliseBuilders({\n    ...definition,\n    type: StructureType.JOURNEY,\n  }) as D\n  stampCallsite(result, captureCallsite(journey))\n  return result\n}\n\n/**\n * Create a forge package that bundles a journey with its custom functions and components.\n *\n * This is the mandatory gate into Forge: it parses string journeys, finalises\n * any builders in the journey tree (stamping source locations for diagnostics),\n * and brands the result so `Forge.registerPackage()` accepts it.\n *\n * @param pkg - The forge package configuration\n * @returns The package with a finalised journey, branded for registration\n *\n * @example\n * ```typescript\n * // Package with custom functions (deps injected via registerPackage)\n * export default createForgePackage<MyDeps>({\n *   journey: myJourney,\n *   functions: {\n *     ...myEffectsImplementations,\n *     ...myTransformersImplementations,\n *   },\n * })\n *\n * // Journey only (no custom functions)\n * export default createForgePackage({\n *   journey: simpleJourney,\n * })\n * ```\n */\nexport function createForgePackage<TDeps = Record<string, never>>(\n  pkg: ForgePackage<TDeps>,\n): RegisteredForgePackage<TDeps> {\n  const parsed: unknown = typeof pkg.journey === 'string' ? JSON.parse(pkg.journey) : pkg.journey\n\n  const result: RegisteredForgePackage<TDeps> = {\n    ...pkg,\n    journey: finaliseBuilders(parsed) as JourneyDefinition,\n    forgePackage: true,\n  }\n  stampCallsite(result, captureCallsite(createForgePackage))\n  return result\n}\n","import { ExpressionBuilder } from './ExpressionBuilder'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport { ChainableExpr, ChainableGenerator } from './types'\nimport { ResolvableValue } from '../types/expressions.type'\nimport { ResolvableString } from '../../components/types/structures.type'\nimport { FormatGenerators } from '../../built-ins/functions/generators/formatGenerators'\n\n/**\n * Creates a string formatting expression with placeholder substitution.\n * Placeholders are %1, %2, etc.\n *\n * @example\n * Format('Hello %1!', Answer('name'))\n * Format('%1 %2', Answer('firstName'), Answer('lastName'))\n */\nexport const Format = FormatGenerators.FormatString as (\n  template: ResolvableString,\n  ...args: ResolvableString[]\n) => ChainableGenerator\n\n/**\n * Wraps a static/literal value to make it chainable with .pipe() and .match().\n *\n * Use this when you have static data that you want to transform or test\n * using the fluent expression API.\n *\n * @param value - Any static value (array, object, primitive)\n * @returns A chainable expression (only exposes .pipe(), .match(), .not)\n *\n * @example\n * // Static array with transformations\n * Literal(['apple', 'banana', 'cherry']).pipe(Transformer.Array.Filter(...))\n *\n * // Static value with condition\n * Literal(42).match(Condition.Number.GreaterThan(0))\n *\n * // Use with .each() for iteration\n * Literal([1, 2, 3]).each(Iterator.Map(Item().value()))\n */\nexport function Literal(value: ResolvableValue): ChainableExpr {\n  const expr = ExpressionBuilder.from(value)\n  stampCallsite(expr, captureCallsite(Literal))\n  return expr\n}\n","import {\n  ConditionBranchExpr,\n  ConditionAndExpr,\n  ConditionOrExpr,\n  ConditionXorExpr,\n  ConditionNotExpr,\n  PredicateExpr,\n  PredicateAndExpr,\n  PredicateOrExpr,\n  PredicateXorExpr,\n  PredicateNotExpr,\n} from '../types/expressions.type'\nimport { ConditionCombinatorType, FunctionType, PredicateType } from '../types/enums'\nimport { captureCallsite, stampCallsite } from './utils/captureCallsite'\nimport ForgeAuthoringError from '../../engine/errors/ForgeAuthoringError'\n\n/** A single operand of a combinator: a bare condition branch, or a predicate. */\ntype CombinatorOperand = ConditionBranchExpr | PredicateExpr\n\n/** Both call forms the AND, OR and XOR combinators accept: one array, or two or more operands. */\ntype CombinatorArgs = [CombinatorOperand[]] | [CombinatorOperand, CombinatorOperand, ...CombinatorOperand[]]\n\n/** The kind of operand a combinator was called with, which decides the node it builds. */\nenum OperandKind {\n  CONDITION = 'OperandKind.Condition',\n  PREDICATE = 'OperandKind.Predicate',\n}\n\ntype ClassifiedOperands =\n  | { kind: OperandKind.CONDITION; operands: ConditionBranchExpr[] }\n  | { kind: OperandKind.PREDICATE; operands: PredicateExpr[] }\n\nconst conditionCombinatorTypes = new Set<string>(Object.values(ConditionCombinatorType))\n\n/**\n * Identifies a bare condition branch - a condition function call, or a nested\n * condition combinator over them - as opposed to a predicate, which carries its own subject.\n */\nfunction isConditionBranch(operand: CombinatorOperand): operand is ConditionBranchExpr {\n  return operand.type === FunctionType.CONDITION || conditionCombinatorTypes.has(operand.type)\n}\n\n/**\n * Flattens the array and variadic call forms into a single operand list, and\n * classifies that list as bare conditions or as predicates.\n * @param fnName - The combinator's name, used in the mixed operand error\n * @param args - The arguments the combinator was called with, in either form\n * @returns The flattened operands, tagged with the kind they all share\n * @throws When conditions and predicates are mixed in one call, which the overloads\n * already rule out for TypeScript callers\n */\nfunction classifyOperands(fnName: string, args: CombinatorArgs): ClassifiedOperands {\n  const operands = Array.isArray(args[0]) && args.length === 1 ? args[0] : (args as CombinatorOperand[])\n  const conditions = operands.filter(isConditionBranch)\n  const predicates = operands.filter((operand): operand is PredicateExpr => !isConditionBranch(operand))\n\n  if (conditions.length === 0) {\n    return { kind: OperandKind.PREDICATE, operands: predicates }\n  }\n\n  if (predicates.length > 0) {\n    throw new ForgeAuthoringError({\n      message: `${fnName}() cannot mix bare conditions with predicates — conditions take their subject from the surrounding match`,\n    })\n  }\n\n  return { kind: OperandKind.CONDITION, operands: conditions }\n}\n\n/**\n * Creates an AND combination where all operands must be true.\n * Given predicates, returns an AND logic predicate.\n * Given bare conditions, or combinators over them, returns a subject-less AND\n * condition combinator, whose conditions take their subject from the surrounding match.\n * @param p - Two or more operands to combine, as one array or as separate arguments\n * @returns A logic predicate, or a condition combinator, that is true if all operands are true\n */\nexport function and(p: PredicateExpr[]): PredicateAndExpr\nexport function and(...p: [PredicateExpr, PredicateExpr, ...PredicateExpr[]]): PredicateAndExpr\nexport function and(c: ConditionBranchExpr[]): ConditionAndExpr\nexport function and(...c: [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]]): ConditionAndExpr\nexport function and(...args: CombinatorArgs): PredicateAndExpr | ConditionAndExpr {\n  const classified = classifyOperands('and', args)\n\n  const expr: PredicateAndExpr | ConditionAndExpr =\n    classified.kind === OperandKind.CONDITION\n      ? {\n          type: ConditionCombinatorType.AND,\n          operands: classified.operands as [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]],\n        }\n      : {\n          type: PredicateType.AND,\n          operands: classified.operands as [PredicateExpr, PredicateExpr, ...PredicateExpr[]],\n        }\n  stampCallsite(expr, captureCallsite(and))\n  return expr\n}\n\n/**\n * Creates an OR combination where at least one operand must be true.\n * Given predicates, returns an OR logic predicate.\n * Given bare conditions, or combinators over them, returns a subject-less OR\n * condition combinator, whose conditions take their subject from the surrounding match.\n * @param p - Two or more operands to combine, as one array or as separate arguments\n * @returns A logic predicate, or a condition combinator, that is true if any operand is true\n */\nexport function or(p: PredicateExpr[]): PredicateOrExpr\nexport function or(...p: [PredicateExpr, PredicateExpr, ...PredicateExpr[]]): PredicateOrExpr\nexport function or(c: ConditionBranchExpr[]): ConditionOrExpr\nexport function or(...c: [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]]): ConditionOrExpr\nexport function or(...args: CombinatorArgs): PredicateOrExpr | ConditionOrExpr {\n  const classified = classifyOperands('or', args)\n\n  const expr: PredicateOrExpr | ConditionOrExpr =\n    classified.kind === OperandKind.CONDITION\n      ? {\n          type: ConditionCombinatorType.OR,\n          operands: classified.operands as [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]],\n        }\n      : {\n          type: PredicateType.OR,\n          operands: classified.operands as [PredicateExpr, PredicateExpr, ...PredicateExpr[]],\n        }\n  stampCallsite(expr, captureCallsite(or))\n  return expr\n}\n\n/**\n * Creates an XOR combination where exactly one operand must be true.\n * Given predicates, returns an XOR logic predicate.\n * Given bare conditions, or combinators over them, returns a subject-less XOR\n * condition combinator, whose conditions take their subject from the surrounding match.\n * @param p - Two or more operands to combine, as one array or as separate arguments\n * @returns A logic predicate, or a condition combinator, that is true if exactly one operand is true\n */\nexport function xor(p: PredicateExpr[]): PredicateXorExpr\nexport function xor(...p: [PredicateExpr, PredicateExpr, ...PredicateExpr[]]): PredicateXorExpr\nexport function xor(c: ConditionBranchExpr[]): ConditionXorExpr\nexport function xor(...c: [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]]): ConditionXorExpr\nexport function xor(...args: CombinatorArgs): PredicateXorExpr | ConditionXorExpr {\n  const classified = classifyOperands('xor', args)\n\n  const expr: PredicateXorExpr | ConditionXorExpr =\n    classified.kind === OperandKind.CONDITION\n      ? {\n          type: ConditionCombinatorType.XOR,\n          operands: classified.operands as [ConditionBranchExpr, ConditionBranchExpr, ...ConditionBranchExpr[]],\n        }\n      : {\n          type: PredicateType.XOR,\n          operands: classified.operands as [PredicateExpr, PredicateExpr, ...PredicateExpr[]],\n        }\n  stampCallsite(expr, captureCallsite(xor))\n  return expr\n}\n\n/**\n * Creates a NOT combination that inverts the operand's result.\n * Given a predicate, returns a NOT logic predicate.\n * Given a bare condition, or a combinator over them, returns a subject-less NOT\n * condition combinator, whose conditions take their subject from the surrounding match.\n * @param p - The operand to negate\n * @returns A logic predicate, or a condition combinator, that is the opposite of the operand\n */\nexport function not(p: PredicateExpr): PredicateNotExpr\nexport function not(c: ConditionBranchExpr): ConditionNotExpr\nexport function not(operand: CombinatorOperand): PredicateNotExpr | ConditionNotExpr {\n  const expr: PredicateNotExpr | ConditionNotExpr = isConditionBranch(operand)\n    ? {\n        type: ConditionCombinatorType.NOT,\n        operand,\n      }\n    : {\n        type: PredicateType.NOT,\n        operand,\n      }\n  stampCallsite(expr, captureCallsite(not))\n  return expr\n}\n","import { block as buildBlock, field as buildField } from '../authoring/builders'\nimport type {\n  BaseComponentOptions,\n  ComponentOptions,\n  FieldComponentOptions,\n  ForgeComponent,\n  PropsOf,\n} from './types/components.type'\nimport type { BlockDefinition, EvaluatedBlock, FieldBlockDefinition } from './types/structures.type'\n\n/**\n * Defines a component from a single block interface.\n *\n * The returned value is both the authoring builder and the registry entry, so one\n * declaration covers both roles:\n *\n * ```typescript\n * export interface MyCard extends BlockDefinition { title: string }\n * export const MyCard = component<MyCard>('myCard', {\n *   render: (props, renderer) => {\n *     const nunjucksEnv = renderer as nunjucks.Environment\n *\n *     return nunjucksEnv.render('components/card.njk', { params: { text: props.title } })\n *   },\n * })\n * ```\n *\n * A component that captures user input declares `field: true` - see\n * {@link FieldComponentOptions.field}.\n *\n * @param variant - The component's variant identifier\n * @param options - How the component renders, plus the field options where it is one\n * @returns A callable block builder that doubles as the component registry entry\n */\nexport function component<TBlock extends BlockDefinition, TOutput = string, TRenderer = unknown>(\n  variant: string,\n  options: ComponentOptions<TBlock, TOutput, TRenderer>,\n): ForgeComponent<TBlock, TOutput> {\n  // TBlock is still generic here, so the conditional options type is unresolved - read it\n  // through a shape carrying every member either arm can contribute.\n  const { render, prepare, field, inputSchema, multiple, errorAnchor } = options as BaseComponentOptions<\n    TBlock,\n    TOutput,\n    TRenderer\n  > &\n    Partial<FieldComponentOptions<TBlock, TOutput, TRenderer>>\n\n  const buildDefinition = (props?: PropsOf<TBlock>): TBlock => {\n    const authored = props ?? ({} as PropsOf<TBlock>)\n    const prepared = prepare ? prepare(authored) : authored\n\n    // The field props are only present on a field component; the cast lets both builders\n    // share one definition, and the declared `field` option picks the right one.\n    const definition = { ...prepared, variant } as unknown as Omit<TBlock & FieldBlockDefinition, 'type' | 'blockType'>\n\n    return field\n      ? buildField<TBlock & FieldBlockDefinition>(definition)\n      : buildBlock<TBlock & FieldBlockDefinition>(definition)\n  }\n\n  return Object.assign(buildDefinition, {\n    variant,\n    render: (block: EvaluatedBlock<TBlock>, renderer?: unknown) => render(block, renderer as TRenderer),\n    ...(inputSchema !== undefined && { inputSchema }),\n    ...(multiple !== undefined && { multiple }),\n    ...(errorAnchor !== undefined && { errorAnchor }),\n  })\n}\n","import { component } from '../../components/component'\nimport { escapeHtmlEntities } from '../sanitize'\nimport { isRenderedBlock } from '../../components/typeguards'\nimport type { BlockDefinition, ResolvableString } from '../../components/types/structures.type'\n\n/**\n * HTML Block component.\n *\n * Use this to render raw HTML content within forms.\n *\n * When `tag` is set, content is wrapped in that element with `classes` and `attributes`\n * applied directly. When `tag` is not set but `classes`/`attributes` are present, falls\n * back to a wrapper `<div>`. Content can be a string or an array of rendered blocks\n * (e.g. from a collection expression), which are concatenated into a single string.\n *\n * **WARNING: XSS Risk — Content is rendered as raw HTML without any sanitization.**\n *\n * Any dynamic data interpolated into the content (e.g. via `Format()`, `Data()`, `Item()`)\n * will be rendered as-is. If that data comes from user input or external sources, it **must**\n * be escaped using `Transformer.String.EscapeHtml()` to prevent injection attacks.\n *\n * @example Safe — static developer HTML:\n * ```typescript\n * HtmlBlock({\n *   content: '<p class=\"govuk-body\">Terms of Service</p>',\n * })\n * ```\n *\n * @example Safe — dynamic data escaped before interpolation:\n * ```typescript\n * HtmlBlock({\n *   content: Format(\n *     '<p class=\"govuk-body\">%1</p>',\n *     Data('goalTitle').pipe(Transformer.String.EscapeHtml()),\n *   ),\n * })\n * ```\n *\n * @example UNSAFE — dynamic data interpolated without escaping:\n * ```typescript\n * // DO NOT do this — vulnerable to XSS if goalTitle contains malicious HTML\n * HtmlBlock({\n *   content: Format('<p class=\"govuk-body\">%1</p>', Data('goalTitle')),\n * })\n * ```\n */\nexport interface HtmlBlock extends BlockDefinition {\n  /**\n   * HTML tag to render content within. When set, `classes` and `attributes`\n   * are applied directly to this element instead of a wrapper `<div>`.\n   */\n  tag?: string\n\n  /**\n   * Content to render. Accepts a string, a dynamic expression, or an array of child blocks.\n   * When `tag` is a void element (e.g. `hr`), content is ignored.\n   *\n   * **WARNING: Not sanitized.** Escape any untrusted data with `Transformer.String.EscapeHtml()`.\n   */\n  content?: ResolvableString | BlockDefinition | BlockDefinition[]\n\n  /** Additional CSS classes to apply to the element (optional) */\n  classes?: ResolvableString\n\n  /** Custom HTML attributes for the element (optional) */\n  attributes?: Record<string, any>\n}\n\nconst VOID_ELEMENTS = new Set([\n  'area',\n  'base',\n  'br',\n  'col',\n  'embed',\n  'hr',\n  'img',\n  'input',\n  'link',\n  'meta',\n  'source',\n  'track',\n  'wbr',\n])\n\nconst resolveContent = (content: unknown): string => {\n  if (Array.isArray(content)) {\n    return content.map(item => resolveContent(item)).join('')\n  }\n\n  if (isRenderedBlock(content)) {\n    return content.html\n  }\n\n  return (content as string) ?? ''\n}\n\n/**\n * HTML Block component.\n *\n * Use this to render raw HTML content within forms.\n *\n * When `tag` is set, content is wrapped in that element with `classes` and `attributes`\n * applied directly. When `tag` is not set but `classes`/`attributes` are present, falls\n * back to a wrapper `<div>`. Content can be a string or an array of rendered blocks\n * (e.g. from a collection expression), which are concatenated into a single string.\n *\n * **WARNING: XSS Risk — Content is rendered as raw HTML without any sanitization.**\n *\n * Any dynamic data interpolated into the content (e.g. via `Format()`, `Data()`, `Item()`)\n * will be rendered as-is. If that data comes from user input or external sources, it **must**\n * be escaped using `Transformer.String.EscapeHtml()` to prevent injection attacks.\n *\n * @example Safe — static developer HTML:\n * ```typescript\n * HtmlBlock({\n *   content: '<p class=\"govuk-body\">Terms of Service</p>',\n * })\n * ```\n *\n * @example Safe — dynamic data escaped before interpolation:\n * ```typescript\n * HtmlBlock({\n *   content: Format(\n *     '<p class=\"govuk-body\">%1</p>',\n *     Data('goalTitle').pipe(Transformer.String.EscapeHtml()),\n *   ),\n * })\n * ```\n *\n * @example UNSAFE — dynamic data interpolated without escaping:\n * ```typescript\n * // DO NOT do this — vulnerable to XSS if goalTitle contains malicious HTML\n * HtmlBlock({\n *   content: Format('<p class=\"govuk-body\">%1</p>', Data('goalTitle')),\n * })\n * ```\n */\nexport const HtmlBlock = component<HtmlBlock>('html', {\n  render: props => {\n    const hasAttrs = props.classes || props.attributes\n\n    if (!props.tag && !hasAttrs) {\n      return resolveContent(props.content)\n    }\n\n    const element = props.tag ?? 'div'\n    const classAttr = props.classes ? ` class=\"${escapeHtmlEntities(props.classes)}\"` : ''\n    const customAttrs = props.attributes\n      ? Object.entries(props.attributes)\n          .map(([key, value]) => ` ${escapeHtmlEntities(key)}=\"${escapeHtmlEntities(String(value))}\"`)\n          .join('')\n      : ''\n\n    if (VOID_ELEMENTS.has(element)) {\n      return `<${element}${classAttr}${customAttrs}>`\n    }\n\n    return `<${element}${classAttr}${customAttrs}>${resolveContent(props.content)}</${element}>`\n  },\n})\n","import { component } from '../../components/component'\nimport { StructureType } from '../../authoring/types/enums'\nimport { isRenderedBlock } from '../../components/typeguards'\nimport { escapeHtmlEntities } from '../sanitize'\nimport type {\n  BlockDefinition,\n  ResolvableArray,\n  ResolvableString,\n  RenderedBlock,\n} from '../../components/types/structures.type'\n\n/**\n * Collection Block component.\n * Renders repeated blocks based on a collection expression.\n *\n * The `collection` property accepts any chainable expression that evaluates to an array of blocks.\n * This works with the Iterator pattern (e.g., `Data('items').each(Iterator.Map(...))`)\n *\n * @template T - Type of blocks in the collection array\n * @template F - Type of blocks in the fallback array (defaults to T)\n *\n * @example\n * ```typescript\n * CollectionBlock({\n *   collection: Data('tasks').each(Iterator.Map({\n *     template: MojCard({\n *       heading: Item().path('title'),\n *       content: Item().path('description'),\n *     }),\n *   })),\n *   fallback: [GovUKInsetText({ html: 'No tasks available' })],\n *   classes: 'govuk-!-margin-bottom-6',\n * })\n * ```\n */\nexport interface CollectionBlock<T = BlockDefinition, F = T> extends BlockDefinition {\n  /**\n   * The blocks to render: an expression that evaluates to an array of blocks,\n   * or a static array of block definitions.\n   * @example Data('items').each(Iterator.Map({ template: GovUKInsetText({ ... }) }))\n   * @example [GovUKInsetText({ html: 'First' }), GovUKInsetText({ html: 'Second' })]\n   */\n  collection: ResolvableArray<T>\n\n  /**\n   * Fallback blocks to render when the collection is empty.\n   * @example [GovUKInsetText({ html: 'No items found' })]\n   */\n  fallback?: F[]\n\n  /**\n   * HTML tag to render content within. When set, `classes` and `attributes`\n   * are applied directly to this element instead of a wrapper `<div>`.\n   * @example 'ul'\n   */\n  tag?: string\n\n  /**\n   * Additional CSS classes to apply to the wrapper element.\n   * @example 'govuk-!-margin-bottom-6'\n   */\n  classes?: ResolvableString\n\n  /**\n   * Custom HTML attributes for the wrapper element.\n   * @example { 'data-module': 'collection-list' }\n   */\n  attributes?: Record<string, any>\n}\n\n/**\n * Runtime representation of a collection block after evaluation.\n * The `collection` property contains the rendered blocks from applying the template.\n *\n * Note: This doesn't extend EvaluatedBlock<CollectionBlock> because the\n * `collection` property transforms from an expression to RenderedBlock[]\n * during evaluation - a transformation the generic type can't express.\n */\nexport interface EvaluatedCollectionBlock {\n  type: typeof StructureType.BLOCK\n  variant: 'collection-block'\n\n  /** The rendered blocks from applying the template to each collection item */\n  collection?: RenderedBlock[]\n\n  /** Fallback blocks rendered when the collection is empty */\n  fallback?: RenderedBlock[]\n\n  /** HTML tag for the wrapper element (defaults to div when classes/attributes are present) */\n  tag?: string\n\n  /** Additional CSS classes applied to the wrapper element */\n  classes?: string\n\n  /** Custom HTML attributes for the wrapper element */\n  attributes?: Record<string, string>\n}\n\n/**\n * Extracts a string value from a collection item that could be:\n * - A rendered block (with .html and .block properties)\n * - A plain string\n * - An array of either\n */\nconst extractItemValue = (item: unknown): string => {\n  if (Array.isArray(item)) {\n    return item.map(i => extractItemValue(i)).join('')\n  }\n\n  if (isRenderedBlock(item)) {\n    return item.html\n  }\n\n  return (item as string) ?? ''\n}\n\n/**\n * Render function for collection-block.\n */\nconst renderCollectionBlock = (block: EvaluatedCollectionBlock): string => {\n  let content = ''\n\n  const hasItems = block.collection && block.collection.length > 0\n\n  if (hasItems) {\n    content = block.collection!.map(item => extractItemValue(item)).join('')\n  } else if (block.fallback && block.fallback.length > 0) {\n    content = block.fallback.map(item => extractItemValue(item)).join('')\n  }\n\n  const hasWrapper = block.tag || block.classes || block.attributes\n\n  if (hasWrapper) {\n    const element = block.tag ?? 'div'\n    const classAttr = block.classes ? ` class=\"${escapeHtmlEntities(block.classes)}\"` : ''\n    const customAttrs = block.attributes\n      ? Object.entries(block.attributes)\n          .map(([key, value]) => ` ${escapeHtmlEntities(key)}=\"${escapeHtmlEntities(String(value))}\"`)\n          .join('')\n      : ''\n\n    return `<${element}${classAttr}${customAttrs}>${content}</${element}>`\n  }\n\n  return content\n}\n\n/**\n * Collection Block component.\n * Renders repeated blocks based on a collection expression.\n *\n * The `collection` property accepts any chainable expression that evaluates to an array of blocks.\n * This works with the Iterator pattern (e.g., `Data('items').each(Iterator.Map(...))`)\n *\n * @example\n * ```typescript\n * CollectionBlock({\n *   collection: Data('tasks').each(Iterator.Map({\n *     template: MojCard({\n *       heading: Item().path('title'),\n *       content: Item().path('description'),\n *     }),\n *   })),\n *   fallback: [GovUKInsetText({ html: 'No tasks available' })],\n *   classes: 'govuk-!-margin-bottom-6',\n * })\n * ```\n */\nexport const CollectionBlock = component<CollectionBlock>('collection-block', {\n  // Cast to the evaluated shape because the generic EvaluatedBlock<CollectionBlock> type\n  // cannot express that `collection` transforms from an expression to RenderedBlock[].\n  render: props => renderCollectionBlock(props as unknown as EvaluatedCollectionBlock),\n})\n","import { component } from '../../components/component'\nimport { isRenderedBlock } from '../../components/typeguards'\nimport { escapeHtmlEntities } from '../sanitize'\nimport type { BlockDefinition, ResolvableString } from '../../components/types/structures.type'\n\n/**\n * TemplateWrapper component.\n *\n * Template wrapper allows wrapping child blocks in an HTML template.\n * Slots in the template use the syntax `{{slot:slotName}}` and will be replaced\n * with the rendered HTML of the corresponding blocks in the `slots` property.\n *\n * Values in the template use the syntax `{{valueName}}` and will be replaced\n * with the corresponding string value from the `values` property.\n *\n * @example\n * ```typescript\n * TemplateWrapper({\n *   template: `\n *     <section class=\"govuk-section\">\n *       <h2 class=\"govuk-heading-m\">{{title}}</h2>\n *       {{slot:content}}\n *       <p class=\"govuk-body-s\">{{footer}}</p>\n *     </section>\n *   `,\n *   values: {\n *     title: 'Journey Configuration',\n *     footer: 'See the next page for step configuration.'\n *   },\n *   slots: {\n *     content: [\n *       HtmlBlock({ content: '<p>Explanation...</p>' }),\n *       GovUKCodeBlock({ code: '...' }),\n *     ]\n *   }\n * })\n * ```\n */\nexport interface TemplateWrapper extends BlockDefinition {\n  /**\n   * HTML template with slot markers ({{slot:name}}) and value markers ({{name}}).\n   *\n   * @example '<div class=\"wrapper\">{{slot:content}}</div>'\n   * @example '<h2>{{title}}</h2>{{slot:body}}'\n   */\n  template: ResolvableString\n\n  /**\n   * String values to inject into the template at {{name}} markers.\n   *\n   * **WARNING: Not sanitized.** Values are injected directly into the HTML template.\n   * Escape any untrusted data with `Transformer.String.EscapeHtml()`.\n   *\n   * @example { title: 'Section Title', footer: 'Footer text' }\n   */\n  values?: Record<string, ResolvableString>\n\n  /**\n   * Named slots containing blocks to render at {{slot:name}} markers.\n   *\n   * @example { content: [HtmlBlock({ content: '<p>Hello</p>' })] }\n   */\n  slots?: Record<string, BlockDefinition[]>\n\n  /**\n   * HTML tag to render content within. When set, `classes` and `attributes`\n   * are applied directly to this element instead of a wrapper `<div>`.\n   *\n   * @example 'section'\n   */\n  tag?: string\n\n  /**\n   * Additional CSS classes to apply to the wrapper element (optional).\n   * Only applies when a wrapper element is rendered.\n   *\n   * @example 'govuk-!-margin-bottom-6'\n   */\n  classes?: ResolvableString\n\n  /**\n   * Custom HTML attributes for the wrapper element (optional).\n   * Only applies when a wrapper element is rendered.\n   *\n   * @example { 'data-module': 'template-section' }\n   */\n  attributes?: Record<string, any>\n}\n\n/**\n * Extracts a string value from a value that could be:\n * - A plain string\n * - A rendered block (with .html and .block properties)\n * - An array of strings or rendered blocks\n */\nconst extractStringValue = (value: unknown): string => {\n  if (Array.isArray(value)) {\n    return value.map(v => extractStringValue(v)).join('')\n  }\n\n  if (isRenderedBlock(value)) {\n    return value.html\n  }\n\n  return (value as string) ?? ''\n}\n\n/**\n * TemplateWrapper component.\n *\n * Template wrapper allows wrapping child blocks in an HTML template.\n * Slots in the template use the syntax `{{slot:slotName}}` and will be replaced\n * with the rendered HTML of the corresponding blocks in the `slots` property.\n *\n * Values in the template use the syntax `{{valueName}}` and will be replaced\n * with the corresponding string value from the `values` property.\n *\n * @example\n * ```typescript\n * TemplateWrapper({\n *   template: `\n *     <section class=\"govuk-section\">\n *       <h2 class=\"govuk-heading-m\">{{title}}</h2>\n *       {{slot:content}}\n *       <p class=\"govuk-body-s\">{{footer}}</p>\n *     </section>\n *   `,\n *   values: {\n *     title: 'Journey Configuration',\n *     footer: 'See the next page for step configuration.'\n *   },\n *   slots: {\n *     content: [\n *       HtmlBlock({ content: '<p>Explanation...</p>' }),\n *       GovUKCodeBlock({ code: '...' }),\n *     ]\n *   }\n * })\n * ```\n */\nexport const TemplateWrapper = component<TemplateWrapper>('templateWrapper', {\n  render: props => {\n    let content = props.template\n\n    // Replace value markers: {{valueName}}\n    // Values are developer-controlled (not user input), so no escaping needed.\n    // User input flows through form fields and is escaped by Nunjucks at render time.\n    if (props.values) {\n      Object.entries(props.values).forEach(([key, value]) => {\n        const marker = `{{${key}}}`\n        const stringValue = extractStringValue(value)\n        content = content.split(marker).join(stringValue)\n      })\n    }\n\n    // Replace slot markers: {{slot:slotName}}\n    if (props.slots) {\n      Object.entries(props.slots).forEach(([slotName, renderedBlocks]) => {\n        const marker = `{{slot:${slotName}}}`\n        const slotHtml = renderedBlocks.map(b => b.html).join('')\n        content = content.split(marker).join(slotHtml)\n      })\n    }\n\n    // Clean up any unreplaced markers (slots/values that weren't provided)\n    content = content.replace(/\\{\\{slot:[^}]+}}/g, '')\n    content = content.replace(/\\{\\{[^}]+}}/g, '')\n\n    const hasWrapper = props.tag || props.classes || props.attributes\n\n    if (hasWrapper) {\n      const element = props.tag ?? 'div'\n      const classAttr = props.classes ? ` class=\"${escapeHtmlEntities(props.classes)}\"` : ''\n      const customAttrs = props.attributes\n        ? Object.entries(props.attributes)\n            .map(([key, value]) => ` ${escapeHtmlEntities(key)}=\"${escapeHtmlEntities(String(value))}\"`)\n            .join('')\n        : ''\n\n      return `<${element}${classAttr}${customAttrs}>${content}</${element}>`\n    }\n\n    return content\n  },\n})\n","import { component } from '../../components/component'\nimport { isRenderedBlock } from '../../components/typeguards'\nimport type { BlockDefinition, ResolvableArray } from '../../components/types/structures.type'\n\n/**\n * Fragment component.\n *\n * Groups child blocks without adding a wrapper element - the blocks render\n * back-to-back exactly as they would as siblings.\n *\n * Useful anywhere a single block is expected but you want to output several,\n * such as the template of an `Iterator.Map()`.\n *\n * @example\n * ```typescript\n * Data('tasks').each(Iterator.Map(\n *   Fragment({\n *     blocks: [\n *       GovUKHeading({ text: Item().path('title'), level: 3 }),\n *       GovUKBody({ text: Item().path('description') }),\n *     ],\n *   }),\n * ))\n * ```\n */\nexport interface Fragment extends BlockDefinition {\n  /**\n   * The child blocks to render, in order.\n   *\n   * @example [GovUKHeading({ text: 'Title' }), GovUKBody({ text: 'Body' })]\n   */\n  blocks: ResolvableArray<BlockDefinition>\n}\n\n/**\n * Renders a fragment child to its HTML string:\n * - Rendered blocks contribute their HTML as-is\n * - Arrays are flattened in order\n * - Anything else (e.g. a dynamic expression resolving to non-blocks) is skipped\n */\nconst renderChild = (child: unknown): string => {\n  if (Array.isArray(child)) {\n    return child.map(c => renderChild(c)).join('')\n  }\n\n  if (isRenderedBlock(child)) {\n    return child.html\n  }\n\n  return ''\n}\n\n/**\n * Fragment component.\n *\n * Groups child blocks without adding a wrapper element - the blocks render\n * back-to-back exactly as they would as siblings.\n *\n * @example\n * ```typescript\n * Fragment({\n *   blocks: [\n *     GovUKHeading({ text: 'Title', level: 3 }),\n *     GovUKBody({ text: 'Body' }),\n *   ],\n * })\n * ```\n */\nexport const Fragment = component<Fragment>('fragment', {\n  render: props => props.blocks.map(child => renderChild(child)).join(''),\n})\n","import { HtmlBlock } from './html'\nimport { CollectionBlock } from './collectionBlock'\nimport { TemplateWrapper } from './templateWrapper'\nimport { Fragment } from './fragment'\n\nexport const coreComponents = [HtmlBlock, CollectionBlock, TemplateWrapper, Fragment]\n\n// Re-export supporting types\nexport type { EvaluatedCollectionBlock } from './collectionBlock'\n\n// Re-export the components (each const is both the block builder and the registry entry)\nexport { HtmlBlock } from './html'\nexport { CollectionBlock } from './collectionBlock'\nexport { TemplateWrapper } from './templateWrapper'\nexport { Fragment } from './fragment'\n","// Each rolldown entry point (core, core/authoring) inlines its own copy of this class, so a\n// module-level Set would warn once per bundle rather than once per process. The Symbol.for key\n// is process-global, so the seen-codes set survives the duplication and dedupes across bundles.\nconst SEEN_CODES = Symbol.for('forge:deprecations')\n\ninterface DeprecationsGlobal {\n  [SEEN_CODES]?: Set<string>\n}\n\nexport class ForgeDeprecations {\n  /**\n   * Emit a runtime deprecation warning exactly once per process for the given `code`.\n   *\n   * Warnings go through `process.emitWarning` with `type: 'DeprecationWarning'`, so Node's\n   * `--trace-deprecation`, `--throw-deprecation`, and `--no-deprecation` flags apply. Node does\n   * not dedupe `emitWarning` itself, so repeated calls for the same `code` are suppressed here.\n   */\n  static warn(code: string, message: string): void {\n    const seen = ForgeDeprecations.seenCodes()\n\n    if (seen.has(code)) {\n      return\n    }\n\n    seen.add(code)\n    process.emitWarning(message, { type: 'DeprecationWarning', code })\n  }\n\n  private static seenCodes(): Set<string> {\n    const store = globalThis as DeprecationsGlobal\n    const existing = store[SEEN_CODES]\n\n    if (existing) {\n      return existing\n    }\n\n    const seen = new Set<string>()\n    store[SEEN_CODES] = seen\n\n    return seen\n  }\n}\n","import { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport type { RouteTreeRouteKind } from '../../../../framework/types/routeTree.type'\n\nexport interface JourneyRouteTemplateCatalog {\n  routeTemplatePathByStepId: Map<NodeId, string>\n  stepIdByRouteTemplatePath: Map<string, NodeId>\n}\n\nexport interface StoredRouteTreeRoute {\n  kind: RouteTreeRouteKind\n  nodeId: NodeId\n}\n\nexport interface StoredRouteTreeNode {\n  segment: string\n  templatePath: string\n  route?: StoredRouteTreeRoute\n  children: StoredRouteTreeNode[]\n}\n\nexport type StoredRouteTree = StoredRouteTreeNode[]\n\nexport interface RouteTreeIndex {\n  roots: StoredRouteTree\n  nodesByTemplatePath: Map<string, StoredRouteTreeNode>\n  journeyNodesById: Map<NodeId, StoredRouteTreeNode>\n  stepNodesById: Map<NodeId, StoredRouteTreeNode>\n}\n\nexport interface JourneyRouteContext {\n  journeyId: NodeId\n  templatePath: string\n  mountPath: string\n  parentTemplatePath?: string\n}\n\nexport interface StepRouteContext {\n  stepId: NodeId\n  path: string\n  routeTemplatePath: string\n  routeTemplateCatalog: JourneyRouteTemplateCatalog\n  journeyBasePath: string\n}\n\nexport interface RouteTreeBuildResult {\n  journeyContexts: JourneyRouteContext[]\n  stepContexts: StepRouteContext[]\n  catalogsByBasePath: Map<string, JourneyRouteTemplateCatalog>\n}\n\nexport function createRouteTreeIndex(): RouteTreeIndex {\n  return {\n    roots: [],\n    nodesByTemplatePath: new Map<string, StoredRouteTreeNode>(),\n    journeyNodesById: new Map<NodeId, StoredRouteTreeNode>(),\n    stepNodesById: new Map<NodeId, StoredRouteTreeNode>(),\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\ninterface ForgeDuplicateRouteErrorOptions {\n  /** The duplicate route path */\n  routePath: string\n  /** Optional additional message */\n  message?: string\n}\n\nexport default class ForgeDuplicateRouteError extends ForgeBaseError {\n  readonly routePath: string\n\n  constructor(options: ForgeDuplicateRouteErrorOptions) {\n    super(options.message ?? `Duplicate route path: ${options.routePath}`)\n    this.routePath = options.routePath\n  }\n}\n","import ForgeInternalError from '../../../errors/ForgeInternalError'\nimport type { JourneyRouteIndex, StepRouteIndex, StepRouteDescriptor } from '../contracts/routeDescriptors.type'\nimport type { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport { joinPaths } from '../../../../shared/routePath'\nimport ForgeDuplicateRouteError from '../../../errors/ForgeDuplicateRouteError'\nimport {\n  JourneyRouteContext,\n  JourneyRouteTemplateCatalog,\n  RouteTreeBuildResult,\n  RouteTreeIndex,\n  StepRouteContext,\n  StoredRouteTreeNode,\n  StoredRouteTreeRoute,\n} from '../contracts/routeTree.type'\n\nexport interface RouteTreeBuilderInput {\n  basePath: string\n  stepRouteIndex: StepRouteIndex\n  journeyRouteIndex: JourneyRouteIndex\n}\n\nexport default class RouteTreeBuilder {\n  constructor(private readonly routeTreeIndex: RouteTreeIndex) {}\n\n  build(input: RouteTreeBuilderInput): RouteTreeBuildResult {\n    const journeyContexts = this.buildJourneyContexts(input.journeyRouteIndex, input.basePath)\n    const catalogsByBasePath = new Map<string, JourneyRouteTemplateCatalog>()\n\n    journeyContexts.forEach(context => {\n      const route: StoredRouteTreeRoute = {\n        kind: 'journey',\n        nodeId: context.journeyId,\n      }\n      const node = this.insertConcreteRoute(context.templatePath, route)\n\n      this.routeTreeIndex.journeyNodesById.set(context.journeyId, node)\n    })\n\n    const stepContexts = Array.from(input.stepRouteIndex.entries()).map(([stepId, descriptor]) =>\n      this.buildStepContext(stepId, descriptor, input.journeyRouteIndex, input.basePath, catalogsByBasePath),\n    )\n\n    stepContexts.forEach(context => {\n      const route: StoredRouteTreeRoute = {\n        kind: 'step',\n        nodeId: context.stepId,\n      }\n      const node = this.insertConcreteRoute(context.routeTemplatePath, route)\n\n      this.routeTreeIndex.stepNodesById.set(context.stepId, node)\n    })\n\n    return {\n      journeyContexts,\n      stepContexts,\n      catalogsByBasePath,\n    }\n  }\n\n  private buildJourneyContexts(journeyRouteIndex: JourneyRouteIndex, basePath: string): JourneyRouteContext[] {\n    const contextsById = new Map<NodeId, JourneyRouteContext>()\n\n    journeyRouteIndex.forEach(descriptor => {\n      let parentPath = basePath\n      let parentTemplatePath: string | undefined\n\n      descriptor.ancestorJourneyIds.forEach(ancestorId => {\n        const ancestor = journeyRouteIndex.get(ancestorId)\n\n        if (!ancestor) {\n          return\n        }\n\n        const templatePath = joinPaths(parentPath, ancestor.path)\n\n        if (!contextsById.has(ancestor.nodeId)) {\n          contextsById.set(ancestor.nodeId, {\n            journeyId: ancestor.nodeId,\n            templatePath,\n            mountPath:\n              parentTemplatePath === undefined ? joinPaths(basePath, ancestor.path) : joinPaths('', ancestor.path),\n            parentTemplatePath,\n          })\n        }\n\n        parentPath = templatePath\n        parentTemplatePath = templatePath\n      })\n    })\n\n    return Array.from(contextsById.values())\n  }\n\n  private buildStepContext(\n    stepId: NodeId,\n    descriptor: StepRouteDescriptor,\n    journeyRouteIndex: JourneyRouteIndex,\n    basePath: string,\n    catalogsByBasePath: Map<string, JourneyRouteTemplateCatalog>,\n  ): StepRouteContext {\n    const journeyBasePath = this.getJourneyBasePath(descriptor.ancestorJourneyIds, journeyRouteIndex, basePath)\n    const routeTemplatePath = joinPaths(journeyBasePath, descriptor.path)\n    const routeTemplateCatalog = this.getRouteTemplateCatalog(catalogsByBasePath, journeyBasePath)\n\n    routeTemplateCatalog.routeTemplatePathByStepId.set(stepId, routeTemplatePath)\n    routeTemplateCatalog.stepIdByRouteTemplatePath.set(routeTemplatePath, stepId)\n\n    return {\n      stepId,\n      path: descriptor.path,\n      routeTemplatePath,\n      routeTemplateCatalog,\n      journeyBasePath,\n    }\n  }\n\n  private getJourneyBasePath(\n    ancestorJourneyIds: readonly NodeId[],\n    journeyRouteIndex: JourneyRouteIndex,\n    basePath: string,\n  ): string {\n    return ancestorJourneyIds.reduce((path, id) => {\n      const descriptor = journeyRouteIndex.get(id)\n\n      if (!descriptor) {\n        return path\n      }\n\n      return joinPaths(path, descriptor.path)\n    }, basePath)\n  }\n\n  private getRouteTemplateCatalog(\n    catalogsByBasePath: Map<string, JourneyRouteTemplateCatalog>,\n    journeyBasePath: string,\n  ): JourneyRouteTemplateCatalog {\n    const existing = catalogsByBasePath.get(journeyBasePath)\n\n    if (existing) {\n      return existing\n    }\n\n    const catalog = {\n      routeTemplatePathByStepId: new Map<NodeId, string>(),\n      stepIdByRouteTemplatePath: new Map<string, NodeId>(),\n    }\n\n    catalogsByBasePath.set(journeyBasePath, catalog)\n\n    return catalog\n  }\n\n  private insertConcreteRoute(templatePath: string, route: StoredRouteTreeRoute): StoredRouteTreeNode {\n    const node = this.ensureNode(templatePath)\n\n    if (node.route !== undefined) {\n      const isStepOverridingJourney = node.route.kind === 'journey' && route.kind === 'step'\n\n      if (!isStepOverridingJourney) {\n        throw new ForgeDuplicateRouteError({ routePath: templatePath })\n      }\n    }\n\n    node.route = route\n\n    return node\n  }\n\n  private ensureNode(path: string): StoredRouteTreeNode {\n    const templatePath = joinPaths(path)\n    const existing = this.routeTreeIndex.nodesByTemplatePath.get(templatePath)\n\n    if (existing) {\n      return existing\n    }\n\n    const segments = this.getPathSegments(templatePath)\n\n    if (segments.length === 0) {\n      return this.ensureChildNode(this.routeTreeIndex.roots, '', '/')\n    }\n\n    let parentPath = ''\n    let siblings = this.routeTreeIndex.roots\n    let node: StoredRouteTreeNode | undefined\n\n    segments.forEach(segment => {\n      const childPath = joinPaths(parentPath, segment)\n\n      node = this.ensureChildNode(siblings, segment, childPath)\n      siblings = node.children\n      parentPath = childPath\n    })\n\n    if (!node) {\n      throw new ForgeInternalError(`Unable to build route tree node for path \"${path}\"`)\n    }\n\n    return node\n  }\n\n  private ensureChildNode(siblings: StoredRouteTreeNode[], segment: string, templatePath: string): StoredRouteTreeNode {\n    const existing = siblings.find(child => child.segment === segment)\n\n    if (existing) {\n      return existing\n    }\n\n    const node: StoredRouteTreeNode = {\n      segment,\n      templatePath,\n      children: [],\n    }\n\n    siblings.push(node)\n    this.routeTreeIndex.nodesByTemplatePath.set(templatePath, node)\n\n    return node\n  }\n\n  private getPathSegments(path: string): string[] {\n    return path.split('/').filter(Boolean)\n  }\n}\n","import { normalizeBasePath } from '../../../shared/routePath'\nimport type PackageInstance from '../../PackageInstance'\nimport type { NodeId } from '../contracts/ast/ast.type'\nimport type {\n  CompiledAccessLifecycleFunction,\n  CompiledSubmitHooksFunction,\n} from '../../concerns/hooks/contracts/hookLifecycle.type'\nimport type {\n  CompiledAnswerPreparationFunction,\n  CompiledEntryValidationFunction,\n  CompiledReachabilityFactsFunction,\n  CompiledReachabilityStateFunction,\n  CompiledResolveFunction,\n  CompiledRouteMetadataFunction,\n  CompiledStaticDataFunction,\n  CompiledValidationFunction,\n} from '../contracts/compiled/compiledFunctions.type'\nimport type { CompiledFieldInventoryFunction } from '../../concerns/answer-cleardown/contracts/compiledFieldInventory.type'\nimport type FunctionRegistry from './FunctionRegistry'\nimport type { ComponentRegistry } from '../../../framework/types/adapter.type'\nimport {\n  createRouteTreeIndex,\n  JourneyRouteContext,\n  JourneyRouteTemplateCatalog,\n  RouteTreeIndex,\n  StepRouteContext,\n  StoredRouteTree,\n} from '../../concerns/route/contracts/routeTree.type'\nimport type { JourneyRouteIndex, StepRouteIndex } from '../../concerns/route/contracts/routeDescriptors.type'\nimport RouteTreeBuilder from '../../concerns/route/runtime/RouteTreeBuilder'\nimport type { ForgeRoute, ForgeTopology } from '../../../framework/types/topology.type'\n\ninterface MountedNodeBase {\n  readonly mountKey: string\n  readonly kind: 'step' | 'journey'\n  readonly nodeId: NodeId\n  readonly journeyCode: string\n  readonly path: string\n  readonly templatePath: string\n  readonly basePath: string\n  readonly functionRegistry: FunctionRegistry\n  readonly componentRegistry: ComponentRegistry\n  readonly compiledReachabilityFacts: CompiledReachabilityFactsFunction\n  readonly compiledReachabilityState: CompiledReachabilityStateFunction\n  readonly compiledFieldInventory: CompiledFieldInventoryFunction | undefined\n  readonly routeTemplateCatalog: JourneyRouteTemplateCatalog\n  readonly compiledStaticData: CompiledStaticDataFunction\n  readonly compiledAccessLifecycle: CompiledAccessLifecycleFunction\n  readonly compiledAnswerPreparation: CompiledAnswerPreparationFunction\n  readonly compiledStepValidations: ReadonlyMap<NodeId, CompiledValidationFunction>\n  readonly compiledRouteMetadata: CompiledRouteMetadataFunction\n}\n\nexport interface MountedStepNode extends MountedNodeBase {\n  readonly kind: 'step'\n  readonly compiledEntryValidation: CompiledEntryValidationFunction\n  readonly compiledSubmitHooks: CompiledSubmitHooksFunction\n  readonly compiledValidation: CompiledValidationFunction\n  readonly compiledResolve: CompiledResolveFunction\n  readonly routeTree: StoredRouteTree\n}\n\ninterface MountedJourneyNode extends MountedNodeBase {\n  readonly kind: 'journey'\n}\n\nexport type MountedNode = MountedStepNode | MountedJourneyNode\n\nexport default class MountRegistry {\n  private readonly basePath: string\n\n  private readonly routeTreeIndex: RouteTreeIndex = createRouteTreeIndex()\n\n  private readonly nodesByMountKey = new Map<string, MountedNode>()\n\n  constructor(basePath?: string) {\n    this.basePath = normalizeBasePath(basePath)\n  }\n\n  register(packageInstance: PackageInstance): void {\n    const { functionRegistry, componentRegistry } = packageInstance.getDependencies()\n    const stepRouteIndex = packageInstance.getStepRouteIndex()\n    const journeyRouteIndex = packageInstance.getJourneyRouteIndex()\n    const journeyCode = packageInstance.getJourneyCode()\n    const routeTreeBuilder = new RouteTreeBuilder(this.routeTreeIndex)\n    const { journeyContexts, stepContexts, catalogsByBasePath } = routeTreeBuilder.build({\n      basePath: this.basePath,\n      stepRouteIndex,\n      journeyRouteIndex,\n    })\n\n    this.buildStepNodes(packageInstance, stepContexts, stepRouteIndex, journeyCode, functionRegistry, componentRegistry)\n    this.buildJourneyNodes(\n      packageInstance,\n      journeyContexts,\n      journeyRouteIndex,\n      catalogsByBasePath,\n      journeyCode,\n      functionRegistry,\n      componentRegistry,\n    )\n  }\n\n  getNode(mountKey: string): MountedNode | undefined {\n    return this.nodesByMountKey.get(mountKey)\n  }\n\n  getTopology(): ForgeTopology {\n    const routes: ForgeRoute[] = []\n\n    this.nodesByMountKey.forEach(node => {\n      routes.push({\n        nodeId: node.mountKey,\n        kind: node.kind,\n        templatePath: node.templatePath,\n        basePath: node.basePath,\n        methods: node.kind === 'step' ? ['GET', 'POST'] : ['GET'],\n      })\n    })\n\n    return { routes }\n  }\n\n  private buildStepNodes(\n    packageInstance: PackageInstance,\n    stepContexts: StepRouteContext[],\n    stepRouteIndex: StepRouteIndex,\n    journeyCode: string,\n    functionRegistry: FunctionRegistry,\n    componentRegistry: ComponentRegistry,\n  ): void {\n    stepContexts.forEach(ctx => {\n      const compiledStep = packageInstance.getCompiledStep(ctx.stepId)\n      const { mountInfo } = compiledStep\n      const mountKey = MountRegistry.scopedRouteKey(journeyCode, ctx.stepId)\n\n      this.nodesByMountKey.set(mountKey, {\n        kind: 'step',\n        mountKey,\n        nodeId: mountInfo.stepId,\n        journeyCode,\n        path: mountInfo.path,\n        templatePath: ctx.routeTemplatePath,\n        basePath: ctx.journeyBasePath,\n        functionRegistry,\n        componentRegistry,\n        compiledReachabilityFacts: compiledStep.compiledReachabilityFacts,\n        compiledReachabilityState: compiledStep.compiledReachabilityState,\n        compiledFieldInventory: compiledStep.compiledFieldInventory,\n        routeTemplateCatalog: ctx.routeTemplateCatalog,\n        compiledStaticData: compiledStep.compiledStaticData,\n        compiledAccessLifecycle: compiledStep.compiledAccessLifecycle,\n        compiledAnswerPreparation: compiledStep.compiledAnswerPreparation,\n        compiledStepValidations: compiledStep.compiledStepValidations,\n        compiledRouteMetadata: compiledStep.compiledRouteMetadata,\n        compiledEntryValidation: compiledStep.compiledEntryValidation,\n        compiledSubmitHooks: compiledStep.compiledSubmitHooks,\n        compiledValidation: compiledStep.compiledValidation,\n        compiledResolve: compiledStep.compiledResolve,\n        routeTree: this.routeTreeIndex.roots,\n      })\n    })\n  }\n\n  private buildJourneyNodes(\n    packageInstance: PackageInstance,\n    journeyContexts: JourneyRouteContext[],\n    journeyRouteIndex: JourneyRouteIndex,\n    catalogsByBasePath: Map<string, JourneyRouteTemplateCatalog>,\n    journeyCode: string,\n    functionRegistry: FunctionRegistry,\n    componentRegistry: ComponentRegistry,\n  ): void {\n    journeyContexts.forEach(({ journeyId, templatePath }) => {\n      const compiledJourney = packageInstance.getCompiledJourney(journeyId)\n      const routeTemplateCatalog = catalogsByBasePath.get(templatePath)\n\n      if (!compiledJourney || !routeTemplateCatalog) {\n        return\n      }\n\n      const { mountInfo } = compiledJourney\n      const mountKey = MountRegistry.scopedRouteKey(journeyCode, journeyId)\n\n      this.nodesByMountKey.set(mountKey, {\n        kind: 'journey',\n        mountKey,\n        nodeId: mountInfo.journeyId,\n        journeyCode,\n        path: mountInfo.path,\n        templatePath,\n        basePath: templatePath,\n        functionRegistry,\n        componentRegistry,\n        compiledReachabilityFacts: compiledJourney.compiledReachabilityFacts,\n        compiledReachabilityState: compiledJourney.compiledReachabilityState,\n        compiledFieldInventory: compiledJourney.compiledFieldInventory,\n        routeTemplateCatalog,\n        compiledStaticData: compiledJourney.compiledStaticData,\n        compiledAccessLifecycle: compiledJourney.compiledAccessLifecycle,\n        compiledAnswerPreparation: compiledJourney.compiledAnswerPreparation,\n        compiledStepValidations: compiledJourney.compiledStepValidations,\n        compiledRouteMetadata: compiledJourney.compiledRouteMetadata,\n      })\n    })\n  }\n\n  static scopedRouteKey(journeyCode: string, nodeId: NodeId): string {\n    return `${journeyCode}::${nodeId}`\n  }\n}\n","import { AnswerHistory, HookType } from '../../contracts/runtime/answerHistory.type'\nimport type { CookieOptions } from '../../../../framework/types/response.type'\nimport type { ResponseBindings } from '../../../../framework/types/responseBindings.type'\nimport type { RuntimeContext } from '../../contracts/runtime/evaluationState.type'\n\nfunction assertStringParam(value: unknown, method: string, param: string): void {\n  if (typeof value !== 'string') {\n    throw new TypeError(`${method}: ${param} must be a string, got ${typeof value}`)\n  }\n}\n\n/**\n * Asserts that a value is JSON-serializable (no functions, Symbols, BigInts, Dates, or class instances).\n * Recursively checks nested objects and arrays.\n */\nfunction assertSerializable(value: unknown, method: string, path: string[] = []): void {\n  if (typeof value === 'function') {\n    throw new TypeError(`${method}: Cannot set a function as a value (at ${formatAssertPath(path)})`)\n  }\n\n  if (typeof value === 'symbol') {\n    throw new TypeError(`${method}: Cannot set a Symbol as a value (at ${formatAssertPath(path)})`)\n  }\n\n  if (typeof value === 'bigint') {\n    throw new TypeError(`${method}: Cannot set a BigInt as a value (at ${formatAssertPath(path)})`)\n  }\n\n  if (value instanceof Date) {\n    throw new TypeError(\n      `${method}: Cannot set a Date object as a value — use an ISO string instead (at ${formatAssertPath(path)})`,\n    )\n  }\n\n  if (value !== null && typeof value === 'object') {\n    if (!Array.isArray(value) && value.constructor !== Object) {\n      throw new TypeError(\n        `${method}: Cannot set a ${value.constructor.name} instance as a value — use a plain object instead (at ${formatAssertPath(path)})`,\n      )\n    }\n\n    if (Array.isArray(value)) {\n      value.forEach((item, i) => assertSerializable(item, method, [...path, String(i)]))\n    } else {\n      Object.entries(value).forEach(([key, v]) => assertSerializable(v, method, [...path, key]))\n    }\n  }\n}\n\nfunction formatAssertPath(path: string[]): string {\n  return path.length > 0 ? path.join('.') : 'root'\n}\n\n/**\n * User-friendly context object provided to effect functions.\n * Wraps the request/evaluation state with a cleaner API.\n *\n * Provides access to:\n * - Answers (get, set, check, clear) with mutation history tracking\n * - Data (get, set)\n * - Request data (params, query, post, session, state)\n * - Response mutations (headers, cookies)\n *\n * The hookType parameter determines the source recorded when setting answers.\n *\n * @typeParam TData - Type for stored data (accessed via getData/setData)\n * @typeParam TAnswers - Type for form answers (accessed via getAnswer/setAnswer)\n * @typeParam TSession - Type for session object (accessed via getSession)\n * @typeParam TState - Type for request state (accessed via getState)\n *\n * @example\n * // Define your project/journey schemas\n * interface MyData {\n *   assessmentUuid: string\n *   goals: Goal[]\n * }\n *\n * interface MyAnswers {\n *   goalDescription: string\n *   targetDate: string\n * }\n *\n * interface MySession {\n *   user: User\n *   stepsCompleted: string[]\n * }\n *\n * // Create a typed context alias\n * type MyContext = EffectFunctionContext<MyData, MyAnswers, MySession>\n *\n * // Use in effects\n * const myEffect = (context: MyContext) => {\n *   context.getData('assessmentUuid')  // typed as string\n *   context.getData('nonExistent')     // compile error\n * }\n */\nclass EffectFunctionContext<\n  TData extends Record<string, unknown> = Record<string, unknown>,\n  TAnswers extends Record<string, unknown> = Record<string, unknown>,\n  TSession = unknown,\n  TState extends Record<string, unknown> = Record<string, unknown>,\n> {\n  /** @internal */\n  constructor(\n    private readonly context: RuntimeContext,\n    private readonly response: ResponseBindings,\n    private readonly hookType: HookType,\n  ) {}\n\n  /**\n   * Get a specific answer value by key\n   */\n  getAnswer<K extends string & keyof TAnswers>(key: K): TAnswers[K]\n\n  getAnswer<TValue = unknown>(key: string): TValue\n\n  getAnswer<TValue = unknown>(key: string): TValue {\n    return this.context.domain.answers[key]?.current as TValue\n  }\n\n  /**\n   * Set a specific answer value\n   *\n   * Pushes a mutation to the answer's history with the current hookType as source.\n   * This enables precedence logic and delta tracking via mutation history.\n   */\n  setAnswer<K extends string & keyof TAnswers>(key: K, value: TAnswers[K]): void {\n    assertSerializable(value, 'setAnswer', [key])\n\n    const history = this.context.domain.answers[key] ?? { current: undefined, mutations: [] }\n\n    history.mutations.push({ value, source: this.hookType })\n    history.current = value\n    this.context.domain.answers[key] = history\n  }\n\n  /**\n   * Get all answers (current values only, without history)\n   */\n  getAllAnswers(): TAnswers {\n    const result: Record<string, unknown> = {}\n\n    Object.entries(this.context.domain.answers).forEach(([key, history]) => {\n      result[key] = history.current\n    })\n\n    return result as TAnswers\n  }\n\n  /**\n   * Get the full history for an answer\n   *\n   * Returns the complete mutation history including all sources that have set this answer.\n   */\n  getAnswerHistory<K extends string & keyof TAnswers>(key: K): AnswerHistory | undefined {\n    return this.context.domain.answers[key]\n  }\n\n  /**\n   * Get all answer histories\n   *\n   * Returns all answers with their full mutation history.\n   * Useful for calculating custom deltas based on mutation sources.\n   */\n  getAllAnswerHistories(): Record<string, AnswerHistory> {\n    return this.context.domain.answers\n  }\n\n  /**\n   * Check if an answer exists\n   */\n  hasAnswer<K extends string & keyof TAnswers>(key: K): boolean {\n    return key in this.context.domain.answers\n  }\n\n  /**\n   * Remove a specific answer\n   */\n  clearAnswer<K extends string & keyof TAnswers>(key: K): void {\n    delete this.context.domain.answers[key]\n  }\n\n  /**\n   * Get stored data by key\n   */\n  getData<K extends string & keyof TData>(key: K): TData[K]\n\n  getData<TValue = unknown>(key: string): TValue\n\n  getData<TValue = unknown>(key: string): TValue {\n    return this.context.domain.data[key] as TValue\n  }\n\n  /**\n   * Store data in the context\n   */\n  setData<K extends string & keyof TData>(key: K, value: TData[K]): void {\n    assertSerializable(value, 'setData', [key])\n\n    this.context.domain.data[key] = value\n  }\n\n  /**\n   * Get all stored data\n   */\n  getAllData(): TData {\n    return { ...this.context.domain.data } as TData\n  }\n\n  /**\n   * Get the full request URL\n   *\n   * @example\n   * const url = new URL(ctx.getRequestUrl())\n   *\n   * url.origin      // 'https://example.com:3000'\n   * url.pathname    // '/forms/journey/step-one'\n   * url.search      // '?page=1&filter=active'\n   * url.searchParams.get('page')  // '1'\n   * url.hash        // '#section'\n   */\n  getRequestUrl(): string {\n    return this.context.request.url\n  }\n\n  /**\n   * Get a specific route parameter\n   */\n  getRequestParam(key: string): string | undefined {\n    return this.context.request.params[key]\n  }\n\n  /**\n   * Get all route parameters\n   */\n  getAllRequestParams(): Record<string, string> {\n    return { ...this.context.request.params }\n  }\n\n  /**\n   * Get a specific query parameter\n   */\n  getQueryParam(key: string): string | string[] | undefined {\n    return this.context.request.query[key]\n  }\n\n  /**\n   * Get all query parameters\n   */\n  getAllQueryParams(): Record<string, string | string[]> {\n    return { ...this.context.request.query }\n  }\n\n  /**\n   * Get raw POST data (before formatting)\n   */\n  getPostData<TValue = unknown>(key: string): TValue | undefined {\n    return this.context.request.post[key] as TValue | undefined\n  }\n\n  /**\n   * Get all raw POST data (before formatting)\n   */\n  getAllPostData<TValue = Record<string, unknown>>(): TValue {\n    return { ...this.context.request.post } as TValue\n  }\n\n  /**\n   * Get the session object\n   */\n  getSession(): TSession | undefined {\n    return this.context.request.session as TSession | undefined\n  }\n\n  /**\n   * Get a custom request state value by key\n   */\n  getState<K extends string & keyof TState>(key: K): TState[K] | undefined {\n    return this.context.request.state[key] as TState[K] | undefined\n  }\n\n  /**\n   * Get all custom request state data\n   */\n  getAllState(): TState {\n    return { ...this.context.request.state } as TState\n  }\n\n  /**\n   * Get a request header value\n   */\n  getRequestHeader(name: string): string | string[] | undefined {\n    return this.context.request.headers[name]\n  }\n\n  /**\n   * Get all request headers\n   */\n  getAllRequestHeaders(): Record<string, string | string[] | undefined> {\n    return { ...this.context.request.headers }\n  }\n\n  /**\n   * Get a request cookie value\n   */\n  getRequestCookie(name: string): string | undefined {\n    return this.context.request.cookies[name]\n  }\n\n  /**\n   * Get all request cookies\n   */\n  getAllRequestCookies(): Record<string, string | undefined> {\n    return { ...this.context.request.cookies }\n  }\n\n  /**\n   * Set a response header via the adapter-provided response bindings.\n   * Setting the same header multiple times will overwrite the previous value.\n   */\n  setResponseHeader(name: string, value: string): void {\n    assertStringParam(name, 'setResponseHeader', 'name')\n    assertStringParam(value, 'setResponseHeader', 'value')\n\n    this.response.setHeader(name, value)\n  }\n\n  /**\n   * Set a cookie via the adapter-provided response bindings.\n   * To clear a cookie, use maxAge: 0.\n   *\n   * @example\n   * // Set a cookie with options\n   * context.setResponseCookie('preference', 'dark', {\n   *   maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days\n   *   httpOnly: true,\n   *   secure: true,\n   *   sameSite: 'lax',\n   * })\n   *\n   * // Clear a cookie\n   * context.setResponseCookie('preference', '', { maxAge: 0 })\n   */\n  setResponseCookie(name: string, value: string, options?: CookieOptions): void {\n    assertStringParam(name, 'setResponseCookie', 'name')\n    assertStringParam(value, 'setResponseCookie', 'value')\n\n    this.response.setCookie(name, value, options)\n  }\n\n  /**\n   * Get the field codes the answer-cleardown phase resolved as stale: field codes on\n   * unreachable steps plus answer keys matching their `cleardownFieldCodes` patterns.\n   * The engine has already pushed a clearing `cleardown` mutation onto each of these\n   * answers; use this list to drop them from your own store when persisting. Empty for\n   * hooks that run before the cleardown phase (access hooks).\n   */\n  getFieldsToClear(): string[] {\n    return [...(this.context.evaluation.fieldsToClear ?? [])]\n  }\n}\n\nexport default EffectFunctionContext\nexport { EffectFunctionContext }\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type {\n  AnswerPreparationFieldResult,\n  FieldAnswerPreparationWorkProps,\n} from '../contracts/AnswerPreparationWork.type'\n\nexport const FIELD_ANSWER_PREPARATION_KIND = 'answer.preparation.field'\n\nexport const FIELD_ANSWER_PREPARATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  FieldAnswerPreparationWorkProps,\n  AnswerPreparationFieldResult\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, FieldAnswerPreparationWorkProps>) {\n    return {\n      code: ctx.props.code,\n      mode: ctx.props.mode,\n    }\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\nexport const FIELD_ANSWER_PREPARATION_WORK_HANDLER: WorkHandler<\n  'answer.preparation.field',\n  FieldAnswerPreparationWorkProps\n> = {\n  kind: FIELD_ANSWER_PREPARATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, FieldAnswerPreparationWorkProps>) {\n    return { output: await ctx.props.run() }\n  },\n}\n\nfunction traceComplete(output: AnswerPreparationFieldResult): TraceSpanFields {\n  return {\n    code: output.code,\n    mode: output.mode,\n    mutationCount: output.mutations.length,\n    parsed: output.parsed !== undefined,\n  }\n}\n\nexport function createFieldAnswerPreparationTask(key: string, props: FieldAnswerPreparationWorkProps) {\n  return createWorkTask(\n    key,\n    FIELD_ANSWER_PREPARATION_WORK_HANDLER,\n    props,\n    FIELD_ANSWER_PREPARATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport { FIELD_ANSWER_PREPARATION_KIND } from './FieldAnswerPreparationWorkHandler'\nimport type {\n  AnswerPreparationResult,\n  AnswerPreparationWorkProps,\n  FieldAnswerPreparationWorkTask,\n} from '../contracts/AnswerPreparationWork.type'\n\nexport const ANSWER_PREPARATION_KIND = 'answer.preparation'\n\nexport const ANSWER_PREPARATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  AnswerPreparationWorkProps,\n  AnswerPreparationResult\n> = {\n  resolveTraceMetadataAtStart() {\n    return undefined\n  },\n\n  resolveTraceMetadataAtFinish(ctx: WorkContextContract<RequestState, AnswerPreparationWorkProps>) {\n    return traceComplete(ctx)\n  },\n}\n\nexport const ANSWER_PREPARATION_WORK_HANDLER: WorkHandler<'answer.preparation', AnswerPreparationWorkProps> = {\n  kind: ANSWER_PREPARATION_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, AnswerPreparationWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'sequential',\n          children: ctx.props.fields,\n        },\n      ],\n    }\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, AnswerPreparationWorkProps>,\n    children: readonly CompletedWork[],\n  ): AnswerPreparationResult {\n    return {\n      fields: childOutputs(children, FIELD_ANSWER_PREPARATION_KIND),\n    }\n  },\n}\n\nfunction traceComplete(ctx: WorkContextContract<RequestState>): TraceSpanFields {\n  return {\n    answers: ctx.state.context.domain.answers,\n  }\n}\n\nexport function createAnswerPreparationTask(fields: readonly FieldAnswerPreparationWorkTask[]) {\n  const props: AnswerPreparationWorkProps = { fields }\n\n  return createWorkTask(\n    'answer-preparation',\n    ANSWER_PREPARATION_WORK_HANDLER,\n    props,\n    ANSWER_PREPARATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport type { StepValidationFailure } from '../../../chassis/contracts/runtime/evaluationState.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { FieldValidationWorkProps } from '../contracts/ValidationWork.type'\n\nexport const FIELD_VALIDATION_KIND = 'validation.field'\n\nexport const FIELD_VALIDATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  FieldValidationWorkProps,\n  readonly StepValidationFailure[]\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, FieldValidationWorkProps>) {\n    return traceBegin(ctx.props)\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return { failures: output.length }\n  },\n}\n\nexport const FIELD_VALIDATION_WORK_HANDLER: WorkHandler<'validation.field', FieldValidationWorkProps> = {\n  kind: FIELD_VALIDATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, FieldValidationWorkProps>) {\n    return { output: await ctx.props.run() }\n  },\n}\n\nfunction traceBegin(props: FieldValidationWorkProps): TraceSpanFields {\n  return {\n    blockId: props.blockId,\n    blockCode: props.blockCode,\n  }\n}\n\nexport function createFieldValidationTask(key: string, props: FieldValidationWorkProps) {\n  return createWorkTask(key, FIELD_VALIDATION_WORK_HANDLER, props, FIELD_VALIDATION_WORK_INSTRUMENTATION)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { DomainValidationFailure } from '../../../chassis/contracts/runtime/evaluationState.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { DomainValidationWorkProps } from '../contracts/ValidationWork.type'\n\nexport const DOMAIN_VALIDATION_KIND = 'validation.domain'\n\nexport const DOMAIN_VALIDATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  DomainValidationWorkProps,\n  readonly DomainValidationFailure[]\n> = {\n  resolveTraceMetadataAtStart() {\n    return undefined\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return { failures: output.length }\n  },\n}\n\nexport const DOMAIN_VALIDATION_WORK_HANDLER: WorkHandler<'validation.domain', DomainValidationWorkProps> = {\n  kind: DOMAIN_VALIDATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, DomainValidationWorkProps>) {\n    return { output: await ctx.props.run() }\n  },\n}\n\nexport function createDomainValidationTask(key: string, props: DomainValidationWorkProps) {\n  return createWorkTask(key, DOMAIN_VALIDATION_WORK_HANDLER, props, DOMAIN_VALIDATION_WORK_INSTRUMENTATION)\n}\n","import type { StepValidityResult } from '../contracts/stepValidityResult.type'\nimport type {\n  DomainValidationFailure,\n  StepValidationFailure,\n} from '../../../chassis/contracts/runtime/evaluationState.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport { FIELD_VALIDATION_KIND } from './FieldValidationWorkHandler'\nimport { DOMAIN_VALIDATION_KIND } from './DomainValidationWorkHandler'\nimport type {\n  DomainValidationWorkTask,\n  FieldValidationWorkTask,\n  StepValidationWorkProps,\n} from '../contracts/ValidationWork.type'\n\nexport const STEP_VALIDATION_KIND = 'validation.step'\n\nexport const STEP_VALIDATION_WORK_INSTRUMENTATION: WorkInstrumentation<StepValidationWorkProps, StepValidityResult> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, StepValidationWorkProps>) {\n    return traceBegin(ctx.props)\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\nexport const STEP_VALIDATION_WORK_HANDLER: WorkHandler<'validation.step', StepValidationWorkProps> = {\n  kind: STEP_VALIDATION_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, StepValidationWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'concurrent',\n          children: ctx.props.fields,\n        },\n        {\n          mode: 'concurrent',\n          children: ctx.props.domains,\n        },\n      ],\n    }\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, StepValidationWorkProps>,\n    children: readonly CompletedWork[],\n  ): StepValidityResult {\n    const fieldFailures = collectFieldFailures(children)\n    const domainFailures = collectDomainFailures(children)\n\n    return { fieldFailures, domainFailures }\n  },\n}\n\nfunction collectFieldFailures(children: readonly CompletedWork[]): StepValidationFailure[] {\n  return childOutputs(children, FIELD_VALIDATION_KIND).flatMap(failures => failures)\n}\n\nfunction collectDomainFailures(children: readonly CompletedWork[]): DomainValidationFailure[] {\n  return childOutputs(children, DOMAIN_VALIDATION_KIND).flatMap(failures => failures)\n}\n\nfunction traceBegin(props: StepValidationWorkProps): TraceSpanFields {\n  return {\n    fieldValidations: props.fields.length,\n    domainValidations: props.domains.length,\n  }\n}\n\nfunction traceComplete(output: StepValidityResult): TraceSpanFields {\n  return {\n    fieldFailures: output.fieldFailures.length,\n    domainFailures: output.domainFailures.length,\n  }\n}\n\nexport function createStepValidationTask(\n  fields: readonly FieldValidationWorkTask[],\n  domains: readonly DomainValidationWorkTask[],\n) {\n  return createWorkTask(\n    'validation-step',\n    STEP_VALIDATION_WORK_HANDLER,\n    { fields, domains },\n    STEP_VALIDATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, singleChildOutput, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { STEP_VALIDATION_KIND } from './StepValidationWorkHandler'\nimport type { StepValidityResult } from '../contracts/stepValidityResult.type'\nimport type { CurrentStepValidationWorkProps } from '../contracts/ValidationWork.type'\nimport type { ValidationView } from '../contracts/validationView.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nexport const CURRENT_STEP_VALIDATION_KIND = 'validation.current-step'\n\nexport const CURRENT_STEP_VALIDATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  CurrentStepValidationWorkProps,\n  ValidationView\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, CurrentStepValidationWorkProps>) {\n    return { groups: ctx.props.groups, includeSubmissionOnly: ctx.props.includeSubmissionOnly }\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return { isValid: output.isValid }\n  },\n}\n\n/**\n * The single current-page validation operation. Both trigger paths schedule this\n * task — entry validation with its matching `validateOnEntry` groups, the submit\n * lifecycle (after `onAlways`) with its hook's validation groups — and the compiled\n * validation applies the group and `submissionOnly` filter before any rule\n * condition runs. `complete` stores the result on `currentPageValidation`, the one\n * request-level display signal: hook branches read its `isValid`, resolve derives\n * the render shape from its presence.\n */\nexport const CURRENT_STEP_VALIDATION_WORK_HANDLER: WorkHandler<\n  'validation.current-step',\n  CurrentStepValidationWorkProps\n> = {\n  kind: CURRENT_STEP_VALIDATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, CurrentStepValidationWorkProps>) {\n    const stepId = ctx.state.dependencies.currentStepId\n\n    if (stepId === undefined) {\n      throw new ForgeInternalError('Current-step validation requires a current step id')\n    }\n\n    const validation = await ctx.state.dependencies.buildStepValidation(stepId, ctx.props)\n\n    if (validation === undefined) {\n      throw new ForgeInternalError('Current-step validation task missing')\n    }\n\n    return singleTaskGroup(validation)\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, CurrentStepValidationWorkProps>,\n    children: readonly CompletedWork[],\n  ): ValidationView {\n    const result = singleChildOutput(children, STEP_VALIDATION_KIND)\n\n    if (result === undefined) {\n      throw new ForgeInternalError('Current-step validation produced an invalid result')\n    }\n\n    const view = toValidationView(result)\n\n    ctx.state.recordCurrentPageValidation(view)\n\n    return view\n  },\n}\n\nfunction toValidationView(result: StepValidityResult): ValidationView {\n  return {\n    isValid: result.fieldFailures.length === 0 && result.domainFailures.length === 0,\n    fieldFailures: result.fieldFailures,\n    domainFailures: result.domainFailures,\n  }\n}\n\nexport function createCurrentStepValidationTask(key: string, props: CurrentStepValidationWorkProps) {\n  return createWorkTask(key, CURRENT_STEP_VALIDATION_WORK_HANDLER, props, CURRENT_STEP_VALIDATION_WORK_INSTRUMENTATION)\n}\n","import { FORGE_WORK } from '../contracts/work/work.type'\nimport type { CompletedWork, WorkTask } from '../contracts/work/work.type'\nimport { isWorkTask } from './workTask'\nimport ForgeInternalError from '../../errors/ForgeInternalError'\n\n/**\n * Collects work tasks embedded anywhere in a props value and, once the executor\n * has run them, substitutes each task with its completed output.\n *\n * `collect` and `replaceCompletedOutputs` walk the props in the same deterministic order\n * (enumerable own keys then array index, depth-first, stopping at task boundaries),\n * so matching is POSITIONAL: the nth task encountered during replace is paired with\n * the nth `completedWork`. The caller must therefore pass `completedWorks` in the exact\n * order `collect` returned the tasks. The executor guarantees this when the tasks\n * are run as a single reduce-all group — both concurrent and sequential preserve child order.\n *\n * The per-position key+kind check is a sanity assertion, not an identity match: task\n * keys are not assumed unique (an iterator can yield sibling blocks that reuse a key), so two\n * same-key, same-kind siblings are told apart only by position. Keep the begin/collect and\n * complete/replace traversals over the same props value, or out-of-order outputs will be\n * mis-paired without tripping the assertion.\n */\nexport default class WorkTaskPropsWalker {\n  collect(value: unknown): readonly WorkTask[] {\n    const workTasks: WorkTask[] = []\n\n    this.collectValue(value, workTasks, new WeakSet<object>())\n\n    return workTasks\n  }\n\n  replaceCompletedOutputs(value: unknown, completedWorks: readonly CompletedWork[]): unknown {\n    let completedWorkIndex = 0\n    const nextCompletedWork = (workTask: WorkTask): CompletedWork => {\n      const completedWork = completedWorks[completedWorkIndex]\n\n      if (completedWork === undefined) {\n        throw new ForgeInternalError(`Missing completed work for task \"${workTask.key}\"`)\n      }\n\n      completedWorkIndex += 1\n      this.assertCompletedWorkMatches(workTask, completedWork)\n\n      return completedWork\n    }\n    const result = this.replaceValue(value, nextCompletedWork, new WeakSet<object>())\n\n    if (completedWorkIndex < completedWorks.length) {\n      throw new ForgeInternalError(\n        `Unused completed work remains from task \"${completedWorks[completedWorkIndex].key}\"`,\n      )\n    }\n\n    return result\n  }\n\n  private collectValue(value: unknown, workTasks: WorkTask[], ancestors: WeakSet<object>): void {\n    if (isWorkTask(value)) {\n      workTasks.push(value)\n\n      return\n    }\n\n    if (this.isMalformedWorkTask(value)) {\n      return\n    }\n\n    if (Array.isArray(value)) {\n      this.assertNotCyclic(value, ancestors)\n      ancestors.add(value)\n      value.forEach(item => this.collectValue(item, workTasks, ancestors))\n      ancestors.delete(value)\n\n      return\n    }\n\n    if (this.isPlainRecord(value)) {\n      this.assertNotCyclic(value, ancestors)\n      ancestors.add(value)\n      this.getEnumerableEntries(value).forEach(([, item]) => this.collectValue(item, workTasks, ancestors))\n      ancestors.delete(value)\n    }\n  }\n\n  private replaceValue(\n    value: unknown,\n    nextCompletedWork: (workTask: WorkTask) => CompletedWork,\n    ancestors: WeakSet<object>,\n  ): unknown {\n    if (isWorkTask(value)) {\n      return nextCompletedWork(value).output\n    }\n\n    if (this.isMalformedWorkTask(value)) {\n      return value\n    }\n\n    if (Array.isArray(value)) {\n      this.assertNotCyclic(value, ancestors)\n      ancestors.add(value)\n      const result = value.map(item => this.replaceValue(item, nextCompletedWork, ancestors))\n\n      ancestors.delete(value)\n\n      return result\n    }\n\n    if (this.isPlainRecord(value)) {\n      this.assertNotCyclic(value, ancestors)\n      ancestors.add(value)\n      const result: Record<PropertyKey, unknown> = {}\n\n      this.getEnumerableEntries(value).forEach(([key, item]) => {\n        result[key] = this.replaceValue(item, nextCompletedWork, ancestors)\n      })\n\n      ancestors.delete(value)\n\n      return result\n    }\n\n    return value\n  }\n\n  private assertCompletedWorkMatches(workTask: WorkTask, completedWork: CompletedWork): void {\n    if (completedWork.key !== workTask.key || completedWork.kind !== workTask.handler.kind) {\n      throw new ForgeInternalError(\n        `Completed work \"${completedWork.key}\" of kind \"${completedWork.kind}\" does not match task \"${workTask.key}\" of kind \"${workTask.handler.kind}\"`,\n      )\n    }\n  }\n\n  private assertNotCyclic(value: object, ancestors: WeakSet<object>): void {\n    if (ancestors.has(value)) {\n      throw new ForgeInternalError('Cannot walk cyclic work task props')\n    }\n  }\n\n  private isPlainRecord(value: unknown): value is Record<PropertyKey, unknown> {\n    if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) {\n      return false\n    }\n\n    const prototype = Object.getPrototypeOf(value)\n\n    return prototype === Object.prototype || prototype === null\n  }\n\n  private isMalformedWorkTask(value: unknown): boolean {\n    return this.isPlainRecord(value) && value.$$typeof === FORGE_WORK\n  }\n\n  private getEnumerableEntries(value: Record<PropertyKey, unknown>): readonly (readonly [PropertyKey, unknown])[] {\n    return Reflect.ownKeys(value)\n      .filter(key => Object.prototype.propertyIsEnumerable.call(value, key))\n      .map(key => [key, value[key]])\n  }\n}\n","import type { CompiledResolveBlockWorkProps } from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport type { BlockType } from '../../../../authoring/types/enums'\nimport { RENDER_BLOCK_BRAND } from '../../render/contracts/renderBlock.brand'\nimport type { RenderBlock } from '../../../../framework/types/rendering.type'\nimport WorkTaskPropsWalker from '../../../chassis/work/WorkTaskPropsWalker'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkTask,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nexport type ResolveBlockWorkProps = CompiledResolveBlockWorkProps\n\nexport type ResolveBlockWorkTask = WorkTask<'resolve.block', ResolveBlockWorkProps>\n\nexport const RESOLVE_BLOCK_KIND = 'resolve.block'\n\nconst propsWalker = new WorkTaskPropsWalker()\n\nexport const RESOLVE_BLOCK_WORK_INSTRUMENTATION: WorkInstrumentation<ResolveBlockWorkProps, RenderBlock> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, ResolveBlockWorkProps>) {\n    return traceBegin(ctx.props)\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\nexport const RESOLVE_BLOCK_WORK_HANDLER: WorkHandler<'resolve.block', ResolveBlockWorkProps> = {\n  kind: RESOLVE_BLOCK_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, ResolveBlockWorkProps>) {\n    const children = propsWalker.collect(ctx.props.properties)\n\n    if (children.length === 0) {\n      return { groups: [] }\n    }\n\n    return {\n      groups: [\n        {\n          mode: 'concurrent',\n          children,\n        },\n      ],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, ResolveBlockWorkProps>,\n    children: readonly CompletedWork[],\n  ): RenderBlock {\n    const properties = replaceCompletedProperties(ctx.props, children)\n\n    return {\n      [RENDER_BLOCK_BRAND]: true,\n      id: ctx.props.id,\n      variant: ctx.props.variant,\n      blockType: ctx.props.blockType,\n      properties,\n    }\n  },\n}\n\nfunction replaceCompletedProperties(\n  props: ResolveBlockWorkProps,\n  children: readonly CompletedWork[],\n): Record<string, unknown> {\n  const properties = propsWalker.replaceCompletedOutputs(props.properties, children)\n\n  if (!isStringRecord(properties)) {\n    throw new ForgeInternalError(`Render block \"${props.id}\" completed with invalid properties`)\n  }\n\n  return properties\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, unknown> {\n  return value !== undefined && value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction traceBegin(props: ResolveBlockWorkProps): TraceSpanFields {\n  return {\n    id: props.id,\n    variant: props.variant,\n    blockType: props.blockType,\n  }\n}\n\nfunction traceComplete(output: RenderBlock): TraceSpanFields {\n  return {\n    visible: output.properties.visibleWhen !== false,\n    properties: output.properties,\n  }\n}\n\nexport function createResolveBlockTask(\n  id: NodeId,\n  variant: string,\n  blockType: BlockType,\n  properties: Record<PropertyKey, unknown>,\n) {\n  return createWorkTask(\n    String(id),\n    RESOLVE_BLOCK_WORK_HANDLER,\n    { id, variant, blockType, properties },\n    RESOLVE_BLOCK_WORK_INSTRUMENTATION,\n  )\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport type { ResolveBlocksOutput } from '../contracts/resolveBlocksOutput.type'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport { RESOLVE_BLOCK_KIND, type ResolveBlockWorkTask } from './ResolveBlockWorkHandler'\n\nexport interface ResolveBlocksWorkProps {\n  readonly blocks: readonly ResolveBlockWorkTask[]\n  readonly step: Record<string, unknown>\n  readonly ancestors: readonly Record<string, unknown>[]\n}\n\nexport const RESOLVE_BLOCKS_KIND = 'resolve.blocks'\n\nexport const RESOLVE_BLOCKS_WORK_INSTRUMENTATION: WorkInstrumentation<ResolveBlocksWorkProps, ResolveBlocksOutput> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, ResolveBlocksWorkProps>) {\n    return traceBegin(ctx.props)\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\nexport const RESOLVE_BLOCKS_WORK_HANDLER: WorkHandler<'resolve.blocks', ResolveBlocksWorkProps> = {\n  kind: RESOLVE_BLOCKS_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, ResolveBlocksWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'concurrent',\n          children: ctx.props.blocks,\n        },\n      ],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, ResolveBlocksWorkProps>,\n    children: readonly CompletedWork[],\n  ): ResolveBlocksOutput {\n    const blocks = childOutputs(children, RESOLVE_BLOCK_KIND)\n\n    return { blocks, step: ctx.props.step, ancestors: ctx.props.ancestors }\n  },\n}\n\nfunction traceBegin(props: ResolveBlocksWorkProps): TraceSpanFields {\n  return {\n    blocks: props.blocks.length,\n  }\n}\n\nfunction traceComplete(output: ResolveBlocksOutput): TraceSpanFields {\n  return {\n    visibleBlocks: output.blocks.filter(block => block.properties.visibleWhen !== false).length,\n  }\n}\n\nexport function createResolveBlocksTask(\n  blocks: readonly ResolveBlockWorkTask[],\n  step: Record<string, unknown>,\n  ancestors: readonly Record<string, unknown>[],\n) {\n  return createWorkTask(\n    'resolve-blocks',\n    RESOLVE_BLOCKS_WORK_HANDLER,\n    { blocks, step, ancestors },\n    RESOLVE_BLOCKS_WORK_INSTRUMENTATION,\n  )\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledAccessHookResult } from '../contracts/hookLifecycle.type'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport type { HookStageResult } from '../contracts/HookStage.type'\nimport type { AccessHookNextWorkProps } from '../contracts/AccessLifecycleWork.type'\n\nconst ACCESS_HOOK_NEXT_KIND = 'access.hook.next'\n\nexport const ACCESS_HOOK_NEXT_WORK_INSTRUMENTATION: WorkInstrumentation<\n  AccessHookNextWorkProps,\n  HookStageResult<CompiledAccessHookResult>\n> = {\n  resolveTraceMetadataAtStart() {\n    return undefined\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\n/**\n * The terminal stage of an access hook: runs the hook's `next` function and maps its\n * outcome to the access result. Always terminal — it is the last stage, and a hook\n * that reaches `next` has executed, so `next` decides the hook's outcome.\n */\nexport const ACCESS_HOOK_NEXT_WORK_HANDLER: WorkHandler<'access.hook.next', AccessHookNextWorkProps> = {\n  kind: ACCESS_HOOK_NEXT_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, AccessHookNextWorkProps>) {\n    const outcome = await ctx.props.next()\n\n    if (outcome?.type === 'redirect') {\n      return {\n        output: { status: 'terminal', result: { executed: true, outcome: 'redirect', redirect: outcome.value } },\n      }\n    }\n\n    if (outcome?.type === 'error') {\n      return {\n        output: {\n          status: 'terminal',\n          result: { executed: true, outcome: 'error', status: outcome.value.status, message: outcome.value.message },\n        },\n      }\n    }\n\n    return { output: { status: 'terminal', result: { executed: true, outcome: 'continue' } } }\n  },\n}\n\nfunction traceComplete(output: HookStageResult<CompiledAccessHookResult>): TraceSpanFields {\n  return output.status === 'terminal'\n    ? { executed: output.result.executed, outcome: output.result.outcome }\n    : { outcome: 'continue' }\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledAccessHookResult } from '../contracts/hookLifecycle.type'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkTask,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { createWorkTask, findTerminalStage, isTerminalStage } from '../../../chassis/work/workTask'\nimport { ACCESS_HOOK_NEXT_WORK_INSTRUMENTATION, ACCESS_HOOK_NEXT_WORK_HANDLER } from './AccessHookNextWorkHandler'\nimport type { AccessHookWorkProps } from '../contracts/AccessLifecycleWork.type'\n\nexport const ACCESS_HOOK_KIND = 'access.hook'\n\nexport const ACCESS_HOOK_WORK_INSTRUMENTATION: WorkInstrumentation<AccessHookWorkProps, CompiledAccessHookResult> = {\n  resolveTraceMetadataAtStart() {\n    return undefined\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\n/**\n * A single access hook as a fixed ordered stage list: when → effects → next, run as\n * one `first-match` group that stops at the first terminal stage. `when=false` ends\n * the hook before effects run; `next` is always terminal. The `next` function prop is\n * wrapped into a stage here so the compiler keeps emitting a plain props bag.\n */\nexport const ACCESS_HOOK_WORK_HANDLER: WorkHandler<'access.hook', AccessHookWorkProps> = {\n  kind: ACCESS_HOOK_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, AccessHookWorkProps>) {\n    const next = ctx.props.next\n\n    const stages: WorkTask[] = [\n      ...(ctx.props.when ? [ctx.props.when] : []),\n      ...(ctx.props.effects ?? []),\n      ...(next\n        ? [createWorkTask('next', ACCESS_HOOK_NEXT_WORK_HANDLER, { next }, ACCESS_HOOK_NEXT_WORK_INSTRUMENTATION)]\n        : []),\n    ]\n\n    return {\n      groups: [{ mode: 'first-match', matches: stage => isTerminalStage(stage.output), children: stages }],\n    }\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, AccessHookWorkProps>,\n    children: readonly CompletedWork[],\n  ): CompiledAccessHookResult {\n    return findTerminalStage<CompiledAccessHookResult>(children) ?? { executed: true, outcome: 'continue' }\n  },\n}\n\nfunction traceComplete(output: CompiledAccessHookResult): TraceSpanFields {\n  return {\n    executed: output.executed,\n    outcome: output.outcome,\n  }\n}\n\nexport function createAccessHookTask(key: string, props: AccessHookWorkProps) {\n  return createWorkTask(key, ACCESS_HOOK_WORK_HANDLER, props, ACCESS_HOOK_WORK_INSTRUMENTATION)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledAccessHookResult } from '../contracts/hookLifecycle.type'\nimport type { CompletedWork, WorkContextContract, WorkHandler } from '../../../chassis/contracts/work/work.type'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport { ACCESS_HOOK_KIND } from './AccessHookWorkHandler'\nimport type { AccessHookWorkTask, AccessLifecycleWorkProps } from '../contracts/AccessLifecycleWork.type'\n\nexport const ACCESS_LIFECYCLE_KIND = 'access.lifecycle'\n\nexport const ACCESS_LIFECYCLE_WORK_HANDLER: WorkHandler<'access.lifecycle', AccessLifecycleWorkProps> = {\n  kind: ACCESS_LIFECYCLE_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, AccessLifecycleWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'first-match',\n          matches: completedWork => isHaltingAccessResult(completedWork.output),\n          children: ctx.props.hooks,\n        },\n      ],\n    }\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, AccessLifecycleWorkProps>,\n    children: readonly CompletedWork[],\n  ): CompiledAccessHookResult {\n    const halting = childOutputs(children, ACCESS_HOOK_KIND).find(result => result.outcome !== 'continue')\n\n    return halting ?? { executed: true, outcome: 'continue' }\n  },\n}\n\nfunction isHaltingAccessResult(output: unknown): boolean {\n  return isAccessHookResult(output) && output.outcome !== 'continue'\n}\n\nfunction isAccessHookResult(output: unknown): output is CompiledAccessHookResult {\n  return output !== undefined &&\n    output !== null &&\n    typeof output === 'object' &&\n    'outcome' in output &&\n    typeof output.outcome === 'string'\n}\n\nexport function createAccessLifecycleTask(hooks: readonly AccessHookWorkTask[]) {\n  return createWorkTask('access-lifecycle', ACCESS_LIFECYCLE_WORK_HANDLER, { hooks })\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler } from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { AccessHookWhenWorkProps } from '../contracts/AccessLifecycleWork.type'\n\nconst ACCESS_HOOK_WHEN_KIND = 'access.hook.when'\n\nexport const ACCESS_HOOK_WHEN_WORK_HANDLER: WorkHandler<'access.hook.when', AccessHookWhenWorkProps> = {\n  kind: ACCESS_HOOK_WHEN_KIND,\n\n  // A false `when` ends the hook before its effects/next run.\n  async begin(ctx: WorkContextContract<RequestState, AccessHookWhenWorkProps>) {\n    if (await ctx.props.evaluate()) {\n      return { output: { status: 'continue' } }\n    }\n\n    return { output: { status: 'terminal', result: { executed: false, outcome: 'continue' } } }\n  },\n}\n\nexport function createAccessHookWhenTask(key: string, props: AccessHookWhenWorkProps) {\n  return createWorkTask(key, ACCESS_HOOK_WHEN_WORK_HANDLER, props)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { HookStageResult } from '../contracts/HookStage.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { HookEffectWorkProps } from '../contracts/HookEffectWork.type'\n\nconst HOOK_EFFECT_KIND = 'hook.effect'\n\nexport const HOOK_EFFECT_WORK_INSTRUMENTATION: WorkInstrumentation<HookEffectWorkProps, HookStageResult<never>> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, HookEffectWorkProps>) {\n    return { name: ctx.props.name }\n  },\n\n  resolveTraceMetadataAtFinish() {\n    return undefined\n  },\n}\n\nexport const HOOK_EFFECT_WORK_HANDLER: WorkHandler<'hook.effect', HookEffectWorkProps> = {\n  kind: HOOK_EFFECT_KIND,\n\n  // An effect runs for its side effect and always continues — it never ends a hook.\n  async begin(ctx: WorkContextContract<RequestState, HookEffectWorkProps>) {\n    await ctx.props.run()\n\n    return { output: { status: 'continue' } }\n  },\n}\n\nexport function createHookEffectTask(key: string, props: HookEffectWorkProps) {\n  return createWorkTask(key, HOOK_EFFECT_WORK_HANDLER, props, HOOK_EFFECT_WORK_INSTRUMENTATION)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledSubmitHookResult } from '../contracts/hookLifecycle.type'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkTask,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { createWorkTask, findChildByTask, findTerminalStage, isTerminalStage } from '../../../chassis/work/workTask'\nimport type { SubmitHookWorkProps } from '../contracts/SubmitLifecycleWork.type'\n\nexport const SUBMIT_HOOK_KIND = 'submit.hook'\n\nexport const SUBMIT_HOOK_WORK_INSTRUMENTATION: WorkInstrumentation<SubmitHookWorkProps, CompiledSubmitHookResult> = {\n  resolveTraceMetadataAtStart() {\n    return undefined\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return traceComplete(output)\n  },\n}\n\n/**\n * A single submit hook as a fixed ordered stage list: when → guards → onAlways →\n * validation → onValid → onInvalid (configured stages only), run as one `first-match`\n * group that stops at the first stage to produce a terminal result. The validation\n * stage is the validation-owned `validation.current-step` task, scheduled here so it\n * runs after `onAlways` exactly once; the hook owns only its position. `complete` is\n * a pure fold: return the terminal stage's result, or the \"ran to completion\"\n * default with validity read off the stored current-page result.\n */\nexport const SUBMIT_HOOK_WORK_HANDLER: WorkHandler<'submit.hook', SubmitHookWorkProps> = {\n  kind: SUBMIT_HOOK_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, SubmitHookWorkProps>) {\n    const stages: WorkTask[] = [\n      ...(ctx.props.when ? [ctx.props.when] : []),\n      ...(ctx.props.guards ? [ctx.props.guards] : []),\n      ...(ctx.props.onAlways ? [ctx.props.onAlways] : []),\n      ...(ctx.props.validation ? [ctx.props.validation] : []),\n      ...(ctx.props.onValid ? [ctx.props.onValid] : []),\n      ...(ctx.props.onInvalid ? [ctx.props.onInvalid] : []),\n    ]\n\n    return {\n      groups: [{ mode: 'first-match', matches: stage => isTerminalStage(stage.output), children: stages }],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, SubmitHookWorkProps>,\n    children: readonly CompletedWork[],\n  ): CompiledSubmitHookResult {\n    const terminal = findTerminalStage<CompiledSubmitHookResult>(children)\n\n    if (terminal !== undefined) {\n      return terminal\n    }\n\n    const ranValidation =\n      ctx.props.validation !== undefined && findChildByTask(children, ctx.props.validation) !== undefined\n\n    if (!ranValidation) {\n      return { executed: true, validated: false, outcome: 'continue' }\n    }\n\n    const isValid = ctx.state.currentPageValidation?.isValid ?? true\n\n    return { executed: true, validated: true, isValid, outcome: 'continue' }\n  },\n}\n\nfunction traceComplete(output: CompiledSubmitHookResult): TraceSpanFields {\n  return {\n    executed: output.executed,\n    validated: output.validated,\n    isValid: output.isValid,\n    outcome: output.outcome,\n  }\n}\n\nexport function createSubmitHookTask(key: string, props: SubmitHookWorkProps) {\n  return createWorkTask(key, SUBMIT_HOOK_WORK_HANDLER, props, SUBMIT_HOOK_WORK_INSTRUMENTATION)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledSubmitHookResult } from '../contracts/hookLifecycle.type'\nimport type { CompletedWork, WorkContextContract, WorkHandler } from '../../../chassis/contracts/work/work.type'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport { SUBMIT_HOOK_KIND } from './SubmitHookWorkHandler'\nimport type { SubmitHookWorkTask, SubmitLifecycleWorkProps } from '../contracts/SubmitLifecycleWork.type'\n\nexport const SUBMIT_LIFECYCLE_KIND = 'submit.lifecycle'\n\nexport const SUBMIT_LIFECYCLE_WORK_HANDLER: WorkHandler<'submit.lifecycle', SubmitLifecycleWorkProps> = {\n  kind: SUBMIT_LIFECYCLE_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, SubmitLifecycleWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'first-match',\n          matches: completedWork => isExecutedSubmitResult(completedWork.output),\n          children: ctx.props.hooks,\n        },\n      ],\n    }\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, SubmitLifecycleWorkProps>,\n    children: readonly CompletedWork[],\n  ): CompiledSubmitHookResult {\n    const executed = childOutputs(children, SUBMIT_HOOK_KIND).find(result => result.executed)\n\n    return executed ?? { executed: false, validated: false, outcome: 'continue' }\n  },\n}\n\nfunction isExecutedSubmitResult(output: unknown): boolean {\n  return isSubmitHookResult(output) && output.executed\n}\n\nfunction isSubmitHookResult(output: unknown): output is CompiledSubmitHookResult {\n  return output !== undefined &&\n    output !== null &&\n    typeof output === 'object' &&\n    'executed' in output &&\n    typeof output.executed === 'boolean'\n}\n\nexport function createSubmitLifecycleTask(hooks: readonly SubmitHookWorkTask[]) {\n  return createWorkTask('submit-lifecycle', SUBMIT_LIFECYCLE_WORK_HANDLER, { hooks })\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { CompiledSubmitHookResult } from '../contracts/hookLifecycle.type'\nimport type { HookStageResult } from '../contracts/HookStage.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { SubmitHookPredicateWorkProps } from '../contracts/SubmitLifecycleWork.type'\n\nconst SUBMIT_HOOK_PREDICATE_KIND = 'submit.predicate'\n\nexport const SUBMIT_HOOK_PREDICATE_WORK_INSTRUMENTATION: WorkInstrumentation<\n  SubmitHookPredicateWorkProps,\n  HookStageResult<CompiledSubmitHookResult>\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, SubmitHookPredicateWorkProps>) {\n    return { name: ctx.props.name }\n  },\n\n  resolveTraceMetadataAtFinish(_ctx, output) {\n    return { passed: output.status === 'continue' }\n  },\n}\n\nexport const SUBMIT_HOOK_PREDICATE_WORK_HANDLER: WorkHandler<'submit.predicate', SubmitHookPredicateWorkProps> = {\n  kind: SUBMIT_HOOK_PREDICATE_KIND,\n\n  // A failed predicate (when/guards) ends the hook: it owns the \"not executed\" result.\n  async begin(ctx: WorkContextContract<RequestState, SubmitHookPredicateWorkProps>) {\n    if (await ctx.props.evaluate()) {\n      return { output: { status: 'continue' } }\n    }\n\n    return { output: { status: 'terminal', result: { executed: false, validated: false, outcome: 'continue' } } }\n  },\n}\n\nexport function createSubmitPredicateTask(key: string, props: SubmitHookPredicateWorkProps) {\n  return createWorkTask(key, SUBMIT_HOOK_PREDICATE_WORK_HANDLER, props, SUBMIT_HOOK_PREDICATE_WORK_INSTRUMENTATION)\n}\n","import type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { CompiledSubmitHookResult } from '../contracts/hookLifecycle.type'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type { HookStageResult } from '../contracts/HookStage.type'\nimport type {\n  SubmitBranchName,\n  SubmitBranchWorkProps,\n  SubmitHookNextResult,\n} from '../contracts/SubmitLifecycleWork.type'\n\nconst SUBMIT_BRANCH_KIND = 'submit.branch'\n\nexport const SUBMIT_BRANCH_WORK_INSTRUMENTATION: WorkInstrumentation<\n  SubmitBranchWorkProps,\n  HookStageResult<CompiledSubmitHookResult>\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, SubmitBranchWorkProps>) {\n    return { name: ctx.props.name }\n  },\n\n  resolveTraceMetadataAtFinish(ctx, output) {\n    return traceComplete(ctx.props, output)\n  },\n}\n\n/**\n * A submit hook branch (`onAlways`, `onValid`, or `onInvalid`). It self-gates on its\n * name and the stored current-page validity: `onAlways` always runs; `onValid` runs\n * only when valid, `onInvalid` only when invalid. An unselected branch runs no effects,\n * continues, and drops its own (empty) trace unit. A selected branch runs its effects\n * then `next()`, ending the hook on a redirect/error and otherwise continuing.\n */\nexport const SUBMIT_BRANCH_WORK_HANDLER: WorkHandler<'submit.branch', SubmitBranchWorkProps> = {\n  kind: SUBMIT_BRANCH_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, SubmitBranchWorkProps>) {\n    if (!isSelected(ctx.props.name, currentStepValid(ctx))) {\n      return { groups: [] }\n    }\n\n    return { groups: [{ mode: 'sequential', children: ctx.props.effects ?? [] }] }\n  },\n\n  async complete(\n    ctx: WorkContextContract<RequestState, SubmitBranchWorkProps>,\n    _children: readonly CompletedWork[],\n  ): Promise<HookStageResult<CompiledSubmitHookResult>> {\n    if (!isSelected(ctx.props.name, currentStepValid(ctx))) {\n      ctx.omitFromTrace?.()\n\n      return { status: 'continue' }\n    }\n\n    const result = toSubmitResult(await ctx.props.next?.(), ctx.props.name)\n\n    return result === undefined ? { status: 'continue' } : { status: 'terminal', result }\n  },\n}\n\nfunction currentStepValid(ctx: WorkContextContract<RequestState, SubmitBranchWorkProps>): boolean {\n  return ctx.state.currentPageValidation?.isValid ?? true\n}\n\nfunction isSelected(name: SubmitBranchName, isValid: boolean): boolean {\n  if (name === 'onAlways') {\n    return true\n  }\n\n  return name === 'onValid' ? isValid : !isValid\n}\n\nfunction toSubmitResult(outcome: SubmitHookNextResult, name: SubmitBranchName): CompiledSubmitHookResult | undefined {\n  const validatedPart = name === 'onAlways' ? { validated: false } : { validated: true, isValid: name === 'onValid' }\n\n  if (outcome?.type === 'redirect') {\n    return { executed: true, ...validatedPart, outcome: 'redirect', redirect: outcome.value }\n  }\n\n  if (outcome?.type === 'error') {\n    return {\n      executed: true,\n      ...validatedPart,\n      outcome: 'error',\n      status: outcome.value.status,\n      message: outcome.value.message,\n    }\n  }\n\n  return undefined\n}\n\nfunction traceComplete(\n  props: SubmitBranchWorkProps,\n  output: HookStageResult<CompiledSubmitHookResult>,\n): TraceSpanFields {\n  return {\n    name: props.name,\n    outcome: output.status === 'terminal' ? output.result.outcome : 'continue',\n  }\n}\n\nexport function createSubmitBranchTask(key: string, props: SubmitBranchWorkProps) {\n  return createWorkTask(key, SUBMIT_BRANCH_WORK_HANDLER, props, SUBMIT_BRANCH_WORK_INSTRUMENTATION)\n}\n","import ForgeBaseError from './ForgeBaseError'\n\nexport default class ForgeIteratorBudgetExceededError extends ForgeBaseError {\n  constructor(maxIterations: number) {\n    super(`Forge iterator evaluation exceeded the per-request limit of ${maxIterations} iterations`)\n  }\n}\n","import ForgeIteratorBudgetExceededError from '../../../errors/ForgeIteratorBudgetExceededError'\nimport type { IteratorBudgetContract } from '../../contracts/runtime/iteratorBudget.type'\n\nexport const DEFAULT_MAX_ITERATOR_ITERATIONS = 10_000\n\nexport default class IteratorBudget implements IteratorBudgetContract {\n  private consumedIterations = 0\n\n  constructor(private readonly maxIterations: number = DEFAULT_MAX_ITERATOR_ITERATIONS) {\n    if (!Number.isSafeInteger(maxIterations) || maxIterations < 1) {\n      throw new TypeError('maxIteratorIterations must be a positive integer')\n    }\n  }\n\n  consume(): void {\n    this.consumedIterations += 1\n\n    if (this.consumedIterations > this.maxIterations) {\n      throw new ForgeIteratorBudgetExceededError(this.maxIterations)\n    }\n  }\n}\n","import type { ResponseBindings } from '../../../../framework/types/responseBindings.type'\nimport type {\n  CompiledAnswerPreparationContext,\n  CompiledBaseContext,\n  CompiledReachabilityContext,\n  CompiledResolveContext,\n  CompiledRouteMetadataContext,\n  CompiledValidationContext,\n} from '../../contracts/compiled/compiledContexts.type'\nimport type { CompiledHookLifecycleContext } from '../../../concerns/hooks/contracts/hookLifecycle.type'\nimport type { ValidationResult } from '../../../concerns/validation/contracts/validationResult.type'\nimport type { HookType } from '../../contracts/runtime/answerHistory.type'\nimport type { ComponentRegistry } from '../../../../framework/types/adapter.type'\nimport FunctionRegistry from '../../registries/FunctionRegistry'\nimport type { RuntimeContext } from '../../contracts/runtime/evaluationState.type'\nimport EffectFunctionContextImpl from './EffectFunctionContext'\nimport { createAnswerPreparationTask } from '../../../concerns/answer-preparation/runtime/AnswerPreparationWorkHandler'\nimport { createFieldAnswerPreparationTask } from '../../../concerns/answer-preparation/runtime/FieldAnswerPreparationWorkHandler'\nimport { createStepValidationTask } from '../../../concerns/validation/runtime/StepValidationWorkHandler'\nimport { createFieldValidationTask } from '../../../concerns/validation/runtime/FieldValidationWorkHandler'\nimport { createDomainValidationTask } from '../../../concerns/validation/runtime/DomainValidationWorkHandler'\nimport { createCurrentStepValidationTask } from '../../../concerns/validation/runtime/CurrentStepValidationWorkHandler'\nimport { createResolveBlockTask } from '../../../concerns/resolve/runtime/ResolveBlockWorkHandler'\nimport { createResolveBlocksTask } from '../../../concerns/resolve/runtime/ResolveBlocksWorkHandler'\nimport { createAccessLifecycleTask } from '../../../concerns/hooks/runtime/AccessLifecycleWorkHandler'\nimport { createAccessHookTask } from '../../../concerns/hooks/runtime/AccessHookWorkHandler'\nimport { createAccessHookWhenTask } from '../../../concerns/hooks/runtime/AccessHookWhenWorkHandler'\nimport { createHookEffectTask } from '../../../concerns/hooks/runtime/HookEffectWorkHandler'\nimport { createSubmitLifecycleTask } from '../../../concerns/hooks/runtime/SubmitLifecycleWorkHandler'\nimport { createSubmitHookTask } from '../../../concerns/hooks/runtime/SubmitHookWorkHandler'\nimport { createSubmitPredicateTask } from '../../../concerns/hooks/runtime/SubmitHookPredicateWorkHandler'\nimport { createSubmitBranchTask } from '../../../concerns/hooks/runtime/SubmitBranchWorkHandler'\nimport IteratorBudget from '../pipeline/IteratorBudget'\nimport type { IteratorBudgetContract } from '../../contracts/runtime/iteratorBudget.type'\n\n/**\n * The task-construction surface handed to generated functions as `ctx.workTasks`.\n * Generated source calls these by property name, so the names are part of the\n * codegen contract and must not change without changing the emitters.\n */\nexport const workTaskBuilders = {\n  answerPreparation: createAnswerPreparationTask,\n  fieldAnswerPreparation: createFieldAnswerPreparationTask,\n  stepValidation: createStepValidationTask,\n  fieldValidation: createFieldValidationTask,\n  domainValidation: createDomainValidationTask,\n  currentStepValidation: createCurrentStepValidationTask,\n  resolveBlock: createResolveBlockTask,\n  resolveBlocks: createResolveBlocksTask,\n  accessLifecycle: createAccessLifecycleTask,\n  accessHook: createAccessHookTask,\n  accessHookWhen: createAccessHookWhenTask,\n  hookEffect: createHookEffectTask,\n  submitLifecycle: createSubmitLifecycleTask,\n  submitHook: createSubmitHookTask,\n  submitPredicate: createSubmitPredicateTask,\n  submitBranch: createSubmitBranchTask,\n}\n\n/**\n * Compiled functions deliberately receive a small serialisable-ish snapshot of\n * request state instead of the full RuntimeContext. That keeps the\n * generated-function boundary explicit and prevents controller-specific objects\n * leaking into codegen as the compiler surface changes.\n */\nfunction buildCompiledBaseContext(context: RuntimeContext, functionRegistry: FunctionRegistry): CompiledBaseContext {\n  return {\n    iteratorBudget: resolveIteratorBudget(context),\n    answers: context.domain.answers,\n    data: context.domain.data,\n    session: context.request.session,\n    params: context.request.params,\n    query: context.request.query,\n    post: context.request.post,\n    request: { ...context.request },\n    conditions: functionRegistry,\n    workTasks: workTaskBuilders,\n  }\n}\n\nfunction resolveIteratorBudget(context: RuntimeContext): IteratorBudgetContract {\n  context.evaluation.iteratorBudget ??= new IteratorBudget()\n\n  return context.evaluation.iteratorBudget\n}\n\nexport function buildCompiledAnswerPreparationContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n  componentRegistry: ComponentRegistry,\n): CompiledAnswerPreparationContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n    answers: context.domain.answers,\n    components: componentRegistry,\n  }\n}\n\nexport function buildCompiledResolveContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n  componentRegistry: ComponentRegistry,\n  fieldFailures: Record<string, ValidationResult[]>,\n  fieldFailureAnchors: Record<string, string>,\n): CompiledResolveContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n    fieldFailures,\n    fieldFailureAnchors,\n    components: componentRegistry,\n  }\n}\n\nexport function buildCompiledValidationContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n): CompiledValidationContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n  }\n}\n\nexport function buildCompiledReachabilityContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n): CompiledReachabilityContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n  }\n}\n\nexport function buildCompiledRouteMetadataContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n): CompiledRouteMetadataContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n  }\n}\n\nexport function buildCompiledHookLifecycleContext(\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n  hookType: HookType,\n  responseBindings: ResponseBindings,\n): CompiledHookLifecycleContext {\n  return {\n    ...buildCompiledBaseContext(context, functionRegistry),\n    answers: context.domain.answers,\n    effectFunctionContext: new EffectFunctionContextImpl(context, responseBindings, hookType),\n  }\n}\n","import type { CompiledValidationFunction } from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport type { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport type FunctionRegistry from '../../../chassis/registries/FunctionRegistry'\nimport type { RuntimeContext } from '../../../chassis/contracts/runtime/evaluationState.type'\nimport { buildCompiledValidationContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { createWorkTask, isWorkTask } from '../../../chassis/work/workTask'\nimport type { StepValidationWorkTask, ValidationRuleFilter } from '../contracts/ValidationWork.type'\nimport { STEP_VALIDATION_WORK_HANDLER } from './StepValidationWorkHandler'\n\n/**\n * The work task key a step's validation task is built under. The step id\n * is encoded into the key so the reachability validities phase can map each\n * completed child back to its step in `complete` without a per-unit side-channel.\n */\nexport function validationTaskKey(stepId: NodeId): string {\n  return `validation:${stepId}`\n}\n\n/**\n * Builds (without executing) a step's validation task, re-keyed to the\n * step so callers can tell sibling step validations apart. Callers run it\n * through the main executor — the reachability validities phase as concurrent\n * children, current-step validation as a single discovered child — so there is\n * no nested executor. The filter selects which rules the run executes; the\n * compiled function applies it before evaluating any rule condition. Returns\n * undefined when the step has no compiled validation.\n */\nexport async function buildStepValidationTask(\n  compiledValidation: CompiledValidationFunction | undefined,\n  stepId: NodeId,\n  context: RuntimeContext,\n  functionRegistry: FunctionRegistry,\n  filter: ValidationRuleFilter,\n): Promise<StepValidationWorkTask | undefined> {\n  if (!compiledValidation) {\n    return undefined\n  }\n\n  const validationContext = buildCompiledValidationContext(context, functionRegistry)\n  const task = await compiledValidation(validationContext, filter)\n\n  if (!isStepValidationWorkTask(task)) {\n    return undefined\n  }\n\n  return createWorkTask(validationTaskKey(stepId), task.handler, task.props, task.instrumentation)\n}\n\nfunction isStepValidationWorkTask(value: unknown): value is StepValidationWorkTask {\n  return isWorkTask(value) && value.handler === STEP_VALIDATION_WORK_HANDLER\n}\n","import type { NodeId } from '../../contracts/ast/ast.type'\nimport type { ReachabilityEvaluation } from '../../../concerns/reachability/contracts/reachabilityEvaluation.type'\nimport type { ValidationView } from '../../../concerns/validation/contracts/validationView.type'\nimport type FunctionRegistry from '../../registries/FunctionRegistry'\nimport type { RuntimeContext } from '../../contracts/runtime/evaluationState.type'\nimport type { ResponseBindings } from '../../../../framework/types/responseBindings.type'\nimport type { ComponentRegistry } from '../../../../framework/types/adapter.type'\nimport type { RenderContext } from '../../../../framework/types/rendering.type'\nimport type { RouteTree } from '../../../../framework/types/routeTree.type'\nimport type { RequestPipelineResult } from '../../contracts/runtime/requestPipelineOutput.type'\nimport type {\n  StepValidationWorkTask,\n  ValidationRuleFilter,\n} from '../../../concerns/validation/contracts/ValidationWork.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\ntype StepValidationTaskResult = StepValidationWorkTask | undefined\n\nexport interface RequestDependencies {\n  readonly responseBindings: ResponseBindings\n  readonly functionRegistry: FunctionRegistry\n  readonly componentRegistry: ComponentRegistry\n  readonly currentStepId?: NodeId\n  readonly hasRenderer: boolean\n  readonly traceEnabled: boolean\n  readonly buildStepValidation: (\n    stepId: NodeId,\n    filter: ValidationRuleFilter,\n  ) => StepValidationTaskResult | Promise<StepValidationTaskResult>\n}\n\n/**\n * The state the request phases build up, one phase at a time: reachability\n * records its evaluation, route-tree records the hydrated tree, validation\n * records the current-page view, resolve records the render context, render\n * records the rendered blocks, and the pipeline records its resolved result.\n * A getter throws only where every reader runs after the writer — the\n * first-match pipeline legitimately halts early, so most values stay optional.\n */\nexport default class RequestState {\n  /**\n   * Document anchors for failing field blocks, keyed by render block ID.\n   * Written during block resolution (each failing field records its `idPrefix`\n   * or code) and read back when the resolve phase assembles the render\n   * context's field validation errors. The record is handed to compiled\n   * resolve contexts by identity and mutated in place.\n   */\n  readonly fieldFailureAnchors: Record<string, string> = {}\n\n  private mutableReachabilityEvaluation?: ReachabilityEvaluation\n\n  private mutableRouteTree?: RouteTree\n\n  private mutableCurrentPageValidation?: ValidationView\n\n  private mutableRenderContext?: RenderContext\n\n  private mutableRenderedBlocks?: readonly unknown[]\n\n  private mutablePipelineResult?: RequestPipelineResult\n\n  constructor(\n    readonly context: RuntimeContext,\n    readonly dependencies: RequestDependencies,\n  ) {}\n\n  get renderContext(): RenderContext {\n    if (this.mutableRenderContext === undefined) {\n      throw new ForgeInternalError('Render phase reached without a render context - resolve phase did not produce one')\n    }\n\n    return this.mutableRenderContext\n  }\n\n  get pipelineResult(): RequestPipelineResult {\n    if (this.mutablePipelineResult === undefined) {\n      throw new ForgeInternalError('Request pipeline completed without a result')\n    }\n\n    return this.mutablePipelineResult\n  }\n\n  /** Undefined until reachability has run - journey halts and error traces read it early. */\n  get reachabilityEvaluation(): ReachabilityEvaluation | undefined {\n    return this.mutableReachabilityEvaluation\n  }\n\n  /** Undefined until the route-tree phase has run - earlier halts and error traces read it early. */\n  get routeTree(): RouteTree | undefined {\n    return this.mutableRouteTree\n  }\n\n  /**\n   * The result of the current-page validation round, written only by the\n   * `validation.current-step` work handler. Its presence is the display signal:\n   * present means current-page validation ran and should be surfaced (a present\n   * result may be valid and carry no failures); absent means it never ran.\n   */\n  get currentPageValidation(): ValidationView | undefined {\n    return this.mutableCurrentPageValidation\n  }\n\n  get renderedBlocks(): readonly unknown[] | undefined {\n    return this.mutableRenderedBlocks\n  }\n\n  recordReachabilityEvaluation(evaluation: ReachabilityEvaluation): void {\n    this.mutableReachabilityEvaluation = evaluation\n  }\n\n  recordRouteTree(routeTree: RouteTree): void {\n    this.mutableRouteTree = routeTree\n  }\n\n  recordCurrentPageValidation(view: ValidationView): void {\n    this.mutableCurrentPageValidation = view\n  }\n\n  recordRenderContext(renderContext: RenderContext): void {\n    this.mutableRenderContext = renderContext\n  }\n\n  recordRenderedBlocks(renderedBlocks: readonly unknown[]): void {\n    this.mutableRenderedBlocks = renderedBlocks\n  }\n\n  recordPipelineResult(result: RequestPipelineResult): void {\n    this.mutablePipelineResult = result\n  }\n}\n","import ForgeInternalError from '../../../errors/ForgeInternalError'\nimport type { CompletedWork, WorkContextContract, WorkHandler } from '../../contracts/work/work.type'\nimport { createWorkTask } from '../../work/workTask'\nimport type { RequestPipelineWorkProps } from '../../contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from './RequestState'\nimport type { PhaseWorkOutput, RequestPipelineResult } from '../../contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_PIPELINE_KIND = 'request.pipeline'\n\n/**\n * The whole request as one work handler. `begin` runs the route's ordered phases as a\n * single sequential first-match group — the drain halts on the first phase that\n * redirects, errors, or renders. `complete` reads the phase outputs to produce the\n * resolved outcome: the halting phase's redirect/error, or the render context.\n */\nexport const REQUEST_PIPELINE_WORK_HANDLER: WorkHandler<'request.pipeline', RequestPipelineWorkProps> = {\n  kind: REQUEST_PIPELINE_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RequestPipelineWorkProps>) {\n    return {\n      groups: [\n        {\n          mode: 'first-match',\n          matches: child => isPhaseWorkOutput(child.output) && child.output.action !== 'continue',\n          children: [...ctx.props.phases],\n        },\n      ],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, RequestPipelineWorkProps>,\n    children: readonly CompletedWork[],\n  ): RequestPipelineResult {\n    const result = resolveResult(children)\n\n    ctx.state.recordPipelineResult(result)\n\n    return result\n  },\n}\n\nfunction resolveResult(children: readonly CompletedWork[]): RequestPipelineResult {\n  for (const child of children) {\n    const output = child.output\n\n    if (!isPhaseWorkOutput(output)) {\n      continue\n    }\n\n    if (output.action === 'halt-redirect') {\n      return { kind: 'redirect', target: output.target }\n    }\n\n    if (output.action === 'halt-error') {\n      return { kind: 'error', status: output.status, message: output.message }\n    }\n\n    if (output.action === 'render') {\n      return { kind: 'render', context: output.renderContext, output: output.output }\n    }\n  }\n\n  throw new ForgeInternalError('Request pipeline produced no terminal outcome')\n}\n\n// The pipeline's children are heterogeneous phases that all produce PhaseWorkOutput,\n// so the per-kind accessor doesn't apply; narrow the erased child output here.\nfunction isPhaseWorkOutput(value: unknown): value is PhaseWorkOutput {\n  return value !== null && typeof value === 'object' && 'action' in value\n}\n\nexport function createRequestPipelineTask(props: RequestPipelineWorkProps) {\n  return createWorkTask('request', REQUEST_PIPELINE_WORK_HANDLER, props)\n}\n","import type {\n  JourneyReachabilityProjection,\n  StepReachabilityProjection,\n} from '../../../concerns/reachability/contracts/journeyReachabilityProjection.type'\nimport type { AnswerHistory, AnswerMutation } from '../../contracts/runtime/answerHistory.type'\nimport type {\n  DomainValidationFailure,\n  StepValidationFailure,\n  RuntimeContext,\n} from '../../contracts/runtime/evaluationState.type'\nimport type { NodeId } from '../../contracts/ast/ast.type'\nimport type { StepValidityResult } from '../../../concerns/validation/contracts/stepValidityResult.type'\nimport type { WorkContextContract, WorkInstrumentation } from '../../contracts/work/work.type'\nimport type { PhaseWorkOutput } from '../../contracts/runtime/requestPipelineOutput.type'\nimport type RequestState from './RequestState'\n\n/**\n * A deep-cloned, point-in-time copy of the request's runtime evaluation state.\n * Captured by each phase's `resolveTraceMetadataAtFinish` instrumentation when its work unit completes, so\n * the value is frozen at that phase and unaffected by later mutations. The trace\n * projection wraps it into a `context-snapshot` `RequestTraceUnit`.\n */\nexport type ContextSnapshotData = {\n  readonly answers: Record<string, AnswerHistory>\n  readonly data: Record<string, unknown>\n  readonly reachabilityValidities?: Record<NodeId, StepValidityResult>\n  readonly reachability?: JourneyReachabilityProjection\n}\n\nexport function captureContextSnapshot(context: RuntimeContext): ContextSnapshotData {\n  return {\n    answers: cloneAnswers(context.domain.answers),\n    data: cloneRecord(context.domain.data),\n    reachabilityValidities: cloneReachabilityValidities(context.evaluation.reachabilityValidities),\n    reachability: cloneReachability(context.evaluation.reachability),\n  }\n}\n\n/**\n * The shared after-phase instrumentation: every request phase snapshots the\n * request context on completion. A generic function rather than a const because\n * `WorkInstrumentation` ties the ctx to the phase's props.\n */\nexport function phaseInstrumentation<TProps>(): WorkInstrumentation<TProps, PhaseWorkOutput> {\n  return {\n    resolveTraceMetadataAtStart() {\n      return undefined\n    },\n\n    resolveTraceMetadataAtFinish(ctx: WorkContextContract<RequestState, TProps>) {\n      return captureContextSnapshot(ctx.state.context)\n    },\n  }\n}\n\nfunction cloneAnswers(answers: Record<string, AnswerHistory>): Record<string, AnswerHistory> {\n  return Object.entries(answers).reduce<Record<string, AnswerHistory>>((clonedAnswers, [key, history]) => {\n    clonedAnswers[key] = {\n      current: cloneValue(history.current),\n      parsed: history.parsed === undefined ? undefined : cloneValue(history.parsed),\n      mutations: history.mutations.map(mutation => cloneAnswerMutation(mutation)),\n    }\n\n    return clonedAnswers\n  }, {})\n}\n\nfunction cloneAnswerMutation(mutation: AnswerMutation): AnswerMutation {\n  return {\n    value: cloneValue(mutation.value),\n    source: mutation.source,\n  }\n}\n\nfunction cloneRecord(record: Record<string, unknown>): Record<string, unknown> {\n  return Object.entries(record).reduce<Record<string, unknown>>((clonedRecord, [key, value]) => {\n    clonedRecord[key] = cloneValue(value)\n\n    return clonedRecord\n  }, {})\n}\n\nfunction cloneReachabilityValidities(\n  reachabilityValidities: ReadonlyMap<NodeId, StepValidityResult> | undefined,\n): Record<NodeId, StepValidityResult> | undefined {\n  if (reachabilityValidities === undefined) {\n    return undefined\n  }\n\n  const cloned: Record<NodeId, StepValidityResult> = {}\n\n  reachabilityValidities.forEach((validity, stepId) => {\n    cloned[stepId] = {\n      fieldFailures: validity.fieldFailures.map(failure => cloneStepValidationFailure(failure)),\n      domainFailures: validity.domainFailures.map(failure => cloneDomainValidationFailure(failure)),\n    }\n  })\n\n  return cloned\n}\n\nfunction cloneStepValidationFailure(failure: StepValidationFailure): StepValidationFailure {\n  return {\n    ...cloneDomainValidationFailure(failure),\n    blockId: failure.blockId,\n  }\n}\n\nfunction cloneDomainValidationFailure(failure: DomainValidationFailure): DomainValidationFailure {\n  return {\n    passed: failure.passed,\n    message: failure.message,\n    submissionOnly: failure.submissionOnly,\n    groups: [...failure.groups],\n    details: failure.details === undefined ? undefined : cloneRecord(failure.details),\n    blockCode: failure.blockCode,\n  }\n}\n\nfunction cloneReachability(\n  reachability: JourneyReachabilityProjection | undefined,\n): JourneyReachabilityProjection | undefined {\n  if (reachability === undefined) {\n    return undefined\n  }\n\n  return {\n    reachableSteps: reachability.reachableSteps.map(step => cloneStepReachabilityProjection(step)),\n    unreachableSteps: reachability.unreachableSteps.map(step => cloneStepReachabilityProjection(step)),\n  }\n}\n\nfunction cloneStepReachabilityProjection(step: StepReachabilityProjection): StepReachabilityProjection {\n  return {\n    path: step.path,\n    code: step.code,\n    fieldCodes: step.fieldCodes === undefined ? undefined : [...step.fieldCodes],\n    cleardownFieldCodes: step.cleardownFieldCodes === undefined ? undefined : [...step.cleardownFieldCodes],\n    backPath: step.backPath,\n  }\n}\n\nfunction cloneValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map(item => cloneValue(item))\n  }\n\n  if (isRecord(value)) {\n    return cloneRecord(value)\n  }\n\n  return value\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value)\n}\n","import type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../contracts/work/work.type'\nimport { phaseInstrumentation } from './contextSnapshot'\nimport { createWorkTask } from '../../work/workTask'\nimport type { RequestContextPreparationWorkProps } from '../../contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from './RequestState'\nimport type { PhaseWorkOutput } from '../../contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_CONTEXT_PREPARATION_KIND = 'request.context-preparation'\n\nexport const REQUEST_CONTEXT_PREPARATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestContextPreparationWorkProps,\n  PhaseWorkOutput\n> = phaseInstrumentation()\n\nexport const REQUEST_CONTEXT_PREPARATION_WORK_HANDLER: WorkHandler<\n  'request.context-preparation',\n  RequestContextPreparationWorkProps\n> = {\n  kind: REQUEST_CONTEXT_PREPARATION_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RequestContextPreparationWorkProps>) {\n    const context = ctx.state.context\n    const snapshot = ctx.props.snapshot\n    const staticData = ctx.props.compiledStaticData()\n\n    Object.assign(context.domain.data, staticData)\n\n    context.request = {\n      url: snapshot.location.href,\n      path: snapshot.location.pathname,\n      method: snapshot.method,\n      location: snapshot.location,\n      headers: snapshot.headers,\n      cookies: snapshot.cookies,\n      state: snapshot.state,\n      params: snapshot.params,\n      query: snapshot.query,\n      post: snapshot.post,\n      session: (snapshot.session ?? {}) as Record<string, unknown>,\n    }\n\n    return { output: { action: 'continue' as const } }\n  },\n}\n\nexport function createRequestContextPreparationTask(props: RequestContextPreparationWorkProps) {\n  return createWorkTask(\n    'context-preparation',\n    REQUEST_CONTEXT_PREPARATION_WORK_HANDLER,\n    props,\n    REQUEST_CONTEXT_PREPARATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type { CompiledAccessHookResult } from '../contracts/hookLifecycle.type'\nimport { buildCompiledHookLifecycleContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { ACCESS_LIFECYCLE_KIND } from './AccessLifecycleWorkHandler'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, isWorkTaskOfKind, singleChildOutput, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestAccessWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nconst REQUEST_ACCESS_KIND = 'request.access'\n\nexport const REQUEST_ACCESS_WORK_INSTRUMENTATION: WorkInstrumentation<RequestAccessWorkProps, PhaseWorkOutput> =\n  phaseInstrumentation()\n\n/**\n * The access phase as work. `begin` builds the hook lifecycle context locally and\n * runs the compiled access task as its child; `complete` maps the access\n * result to a halt or continue.\n */\nexport const REQUEST_ACCESS_WORK_HANDLER: WorkHandler<'request.access', RequestAccessWorkProps> = {\n  kind: REQUEST_ACCESS_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestAccessWorkProps>) {\n    const hookLifecycleContext = buildCompiledHookLifecycleContext(\n      ctx.state.context,\n      ctx.state.dependencies.functionRegistry,\n      'access',\n      ctx.state.dependencies.responseBindings,\n    )\n\n    const resolved = await ctx.props.compiled(hookLifecycleContext)\n\n    if (!isWorkTaskOfKind(resolved, ACCESS_LIFECYCLE_KIND)) {\n      throw new ForgeInternalError('Compiled access lifecycle returned an invalid work task')\n    }\n\n    return singleTaskGroup(resolved)\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, RequestAccessWorkProps>,\n    children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    const result = singleChildOutput(children, ACCESS_LIFECYCLE_KIND)\n\n    if (result === undefined) {\n      throw new ForgeInternalError('Access lifecycle work task completed with an invalid access result')\n    }\n\n    const output = toOutput(result)\n\n    return output\n  },\n}\n\nfunction toOutput(result: CompiledAccessHookResult): PhaseWorkOutput {\n  if (result.outcome === 'redirect') {\n    if (result.redirect === undefined) {\n      throw new ForgeInternalError('Hook redirect target is missing')\n    }\n\n    return { action: 'halt-redirect', target: result.redirect, reason: 'access-lifecycle' }\n  }\n\n  if (result.outcome === 'error') {\n    return { action: 'halt-error', status: result.status ?? 500, message: result.message || 'Access denied' }\n  }\n\n  return { action: 'continue' }\n}\n\nexport function createRequestAccessTask(props: RequestAccessWorkProps) {\n  return createWorkTask('access', REQUEST_ACCESS_WORK_HANDLER, props, REQUEST_ACCESS_WORK_INSTRUMENTATION)\n}\n","import ForgeInternalError from '../../../errors/ForgeInternalError'\nimport { buildCompiledAnswerPreparationContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { ANSWER_PREPARATION_KIND } from './AnswerPreparationWorkHandler'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, isWorkTaskOfKind, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestAnswerPreparationWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_ANSWER_PREPARATION_KIND = 'request.answer-preparation'\n\nexport const REQUEST_ANSWER_PREPARATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestAnswerPreparationWorkProps,\n  PhaseWorkOutput\n> = phaseInstrumentation()\n\n/**\n * The answer-preparation phase as work. `begin` runs the compiled answer\n * preparation task (which mutates the answer store in place); `complete`\n * always continues.\n */\nexport const REQUEST_ANSWER_PREPARATION_WORK_HANDLER: WorkHandler<\n  'request.answer-preparation',\n  RequestAnswerPreparationWorkProps\n> = {\n  kind: REQUEST_ANSWER_PREPARATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestAnswerPreparationWorkProps>) {\n    const answerPreparationContext = buildCompiledAnswerPreparationContext(\n      ctx.state.context,\n      ctx.state.dependencies.functionRegistry,\n      ctx.state.dependencies.componentRegistry,\n    )\n\n    const resolved = await ctx.props.compiled(answerPreparationContext)\n\n    if (!isWorkTaskOfKind(resolved, ANSWER_PREPARATION_KIND)) {\n      throw new ForgeInternalError('Compiled answer preparation returned an invalid work task')\n    }\n\n    return singleTaskGroup(resolved)\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, RequestAnswerPreparationWorkProps>,\n    _children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    return { action: 'continue' }\n  },\n}\n\nexport function createRequestAnswerPreparationTask(props: RequestAnswerPreparationWorkProps) {\n  return createWorkTask(\n    'answer-preparation',\n    REQUEST_ANSWER_PREPARATION_WORK_HANDLER,\n    props,\n    REQUEST_ANSWER_PREPARATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport type { StepValidityResult } from '../contracts/stepValidityResult.type'\nimport type { RuntimeContext } from '../../../chassis/contracts/runtime/evaluationState.type'\n\n/**\n * Records a non-current step's reachability-round failure set into the per-step\n * `reachabilityValidities` map on the request context. Only the reachability\n * validities phase writes here; the current-page round stores its result on\n * `RequestState.currentPageValidation` instead.\n */\nexport function recordReachabilityValidity(context: RuntimeContext, stepId: NodeId, result: StepValidityResult): void {\n  if (context.evaluation.reachabilityValidities === undefined) {\n    context.evaluation.reachabilityValidities = new Map()\n  }\n\n  context.evaluation.reachabilityValidities.set(stepId, result)\n}\n\nexport function isStepValidityResult(value: unknown): value is StepValidityResult {\n  if (value === undefined || value === null || typeof value !== 'object') {\n    return false\n  }\n\n  if (!('fieldFailures' in value) || !('domainFailures' in value)) {\n    return false\n  }\n\n  return Array.isArray(value.fieldFailures) && Array.isArray(value.domainFailures)\n}\n","import type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport { validationTaskKey } from './stepValidationStore'\nimport { isStepValidityResult, recordReachabilityValidity } from './reachabilityValidityState'\nimport type { ValidationRuleFilter } from '../contracts/ValidationWork.type'\nimport type { RequestValiditiesWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_VALIDITIES_KIND = 'request.validities'\n\n// Reachability needs each step's default-group, non-submission validity, so\n// `submissionOnly` and off-default rules never run in — or gate — this round.\nconst REACHABILITY_VALIDATION_FILTER: ValidationRuleFilter = { groups: ['default'], includeSubmissionOnly: false }\n\nexport const REACHABILITY_VALIDITIES_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestValiditiesWorkProps,\n  PhaseWorkOutput\n> = phaseInstrumentation()\n\n/**\n * The reachability validities phase. Runs before navigation on every request and\n * validates every step that has a compiled validation, once, under the\n * reachability filter (default group, no `submissionOnly` rules). It fans the\n * per-step tasks out as one concurrent group and records each result into\n * `context.evaluation.reachabilityValidities` keyed by step id, for the\n * reachability walk to read. The current step is included: resume and frontier\n * resolution need its navigation validity, and this phase runs before either\n * current-page trigger could supply one. Its result here is a navigation fact\n * only — this phase never touches `currentPageValidation` or validation display,\n * which belong exclusively to the `validation.current-step` operation.\n *\n * `complete` rebuilds the task-key → step-id index from the props (the same\n * `validationTaskKey` the tasks were built under), so each result maps\n * back to its step without a per-unit side-channel. Each result maps to a\n * distinct step key, so there is no shared slot to clobber. Steps with no\n * compiled validation are absent from the map and are treated as valid by the walk.\n */\nexport const REACHABILITY_VALIDITIES_WORK_HANDLER: WorkHandler<'request.validities', RequestValiditiesWorkProps> = {\n  kind: REQUEST_VALIDITIES_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestValiditiesWorkProps>) {\n    const tasks = await Promise.all(\n      [...ctx.props.compiledStepValidations.keys()].map(stepId =>\n        ctx.state.dependencies.buildStepValidation(stepId, REACHABILITY_VALIDATION_FILTER),\n      ),\n    )\n    const present = tasks.filter(task => task !== undefined)\n\n    if (present.length === 0) {\n      return { groups: [] }\n    }\n\n    return {\n      groups: [{ mode: 'concurrent', children: present }],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, RequestValiditiesWorkProps>,\n    children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    const stepIdByKey = new Map(\n      [...ctx.props.compiledStepValidations.keys()].map(stepId => [validationTaskKey(stepId), stepId] as const),\n    )\n\n    // Read by key (each child maps back to its step by task key), so the\n    // per-kind accessor doesn't apply; narrow the erased child output here.\n    children.forEach(child => {\n      const stepId = stepIdByKey.get(child.key)\n\n      if (stepId !== undefined && isStepValidityResult(child.output)) {\n        recordReachabilityValidity(ctx.state.context, stepId, child.output)\n      }\n    })\n\n    return { action: 'continue' }\n  },\n}\n\nexport function createReachabilityValiditiesTask(props: RequestValiditiesWorkProps) {\n  return createWorkTask(\n    'validities',\n    REACHABILITY_VALIDITIES_WORK_HANDLER,\n    props,\n    REACHABILITY_VALIDITIES_WORK_INSTRUMENTATION,\n  )\n}\n","import type { ReachabilityEvaluation } from '../contracts/reachabilityEvaluation.type'\nimport type { HttpMethod } from '../../../../framework/types/request.type'\n\nexport function resolveBacklinkRouteTemplatePath(evaluation: ReachabilityEvaluation): string | undefined {\n  const currentStep = evaluation.steps.find(step => step.stepId === evaluation.currentStepId)\n\n  if (!currentStep) {\n    return undefined\n  }\n\n  const currentIndex = evaluation.canonicalPathRouteTemplatePaths.indexOf(currentStep.routeTemplatePath)\n\n  if (currentIndex <= 0) {\n    return undefined\n  }\n\n  return evaluation.canonicalPathRouteTemplatePaths[currentIndex - 1]\n}\n\nexport function resolveRedirect(\n  evaluation: ReachabilityEvaluation,\n  nodeKind: 'step' | 'journey',\n  method: HttpMethod,\n): string | undefined {\n  if (nodeKind === 'journey') {\n    if (evaluation.resumeOutcome === 'redirect') {\n      return evaluation.frontierRouteTemplatePath\n    }\n\n    return evaluation.defaultEntryRouteTemplatePath\n  }\n\n  const currentStep = evaluation.steps.find(step => step.stepId === evaluation.currentStepId)\n\n  if (!currentStep) {\n    return undefined\n  }\n\n  if (method === 'GET' && evaluation.resumeOutcome === 'redirect') {\n    return evaluation.frontierRouteTemplatePath\n  }\n\n  if (currentStep.isReachable) {\n    return undefined\n  }\n\n  return resolveUnreachableRedirect(evaluation)\n}\n\nfunction resolveUnreachableRedirect(evaluation: ReachabilityEvaluation): string | undefined {\n  if (evaluation.unreachableRedirect === 'frontier') {\n    return evaluation.frontierRouteTemplatePath ?? evaluation.defaultEntryRouteTemplatePath\n  }\n\n  return evaluation.defaultEntryRouteTemplatePath\n}\n","import { buildCompiledReachabilityContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { resolveRedirect } from './reachabilityRedirects'\nimport { captureContextSnapshot } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport type {\n  WorkBegin,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { RequestReachabilityWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type { ReachabilityStateInput } from '../contracts/generatedReachabilityEvaluation.type'\nimport type { NodeId } from '../../../chassis/contracts/ast/ast.type'\nimport type { ReachabilityEvaluation } from '../contracts/reachabilityEvaluation.type'\nimport type { StepValidityResult } from '../../validation/contracts/stepValidityResult.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nconst REQUEST_REACHABILITY_KIND = 'request.reachability'\n\nexport const REQUEST_REACHABILITY_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestReachabilityWorkProps,\n  PhaseWorkOutput\n> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, RequestReachabilityWorkProps>) {\n    return {\n      currentStepId: ctx.state.dependencies.currentStepId,\n      mode: ctx.props.mode,\n      stepCount: ctx.props.routeTemplateCatalog.routeTemplatePathByStepId.size,\n      hasParams: ctx.state.context.request.params !== undefined,\n    }\n  },\n\n  resolveTraceMetadataAtFinish(ctx: WorkContextContract<RequestState, RequestReachabilityWorkProps>) {\n    const evaluation = ctx.state.reachabilityEvaluation\n\n    return {\n      ...captureContextSnapshot(ctx.state.context),\n      resumeOutcome: evaluation?.resumeOutcome,\n      resumeActive: evaluation?.resumeActive,\n      reachableSteps: evaluation?.steps.filter(step => step.isReachable).length,\n      defaultEntryRouteTemplatePath: evaluation?.defaultEntryRouteTemplatePath,\n      frontierRouteTemplatePath: evaluation?.frontierRouteTemplatePath,\n      hasReachabilityProjection: ctx.state.context.evaluation.reachability !== undefined,\n    }\n  },\n}\n\n/**\n * The reachability phase, for both step and journey requests. It evaluates the\n * compiled reachability facts (the dynamic expressions) and, on step requests,\n * answer-cleardown's compiled field inventory, runs the compiled reachability\n * state function over them (graph walk, path/frontier/resume), stores the\n * evaluation and its projection on the shared context, then resolves the\n * redirect: step mode redirects when the requested step is unreachable or a\n * resume should jump to the frontier, else continues to the `answer-cleardown`\n * phase and on to render; journey mode always redirects to the journey's first\n * reachable step.\n */\nexport const REQUEST_REACHABILITY_WORK_HANDLER: WorkHandler<'request.reachability', RequestReachabilityWorkProps> = {\n  kind: REQUEST_REACHABILITY_KIND,\n\n  async begin(\n    ctx: WorkContextContract<RequestState, RequestReachabilityWorkProps>,\n  ): Promise<WorkBegin<'request.reachability'>> {\n    const { compiledReachabilityFacts, compiledReachabilityState } = ctx.props\n\n    const reachabilityContext = buildCompiledReachabilityContext(\n      ctx.state.context,\n      ctx.state.dependencies.functionRegistry,\n    )\n    const stepValidities = toReachabilityValidities(ctx.state.context.evaluation.reachabilityValidities)\n    const params = ctx.state.context.request.params\n\n    const facts = await compiledReachabilityFacts(reachabilityContext)\n\n    // Field inventory belongs to step requests: journey requests have no step to\n    // project onto, and without params the projection cannot resolve step paths.\n    const fieldInventory =\n      ctx.props.mode === 'journey' || params === undefined\n        ? undefined\n        : await ctx.props.compiledFieldInventory?.(reachabilityContext)\n\n    const stateInput: ReachabilityStateInput =\n      ctx.props.mode === 'journey'\n        ? { facts, routeTemplateCatalog: ctx.props.routeTemplateCatalog, stepValidities }\n        : {\n            facts,\n            currentStepId: ctx.state.dependencies.currentStepId,\n            routeTemplateCatalog: ctx.props.routeTemplateCatalog,\n            stepValidities,\n            params,\n            fieldInventory,\n          }\n\n    const result = compiledReachabilityState(stateInput)\n\n    if (result.reachability !== undefined) {\n      ctx.state.context.evaluation.reachability = result.reachability\n    }\n\n    ctx.state.recordReachabilityEvaluation(result.evaluation)\n\n    return { output: resolvePhaseOutput(result.evaluation, ctx.props) }\n  },\n}\n\nfunction resolvePhaseOutput(evaluation: ReachabilityEvaluation, props: RequestReachabilityWorkProps): PhaseWorkOutput {\n  const redirectTarget = resolveRedirect(evaluation, props.mode, props.method)\n\n  if (props.mode === 'journey') {\n    if (!redirectTarget) {\n      throw new ForgeInternalError('No steps found in journey')\n    }\n\n    return { action: 'halt-redirect', target: redirectTarget, reason: 'journey-redirect' }\n  }\n\n  if (redirectTarget) {\n    const reason = evaluation.resumeOutcome === 'redirect' ? 'resume' : 'unreachable'\n\n    return { action: 'halt-redirect', target: redirectTarget, reason }\n  }\n\n  return { action: 'continue' }\n}\n\n// The reachability validities phase already executed only the rules reachability\n// cares about (default group, no `submissionOnly`), so a stored result is valid\n// exactly when it recorded no failures.\nfunction toReachabilityValidities(\n  reachabilityValidities: ReadonlyMap<NodeId, StepValidityResult> | undefined,\n): Map<NodeId, boolean> {\n  const validityByStepId = new Map<NodeId, boolean>()\n\n  reachabilityValidities?.forEach((result, stepId) => {\n    validityByStepId.set(stepId, result.fieldFailures.length === 0 && result.domainFailures.length === 0)\n  })\n\n  return validityByStepId\n}\n\nexport function createRequestReachabilityTask(props: RequestReachabilityWorkProps) {\n  return createWorkTask(\n    'reachability',\n    REQUEST_REACHABILITY_WORK_HANDLER,\n    props,\n    REQUEST_REACHABILITY_WORK_INSTRUMENTATION,\n  )\n}\n","import type { AnswerHistory } from '../../../chassis/contracts/runtime/answerHistory.type'\nimport type { JourneyReachabilityProjection } from '../../reachability/contracts/journeyReachabilityProjection.type'\n\n/**\n * Resolves the answers of steps no active path can reach and clears each in place,\n * returning the resolved field codes. The reachability walk marks every step a valid\n * chain reaches — including steps ahead of the current one — as reachable, so only\n * steps no path can reach under the current answers are cleared.\n */\nexport function evaluateAnswerCleardown(\n  reachability: JourneyReachabilityProjection,\n  answers: Record<string, AnswerHistory>,\n): readonly string[] {\n  const fieldsToClear = resolveFieldsToClear(reachability, answers)\n\n  clearStaleAnswers(answers, fieldsToClear)\n\n  return fieldsToClear\n}\n\n/**\n * Resolves which answer field codes belong to unreachable steps: codes declared on\n * those steps' blocks, plus any answer key matching their `cleardownFieldCodes`\n * patterns. Only codes that actually have an answer are returned.\n */\nfunction resolveFieldsToClear(\n  reachability: JourneyReachabilityProjection,\n  answers: Record<string, AnswerHistory>,\n): readonly string[] {\n  const answerKeys = Object.keys(answers)\n\n  if (answerKeys.length === 0) {\n    return []\n  }\n\n  const unreachableSteps = reachability.unreachableSteps\n  const answerKeySet = new Set(answerKeys)\n  const fieldsToClear = new Set<string>()\n\n  unreachableSteps.forEach(step => {\n    step.fieldCodes?.forEach(code => {\n      if (answerKeySet.has(code)) {\n        fieldsToClear.add(code)\n      }\n    })\n  })\n\n  const matchers = unreachableSteps.flatMap(step => step.cleardownFieldCodes ?? []).map(pattern => new RegExp(pattern))\n\n  if (matchers.length > 0) {\n    answerKeys.forEach(answerKey => {\n      if (matchers.some(matcher => matcher.test(answerKey))) {\n        fieldsToClear.add(answerKey)\n      }\n    })\n  }\n\n  return [...fieldsToClear]\n}\n\n/**\n * Pushes a clearing `cleardown` mutation onto each stale answer so later phases\n * observe it as unanswered. Already-cleared answers are skipped so a request never\n * stacks duplicate cleardown mutations.\n */\nfunction clearStaleAnswers(answers: Record<string, AnswerHistory>, fieldCodes: readonly string[]): void {\n  fieldCodes.forEach(fieldCode => {\n    const history = answers[fieldCode]\n\n    if (history === undefined || history.current === undefined) {\n      return\n    }\n\n    history.current = undefined\n    history.parsed = undefined\n    history.mutations.push({ value: undefined, source: 'cleardown' })\n  })\n}\n","import { evaluateAnswerCleardown } from './evaluateAnswerCleardown'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestAnswerCleardownWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_ANSWER_CLEARDOWN_KIND = 'request.answer-cleardown'\n\nexport const REQUEST_ANSWER_CLEARDOWN_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestAnswerCleardownWorkProps,\n  PhaseWorkOutput\n> = phaseInstrumentation()\n\n/**\n * The answer-cleardown phase (step requests only). Runs straight after `reachability`\n * so the reachability projection, the navigation evaluation, and the answer record\n * are sampled at one point. It delegates to `evaluateAnswerCleardown`, which clears\n * the stale answers in place, then publishes the resolved codes on\n * `context.evaluation.fieldsToClear` for `getFieldsToClear()` readers. No-ops when reachability\n * is disabled (no projection was stored). Always continues — clearing is a side\n * effect, never a redirect.\n */\nexport const REQUEST_ANSWER_CLEARDOWN_WORK_HANDLER: WorkHandler<\n  'request.answer-cleardown',\n  RequestAnswerCleardownWorkProps\n> = {\n  kind: REQUEST_ANSWER_CLEARDOWN_KIND,\n\n  begin() {\n    return { groups: [] }\n  },\n\n  complete(ctx: WorkContextContract<RequestState, RequestAnswerCleardownWorkProps>): PhaseWorkOutput {\n    const context = ctx.state.context\n    const evaluation = ctx.state.reachabilityEvaluation\n\n    if (context.evaluation.reachability === undefined || evaluation === undefined) {\n      return { action: 'continue' }\n    }\n\n    context.evaluation.fieldsToClear = evaluateAnswerCleardown(context.evaluation.reachability, context.domain.answers)\n\n    return { action: 'continue' }\n  },\n}\n\nexport function createRequestAnswerCleardownTask(props: RequestAnswerCleardownWorkProps) {\n  return createWorkTask(\n    'answer-cleardown',\n    REQUEST_ANSWER_CLEARDOWN_WORK_HANDLER,\n    props,\n    REQUEST_ANSWER_CLEARDOWN_WORK_INSTRUMENTATION,\n  )\n}\n","import type { CompiledSubmitHookResult } from '../contracts/hookLifecycle.type'\nimport { buildCompiledHookLifecycleContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { SUBMIT_LIFECYCLE_KIND } from './SubmitLifecycleWorkHandler'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, isWorkTaskOfKind, singleChildOutput, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestSubmitWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nconst REQUEST_SUBMIT_KIND = 'request.submit'\n\nexport const REQUEST_SUBMIT_WORK_INSTRUMENTATION: WorkInstrumentation<RequestSubmitWorkProps, PhaseWorkOutput> =\n  phaseInstrumentation()\n\n/**\n * The submit phase as work (POST steps only). `begin` runs the compiled submit\n * lifecycle (its validation stage is the validation-owned `validation.current-step`\n * task, which owns execution, result storage, and the display signal); `complete`\n * maps the hook result to a halt or continue — submit outcomes only, never\n * validation display state.\n */\nexport const REQUEST_SUBMIT_WORK_HANDLER: WorkHandler<'request.submit', RequestSubmitWorkProps> = {\n  kind: REQUEST_SUBMIT_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestSubmitWorkProps>) {\n    const hookLifecycleContext = buildCompiledHookLifecycleContext(\n      ctx.state.context,\n      ctx.state.dependencies.functionRegistry,\n      'submit',\n      ctx.state.dependencies.responseBindings,\n    )\n\n    const resolved = await ctx.props.compiled(hookLifecycleContext)\n\n    if (!isWorkTaskOfKind(resolved, SUBMIT_LIFECYCLE_KIND)) {\n      throw new ForgeInternalError('Compiled submit hooks returned an invalid work task')\n    }\n\n    return singleTaskGroup(resolved)\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, RequestSubmitWorkProps>,\n    children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    const result = singleChildOutput(children, SUBMIT_LIFECYCLE_KIND)\n\n    if (result === undefined) {\n      throw new ForgeInternalError('Submit lifecycle work task completed with an invalid submit result')\n    }\n\n    return toOutput(result)\n  },\n}\n\nfunction toOutput(result: CompiledSubmitHookResult): PhaseWorkOutput {\n  if (result.outcome === 'redirect') {\n    if (result.redirect === undefined) {\n      throw new ForgeInternalError('Hook redirect target is missing')\n    }\n\n    return { action: 'halt-redirect', target: result.redirect, reason: 'submit' }\n  }\n\n  if (result.outcome === 'error') {\n    return { action: 'halt-error', status: result.status ?? 500, message: result.message || 'Submission error' }\n  }\n\n  return { action: 'continue' }\n}\n\nexport function createRequestSubmitTask(props: RequestSubmitWorkProps) {\n  return createWorkTask('submit', REQUEST_SUBMIT_WORK_HANDLER, props, REQUEST_SUBMIT_WORK_INSTRUMENTATION)\n}\n","import { buildCompiledValidationContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport {\n  CURRENT_STEP_VALIDATION_WORK_HANDLER,\n  CURRENT_STEP_VALIDATION_WORK_INSTRUMENTATION,\n} from './CurrentStepValidationWorkHandler'\nimport type { CurrentStepValidationWorkProps } from '../contracts/ValidationWork.type'\nimport type { RequestEntryValidationWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_ENTRY_VALIDATION_KIND = 'request.entry-validation'\n\nexport const REQUEST_ENTRY_VALIDATION_WORK_INSTRUMENTATION: WorkInstrumentation<\n  RequestEntryValidationWorkProps,\n  PhaseWorkOutput\n> = phaseInstrumentation()\n\n/**\n * The entry-validation phase as work (GET steps only). It runs the compiled\n * `validateOnEntry` selector, which combines the groups from every matching entry,\n * and — when at least one group is active — schedules the shared\n * `validation.current-step` task in non-submission mode. The task owns the whole\n * current-page operation and its result store; this phase only decides whether to\n * trigger it. With no compiled entry validation or no resolved groups, nothing runs\n * and nothing is displayed.\n */\nexport const REQUEST_ENTRY_VALIDATION_WORK_HANDLER: WorkHandler<\n  'request.entry-validation',\n  RequestEntryValidationWorkProps\n> = {\n  kind: REQUEST_ENTRY_VALIDATION_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestEntryValidationWorkProps>) {\n    const validationContext = buildCompiledValidationContext(ctx.state.context, ctx.state.dependencies.functionRegistry)\n    const groups = await ctx.props.compiled(validationContext)\n\n    if (groups.length === 0) {\n      return { groups: [] }\n    }\n\n    const props: CurrentStepValidationWorkProps = { groups, includeSubmissionOnly: false }\n\n    return singleTaskGroup(\n      createWorkTask(\n        'entry-validation',\n        CURRENT_STEP_VALIDATION_WORK_HANDLER,\n        props,\n        CURRENT_STEP_VALIDATION_WORK_INSTRUMENTATION,\n      ),\n    )\n  },\n\n  complete(\n    _ctx: WorkContextContract<RequestState, RequestEntryValidationWorkProps>,\n    _children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    return { action: 'continue' }\n  },\n}\n\nexport function createRequestEntryValidationTask(props: RequestEntryValidationWorkProps) {\n  return createWorkTask(\n    'entry-validation',\n    REQUEST_ENTRY_VALIDATION_WORK_HANDLER,\n    props,\n    REQUEST_ENTRY_VALIDATION_WORK_INSTRUMENTATION,\n  )\n}\n","import type { ReachabilityEvaluation } from '../../reachability/contracts/reachabilityEvaluation.type'\nimport type { StepValidationFailure } from '../../../chassis/contracts/runtime/evaluationState.type'\nimport type { ValidationResult } from '../../validation/contracts/validationResult.type'\nimport { resolvePathParams } from '../../../../shared/routePath'\nimport type { RenderContext, RenderValidationError } from '../../../../framework/types/rendering.type'\nimport type { ViewConfig } from '../../../../authoring/types/structures.type'\nimport { buildCompiledResolveContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { resolveBacklinkRouteTemplatePath } from '../../reachability/runtime/reachabilityRedirects'\nimport { RESOLVE_BLOCKS_KIND } from './ResolveBlocksWorkHandler'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, isWorkTaskOfKind, singleChildOutput, singleTaskGroup } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestResolveWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\nimport ForgeInternalError from '../../../errors/ForgeInternalError'\n\nconst REQUEST_RESOLVE_KIND = 'request.resolve'\n\nexport const REQUEST_RESOLVE_WORK_INSTRUMENTATION: WorkInstrumentation<RequestResolveWorkProps, PhaseWorkOutput> =\n  phaseInstrumentation()\n\n/**\n * The resolve phase as work. `begin` runs the compiled block task; `complete`\n * assembles the `RenderContext` from the resolved blocks, effective inherited\n * view, and navigation/validation signalling on the context. When a renderer is present,\n * it stores the context for the render phase and continues. Otherwise it\n * returns the render context as the terminal outcome.\n */\nexport const REQUEST_RESOLVE_WORK_HANDLER: WorkHandler<'request.resolve', RequestResolveWorkProps> = {\n  kind: REQUEST_RESOLVE_KIND,\n\n  async begin(ctx: WorkContextContract<RequestState, RequestResolveWorkProps>) {\n    const fieldFailures: Record<string, ValidationResult[]> = groupFieldFailuresByBlockId(\n      ctx.state.currentPageValidation?.fieldFailures ?? [],\n    )\n    const compiledResolveContext = buildCompiledResolveContext(\n      ctx.state.context,\n      ctx.state.dependencies.functionRegistry,\n      ctx.state.dependencies.componentRegistry,\n      fieldFailures,\n      ctx.state.fieldFailureAnchors,\n    )\n\n    const resolved = await ctx.props.compiled(compiledResolveContext)\n\n    if (!isWorkTaskOfKind(resolved, RESOLVE_BLOCKS_KIND)) {\n      throw new ForgeInternalError('Compiled render function returned an invalid resolve work task')\n    }\n\n    return singleTaskGroup(resolved)\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, RequestResolveWorkProps>,\n    children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    const output = singleChildOutput(children, RESOLVE_BLOCKS_KIND)\n\n    if (output === undefined) {\n      throw new ForgeInternalError('Resolve work task completed with an invalid render result')\n    }\n\n    const ancestors = output.ancestors as RenderContext['ancestors']\n    const stepMetadata = resolveStepMetadata(\n      output.step as RenderContext['step'],\n      ctx.state.context.request.params,\n      ctx.state.reachabilityEvaluation,\n    )\n    const view = resolveView(ancestors, stepMetadata.view)\n    const step = view === undefined ? stepMetadata : { ...stepMetadata, view }\n\n    // The presence of a current-page result is the display signal: present means\n    // validation ran (possibly passing with no failures), absent means it never ran.\n    const validation = ctx.state.currentPageValidation\n\n    const showValidationFailures = validation !== undefined\n    const fieldFailures = validation?.fieldFailures ?? []\n    const domainFailures = validation?.domainFailures ?? []\n\n    const renderContext: RenderContext = {\n      routeTree: ctx.state.routeTree ?? [],\n      step,\n      ancestors,\n      blocks: [...output.blocks],\n      showValidationFailures,\n      fieldValidationErrors: fieldFailures.map(failure =>\n        toRenderValidationError(failure, ctx.state.fieldFailureAnchors),\n      ),\n      domainValidationErrors: domainFailures,\n      answers: ctx.state.context.domain.answers,\n      data: ctx.state.context.domain.data,\n    }\n\n    if (ctx.state.dependencies.hasRenderer) {\n      ctx.state.recordRenderContext(renderContext)\n\n      return { action: 'continue' }\n    }\n\n    return { action: 'render', renderContext }\n  },\n}\n\nfunction resolveView(ancestors: RenderContext['ancestors'], stepView: ViewConfig | undefined): ViewConfig | undefined {\n  const viewConfigs = [\n    ...ancestors.flatMap(ancestor => (ancestor.view === undefined ? [] : [ancestor.view])),\n    ...(stepView === undefined ? [] : [stepView]),\n  ]\n\n  if (viewConfigs.length === 0) {\n    return undefined\n  }\n\n  const template = viewConfigs.reduce<string | undefined>(\n    (resolvedTemplate, view) => view.template ?? resolvedTemplate,\n    undefined,\n  )\n  const locals = viewConfigs.reduce<Record<string, unknown>>(\n    (resolvedLocals, view) => ({ ...resolvedLocals, ...view.locals }),\n    {},\n  )\n  const hasLocals = viewConfigs.some(view => view.locals !== undefined)\n\n  return {\n    ...(template === undefined ? {} : { template }),\n    ...(hasLocals ? { locals } : {}),\n  }\n}\n\nfunction resolveStepMetadata(\n  step: RenderContext['step'],\n  params: Record<string, string>,\n  reachabilityEvaluation: ReachabilityEvaluation | undefined,\n): RenderContext['step'] {\n  if (step.backlink !== undefined || !reachabilityEvaluation) {\n    return step\n  }\n\n  const backPath = resolveBacklinkRouteTemplatePath(reachabilityEvaluation)\n\n  if (!backPath) {\n    return step\n  }\n\n  return {\n    ...step,\n    backlink: resolvePathParams(backPath, params),\n  }\n}\n\n// Groups the step's field failures by render block ID (stripping blockId), so\n// each field self-resolves its own failures during render. Field code is answer\n// identity, not render-block identity.\nfunction groupFieldFailuresByBlockId(failures: readonly StepValidationFailure[]): Record<string, ValidationResult[]> {\n  const grouped: Record<string, ValidationResult[]> = {}\n\n  failures.forEach(failure => {\n    grouped[failure.blockId] ??= []\n    grouped[failure.blockId].push(stripBlockId(failure))\n  })\n\n  return grouped\n}\n\nfunction stripBlockId(failure: StepValidationFailure): ValidationResult {\n  const { blockId: _, ...validation } = failure\n\n  return validation\n}\n\n// Pairs a failure with its failing block instance's document anchor, recorded\n// during block resolution, so the error summary links to the right instance\n// even when several blocks share one code.\nfunction toRenderValidationError(\n  failure: StepValidationFailure,\n  fieldFailureAnchors: Record<string, string>,\n): RenderValidationError {\n  const anchor = fieldFailureAnchors[failure.blockId]\n\n  return anchor === undefined ? stripBlockId(failure) : { ...stripBlockId(failure), anchor }\n}\n\nexport function createRequestResolveTask(props: RequestResolveWorkProps) {\n  return createWorkTask('resolve', REQUEST_RESOLVE_WORK_HANDLER, props, REQUEST_RESOLVE_WORK_INSTRUMENTATION)\n}\n","import { resolvePathParams } from '../../../../shared/routePath'\nimport { RouteTree, RouteTreeNode, RouteTreeRoute } from '../../../../framework/types/routeTree.type'\nimport type {\n  ResolvedRouteMetadata,\n  ResolvedRouteMetadataEntry,\n} from '../../../chassis/contracts/compiled/compiledFunctions.type'\nimport { StoredRouteTree, StoredRouteTreeNode, StoredRouteTreeRoute } from '../contracts/routeTree.type'\n\n/**\n * Hydrates the stored route hierarchy for one request: resolves `:param`\n * placeholders to concrete paths, marks the active branch for the current step,\n * and merges the per-request resolved route metadata onto each node by node ID.\n */\nexport function hydrateRouteTree(\n  routeTree: StoredRouteTree,\n  currentStepPath: string,\n  params: Record<string, string>,\n  routeMetadata: ResolvedRouteMetadata,\n): RouteTree {\n  return routeTree.map(node => toRouteTreeNode(node, currentStepPath, params, routeMetadata))\n}\n\nfunction toRouteTreeNode(\n  stored: StoredRouteTreeNode,\n  currentStepPath: string,\n  params: Record<string, string>,\n  routeMetadata: ResolvedRouteMetadata,\n): RouteTreeNode {\n  const children = stored.children.map(child => toRouteTreeNode(child, currentStepPath, params, routeMetadata))\n  const entry = stored.route ? routeMetadata[stored.route.nodeId] : undefined\n\n  return {\n    segment: stored.segment,\n    path: resolvePathParams(stored.templatePath, params),\n    templatePath: stored.templatePath,\n    active: stored.templatePath === currentStepPath || children.some(child => child.active),\n    metadata: entry?.metadata,\n    route: stored.route ? toRouteTreeRoute(stored.route, entry) : undefined,\n    children,\n  }\n}\n\nfunction toRouteTreeRoute(stored: StoredRouteTreeRoute, entry: ResolvedRouteMetadataEntry | undefined): RouteTreeRoute {\n  return {\n    kind: stored.kind,\n    nodeId: stored.nodeId,\n    title: entry?.title,\n    description: entry?.description,\n    metadata: entry?.metadata,\n  }\n}\n","import { buildCompiledRouteMetadataContext } from '../../../chassis/runtime/context/compiledEvaluationContext'\nimport { hydrateRouteTree } from './hydrateRouteTree'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport type { RequestRouteTreeWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_ROUTE_TREE_KIND = 'request.route-tree'\n\nexport const REQUEST_ROUTE_TREE_WORK_INSTRUMENTATION: WorkInstrumentation<RequestRouteTreeWorkProps, PhaseWorkOutput> =\n  phaseInstrumentation()\n\n/**\n * The route-tree phase (step requests only). Runs just before resolve. It\n * evaluates the package-level route-metadata function and merges the resolved\n * title/description/metadata onto the statically built topology, publishing the\n * hydrated tree on `ctx.state.routeTree` for resolve to assemble into the render\n * context. Always continues — building the tree is preparation, never a redirect.\n */\nexport const REQUEST_ROUTE_TREE_WORK_HANDLER: WorkHandler<'request.route-tree', RequestRouteTreeWorkProps> = {\n  kind: REQUEST_ROUTE_TREE_KIND,\n\n  begin() {\n    return { groups: [] }\n  },\n\n  async complete(ctx: WorkContextContract<RequestState, RequestRouteTreeWorkProps>): Promise<PhaseWorkOutput> {\n    const routeMetadata = await ctx.props.compiled(\n      buildCompiledRouteMetadataContext(ctx.state.context, ctx.state.dependencies.functionRegistry),\n    )\n\n    ctx.state.recordRouteTree(\n      hydrateRouteTree(\n        ctx.props.routeTree,\n        ctx.props.currentRouteTemplatePath,\n        ctx.state.context.request.params,\n        routeMetadata,\n      ),\n    )\n\n    return { action: 'continue' }\n  },\n}\n\nexport function createRequestRouteTreeTask(props: RequestRouteTreeWorkProps) {\n  return createWorkTask('route-tree', REQUEST_ROUTE_TREE_WORK_HANDLER, props, REQUEST_ROUTE_TREE_WORK_INSTRUMENTATION)\n}\n","import type { RenderContext, ForgeRenderer } from '../../../../framework/types/rendering.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { WorkContextContract, WorkHandler, WorkInstrumentation } from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport { createWorkTask } from '../../../chassis/work/workTask'\n\nexport interface RenderAssemblePageWorkProps {\n  readonly renderContext: RenderContext\n  readonly renderer: ForgeRenderer<unknown>\n}\n\nexport const RENDER_ASSEMBLE_PAGE_KIND = 'render.assemble-page'\n\nexport const RENDER_ASSEMBLE_PAGE_WORK_INSTRUMENTATION: WorkInstrumentation<RenderAssemblePageWorkProps, unknown> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, RenderAssemblePageWorkProps>): TraceSpanFields {\n    return {\n      renderedBlocks: (ctx.state.renderedBlocks ?? []).length,\n    }\n  },\n\n  resolveTraceMetadataAtFinish(): TraceSpanFields | undefined {\n    return undefined\n  },\n}\n\nexport const RENDER_ASSEMBLE_PAGE_WORK_HANDLER: WorkHandler<'render.assemble-page', RenderAssemblePageWorkProps> = {\n  kind: RENDER_ASSEMBLE_PAGE_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RenderAssemblePageWorkProps>) {\n    const { renderContext, renderer } = ctx.props\n    const renderedBlocks = ctx.state.renderedBlocks ?? []\n    const requestState = ctx.state.context.request.state\n\n    const output = renderer.assemblePage(renderContext, renderedBlocks, requestState)\n\n    return { output: output as Promise<unknown> }\n  },\n}\n\nexport function createAssemblePageTask(renderContext: RenderContext, renderer: ForgeRenderer<unknown>) {\n  return createWorkTask(\n    'assemble-page',\n    RENDER_ASSEMBLE_PAGE_WORK_HANDLER,\n    { renderContext, renderer },\n    RENDER_ASSEMBLE_PAGE_WORK_INSTRUMENTATION,\n  )\n}\n","import type { ComponentRegistryEntry } from '../../../../components/types/components.type'\nimport type { BlockDefinition, EvaluatedBlock } from '../../../../components/types/structures.type'\nimport { StructureType } from '../../../../authoring/types/enums'\nimport { RENDER_BLOCK_BRAND } from '../contracts/renderBlock.brand'\nimport type { RenderBlock, ForgeRenderer } from '../../../../framework/types/rendering.type'\nimport type { ComponentRegistry } from '../../../../framework/types/adapter.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n  WorkTask,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport ForgeUnregisteredComponentError from '../../../errors/ForgeUnregisteredComponentError'\nimport { createWorkTask } from '../../../chassis/work/workTask'\n\nexport interface RenderBlockWorkProps {\n  readonly block: RenderBlock\n  readonly entry: ComponentRegistryEntry<BlockDefinition, unknown>\n  readonly renderer: ForgeRenderer<unknown>\n  readonly componentRegistry: ComponentRegistry\n}\n\ntype RenderBlockWorkTask = WorkTask<'render.render-blocks.block', RenderBlockWorkProps>\n\nexport const RENDER_BLOCK_KIND = 'render.render-blocks.block'\n\nexport const RENDER_BLOCK_WORK_INSTRUMENTATION: WorkInstrumentation<RenderBlockWorkProps, unknown> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, RenderBlockWorkProps>): TraceSpanFields {\n    return {\n      id: ctx.props.block.id,\n      variant: ctx.props.block.variant,\n      blockType: ctx.props.block.blockType,\n    }\n  },\n\n  resolveTraceMetadataAtFinish(): TraceSpanFields | undefined {\n    return undefined\n  },\n}\n\nexport const RENDER_BLOCK_WORK_HANDLER: WorkHandler<'render.render-blocks.block', RenderBlockWorkProps> = {\n  kind: RENDER_BLOCK_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RenderBlockWorkProps>) {\n    const { block, renderer, componentRegistry } = ctx.props\n\n    if (block.properties.visibleWhen === false) {\n      ctx.omitFromTrace?.()\n\n      return { output: '' }\n    }\n\n    const nestedTasks = collectNestedBlockTasks(block.properties, renderer, componentRegistry)\n\n    if (nestedTasks.length === 0) {\n      return { groups: [] }\n    }\n\n    return {\n      groups: [\n        {\n          mode: 'concurrent' as const,\n          children: nestedTasks,\n        },\n      ],\n    }\n  },\n\n  async complete(ctx: WorkContextContract<RequestState, RenderBlockWorkProps>, children: readonly CompletedWork[]) {\n    const { block, entry, renderer } = ctx.props\n\n    if (block.properties.visibleWhen === false) {\n      return ''\n    }\n\n    const updatedProperties = replaceNestedBlocks(block.properties, children, renderer)\n    const evaluatedBlock = toEvaluatedBlock({ ...block, properties: updatedProperties })\n\n    const output = await renderer.renderBlock(entry, evaluatedBlock)\n\n    // Mark only while devtools is tracing, so production output stays unmarked.\n    if (ctx.state.dependencies.traceEnabled && renderer.markBlock) {\n      return renderer.markBlock(block.id, output)\n    }\n\n    return output\n  },\n}\n\nfunction toEvaluatedBlock(block: RenderBlock): EvaluatedBlock<BlockDefinition> {\n  return {\n    type: StructureType.BLOCK,\n    variant: block.variant,\n    blockType: block.blockType,\n    ...block.properties,\n  } as EvaluatedBlock<BlockDefinition>\n}\n\nfunction isRenderBlock(value: unknown): value is RenderBlock {\n  return typeof value === 'object' &&\n    value !== null &&\n    RENDER_BLOCK_BRAND in value &&\n    (value as Record<symbol, unknown>)[RENDER_BLOCK_BRAND] === true\n}\n\nfunction collectNestedBlockTasks(\n  properties: Record<string, unknown>,\n  renderer: ForgeRenderer<unknown>,\n  componentRegistry: ComponentRegistry,\n): RenderBlockWorkTask[] {\n  const tasks: RenderBlockWorkTask[] = []\n\n  walkProperties(properties, value => {\n    if (!isRenderBlock(value)) {\n      return\n    }\n\n    const entry = componentRegistry.get(value.variant)\n\n    if (entry === undefined) {\n      throw new ForgeUnregisteredComponentError({ variant: value.variant })\n    }\n\n    tasks.push(createRenderBlockTask(value.id, value, entry, renderer, componentRegistry))\n  })\n\n  return tasks\n}\n\nfunction replaceNestedBlocks(\n  properties: Record<string, unknown>,\n  children: readonly CompletedWork[],\n  renderer: ForgeRenderer<unknown>,\n): Record<string, unknown> {\n  let childIndex = 0\n\n  return replaceInValue(properties, value => {\n    if (!isRenderBlock(value)) {\n      return value\n    }\n\n    const blockDefinition = {\n      type: StructureType.BLOCK,\n      variant: value.variant,\n      blockType: value.blockType,\n      ...value.properties,\n    } as BlockDefinition\n\n    const entry = children[childIndex]\n\n    if (!entry) {\n      return value\n    }\n\n    childIndex += 1\n\n    return renderer.wrapNestedBlock(blockDefinition, entry.output)\n  }) as Record<string, unknown>\n}\n\nfunction walkProperties(value: unknown, visitor: (value: unknown) => void): void {\n  if (value === undefined || value === null || typeof value !== 'object') {\n    return\n  }\n\n  if (isRenderBlock(value)) {\n    visitor(value)\n\n    return\n  }\n\n  if (Array.isArray(value)) {\n    value.forEach(item => walkProperties(item, visitor))\n\n    return\n  }\n\n  Object.values(value).forEach(item => walkProperties(item, visitor))\n}\n\nfunction replaceInValue(value: unknown, replacer: (value: unknown) => unknown): unknown {\n  if (value === undefined || value === null || typeof value !== 'object') {\n    return value\n  }\n\n  if (isRenderBlock(value)) {\n    return replacer(value)\n  }\n\n  if (Array.isArray(value)) {\n    return value.map(item => replaceInValue(item, replacer))\n  }\n\n  const result: Record<string, unknown> = {}\n\n  Object.entries(value as Record<string, unknown>).forEach(([key, item]) => {\n    result[key] = replaceInValue(item, replacer)\n  })\n\n  return result\n}\n\nexport function createRenderBlockTask(\n  id: string,\n  block: RenderBlock,\n  entry: ComponentRegistryEntry<BlockDefinition, unknown>,\n  renderer: ForgeRenderer<unknown>,\n  componentRegistry: ComponentRegistry,\n) {\n  return createWorkTask(\n    id,\n    RENDER_BLOCK_WORK_HANDLER,\n    { block, entry, renderer, componentRegistry },\n    RENDER_BLOCK_WORK_INSTRUMENTATION,\n  )\n}\n","import type { RenderBlock, ForgeRenderer } from '../../../../framework/types/rendering.type'\nimport type { ComponentRegistry } from '../../../../framework/types/adapter.type'\nimport type { ComponentRegistryEntry } from '../../../../components/types/components.type'\nimport type { BlockDefinition } from '../../../../components/types/structures.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport type { TraceSpanFields } from '../../../chassis/tracing/traceSpan.type'\nimport ForgeUnregisteredComponentError from '../../../errors/ForgeUnregisteredComponentError'\nimport { childOutputs, createWorkTask } from '../../../chassis/work/workTask'\nimport { RENDER_BLOCK_KIND, createRenderBlockTask } from './RenderBlockWorkHandler'\n\nexport interface RenderBlocksWorkProps {\n  readonly blocks: readonly RenderBlock[]\n  readonly renderer: ForgeRenderer<unknown>\n  readonly componentRegistry: ComponentRegistry\n}\n\nconst RENDER_BLOCKS_KIND = 'render.render-blocks'\n\nexport const RENDER_BLOCKS_WORK_INSTRUMENTATION: WorkInstrumentation<RenderBlocksWorkProps, unknown> = {\n  resolveTraceMetadataAtStart(ctx: WorkContextContract<RequestState, RenderBlocksWorkProps>): TraceSpanFields {\n    return {\n      blocks: ctx.props.blocks.length,\n    }\n  },\n\n  resolveTraceMetadataAtFinish(): TraceSpanFields | undefined {\n    return undefined\n  },\n}\n\nexport const RENDER_BLOCKS_WORK_HANDLER: WorkHandler<'render.render-blocks', RenderBlocksWorkProps> = {\n  kind: RENDER_BLOCKS_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RenderBlocksWorkProps>) {\n    const { blocks, renderer, componentRegistry } = ctx.props\n\n    const children = blocks.map(block =>\n      createRenderBlockTask(\n        block.id,\n        block,\n        resolveComponentEntry(componentRegistry, block.variant),\n        renderer,\n        componentRegistry,\n      ),\n    )\n\n    return {\n      groups: [\n        {\n          mode: 'concurrent' as const,\n          children,\n        },\n      ],\n    }\n  },\n\n  complete(ctx: WorkContextContract<RequestState, RenderBlocksWorkProps>, children: readonly CompletedWork[]) {\n    const renderedBlocks = childOutputs(children, RENDER_BLOCK_KIND)\n\n    ctx.state.recordRenderedBlocks(renderedBlocks)\n\n    return renderedBlocks\n  },\n}\n\nfunction resolveComponentEntry(\n  componentRegistry: ComponentRegistry,\n  variant: string,\n): ComponentRegistryEntry<BlockDefinition, unknown> {\n  const entry = componentRegistry.get(variant)\n\n  if (entry === undefined) {\n    throw new ForgeUnregisteredComponentError({ variant })\n  }\n\n  return entry\n}\n\nexport function createRenderBlocksTask(\n  blocks: readonly RenderBlock[],\n  renderer: ForgeRenderer<unknown>,\n  componentRegistry: ComponentRegistry,\n) {\n  return createWorkTask(\n    'render-blocks',\n    RENDER_BLOCKS_WORK_HANDLER,\n    { blocks, renderer, componentRegistry },\n    RENDER_BLOCKS_WORK_INSTRUMENTATION,\n  )\n}\n","import type {\n  CompletedWork,\n  WorkContextContract,\n  WorkHandler,\n  WorkInstrumentation,\n} from '../../../chassis/contracts/work/work.type'\nimport { createWorkTask, singleChildOutput } from '../../../chassis/work/workTask'\nimport { phaseInstrumentation } from '../../../chassis/runtime/pipeline/contextSnapshot'\nimport { RENDER_ASSEMBLE_PAGE_KIND, createAssemblePageTask } from './RenderAssemblePageWorkHandler'\nimport { createRenderBlocksTask } from './RenderBlocksWorkHandler'\nimport type { RequestRenderWorkProps } from '../../../chassis/contracts/runtime/RequestPipelineWork.type'\nimport type RequestState from '../../../chassis/runtime/pipeline/RequestState'\nimport type { PhaseWorkOutput } from '../../../chassis/contracts/runtime/requestPipelineOutput.type'\n\nconst REQUEST_RENDER_KIND = 'request.render'\n\nexport const REQUEST_RENDER_WORK_INSTRUMENTATION: WorkInstrumentation<RequestRenderWorkProps, PhaseWorkOutput> =\n  phaseInstrumentation()\n\nexport const REQUEST_RENDER_WORK_HANDLER: WorkHandler<'request.render', RequestRenderWorkProps> = {\n  kind: REQUEST_RENDER_KIND,\n\n  begin(ctx: WorkContextContract<RequestState, RequestRenderWorkProps>) {\n    const renderContext = ctx.state.renderContext\n    const { renderer, componentRegistry } = ctx.props\n\n    const renderBlocks = createRenderBlocksTask(renderContext.blocks, renderer, componentRegistry)\n    const assemblePage = createAssemblePageTask(renderContext, renderer)\n\n    return {\n      groups: [\n        { mode: 'sequential' as const, children: [renderBlocks] },\n        { mode: 'sequential' as const, children: [assemblePage] },\n      ],\n    }\n  },\n\n  complete(\n    ctx: WorkContextContract<RequestState, RequestRenderWorkProps>,\n    children: readonly CompletedWork[],\n  ): PhaseWorkOutput {\n    const renderContext = ctx.state.renderContext\n    const output = singleChildOutput(children, RENDER_ASSEMBLE_PAGE_KIND)\n\n    return { action: 'render', renderContext, output }\n  },\n}\n\nexport function createRequestRenderTask(props: RequestRenderWorkProps) {\n  return createWorkTask('render', REQUEST_RENDER_WORK_HANDLER, props, REQUEST_RENDER_WORK_INSTRUMENTATION)\n}\n","import type { ForgeRenderer } from '../../../../framework/types/rendering.type'\nimport type { NodeId } from '../../contracts/ast/ast.type'\nimport type { ValidationRuleFilter } from '../../../concerns/validation/contracts/ValidationWork.type'\nimport type { HttpMethod } from '../../../../framework/types/request.type'\nimport type { RequestSnapshot } from '../../../../framework/types/snapshot.type'\nimport type { MountedNode, MountedStepNode } from '../../registries/MountRegistry'\nimport { buildStepValidationTask } from '../../../concerns/validation/runtime/stepValidationStore'\nimport type { WorkTask } from '../../contracts/work/work.type'\nimport type { RuntimeContext } from '../../contracts/runtime/evaluationState.type'\nimport type { ResponseBindings } from '../../../../framework/types/responseBindings.type'\nimport RequestState from './RequestState'\nimport { createRequestPipelineTask } from './RequestPipelineWorkHandler'\nimport { createRequestContextPreparationTask } from './RequestContextPreparationWorkHandler'\nimport { createRequestAccessTask } from '../../../concerns/hooks/runtime/RequestAccessWorkHandler'\nimport { createRequestAnswerPreparationTask } from '../../../concerns/answer-preparation/runtime/RequestAnswerPreparationWorkHandler'\nimport { createReachabilityValiditiesTask } from '../../../concerns/validation/runtime/ReachabilityValiditiesWorkHandler'\nimport { createRequestReachabilityTask } from '../../../concerns/reachability/runtime/RequestReachabilityWorkHandler'\nimport { createRequestAnswerCleardownTask } from '../../../concerns/answer-cleardown/runtime/RequestAnswerCleardownWorkHandler'\nimport { createRequestSubmitTask } from '../../../concerns/hooks/runtime/RequestSubmitWorkHandler'\nimport { createRequestEntryValidationTask } from '../../../concerns/validation/runtime/RequestEntryValidationWorkHandler'\nimport { createRequestResolveTask } from '../../../concerns/resolve/runtime/RequestResolveWorkHandler'\nimport { createRequestRouteTreeTask } from '../../../concerns/route/runtime/RequestRouteTreeWorkHandler'\nimport { createRequestRenderTask } from '../../../concerns/render/runtime/RequestRenderWorkHandler'\nimport IteratorBudget from './IteratorBudget'\n\nexport interface RequestPipelineConfig {\n  readonly method: HttpMethod\n  readonly node: MountedNode\n  readonly snapshot: RequestSnapshot\n  readonly renderer?: ForgeRenderer<unknown>\n  readonly traceEnabled: boolean\n  readonly responseBindings: ResponseBindings\n  readonly maxIteratorIterations: number\n}\n\nexport default class RequestPipelineBootstrap {\n  constructor(private readonly config: RequestPipelineConfig) {}\n\n  buildPipelineElement(): WorkTask {\n    return createRequestPipelineTask({\n      phases: this.buildPhases(),\n    })\n  }\n\n  buildExecutionContext(): RequestState {\n    const { node } = this.config\n    const { functionRegistry, componentRegistry, compiledStepValidations } = node\n    const compiledValidation = node.kind === 'step' ? node.compiledValidation : undefined\n\n    const context = {\n      request: {},\n      domain: {\n        data: {},\n        answers: {},\n      },\n      evaluation: {},\n    } as RuntimeContext\n\n    context.evaluation.iteratorBudget = new IteratorBudget(this.config.maxIteratorIterations)\n\n    const buildStepValidation = (stepId: NodeId, filter: ValidationRuleFilter) =>\n      buildStepValidationTask(\n        compiledStepValidations.get(stepId) ?? compiledValidation,\n        stepId,\n        context,\n        functionRegistry,\n        filter,\n      )\n\n    return new RequestState(context, {\n      responseBindings: this.config.responseBindings,\n      functionRegistry,\n      componentRegistry,\n      currentStepId: node.kind === 'step' ? node.nodeId : undefined,\n      hasRenderer: this.config.renderer !== undefined,\n      traceEnabled: this.config.traceEnabled,\n      buildStepValidation,\n    })\n  }\n\n  private buildPhases(): readonly WorkTask[] {\n    const { method, node, snapshot } = this.config\n\n    const contextPreparation = createRequestContextPreparationTask({\n      compiledStaticData: node.compiledStaticData,\n      snapshot,\n    })\n\n    const access = createRequestAccessTask({\n      compiled: node.compiledAccessLifecycle,\n      path: node.path,\n    })\n\n    const answerPreparation = createRequestAnswerPreparationTask({\n      compiled: node.compiledAnswerPreparation,\n      path: node.path,\n    })\n\n    const validities = createReachabilityValiditiesTask({\n      compiledStepValidations: node.compiledStepValidations,\n    })\n\n    const reachability = createRequestReachabilityTask({\n      mode: node.kind,\n      compiledReachabilityFacts: node.compiledReachabilityFacts,\n      compiledReachabilityState: node.compiledReachabilityState,\n      compiledFieldInventory: node.compiledFieldInventory,\n      routeTemplateCatalog: node.routeTemplateCatalog,\n      method,\n    })\n\n    if (node.kind === 'journey') {\n      return [contextPreparation, access, answerPreparation, validities, reachability]\n    }\n\n    const stepNode = node as MountedStepNode\n\n    const answerCleardown = createRequestAnswerCleardownTask({})\n\n    const routeTree = createRequestRouteTreeTask({\n      compiled: stepNode.compiledRouteMetadata,\n      path: node.path,\n      routeTree: stepNode.routeTree,\n      currentRouteTemplatePath: stepNode.templatePath,\n    })\n\n    const resolve = createRequestResolveTask({\n      compiled: stepNode.compiledResolve,\n      path: node.path,\n    })\n\n    const terminalPhases = this.buildTerminalPhases(routeTree, resolve, stepNode)\n\n    if (method === 'POST') {\n      const submit = createRequestSubmitTask({\n        compiled: stepNode.compiledSubmitHooks,\n        path: node.path,\n      })\n\n      return [\n        contextPreparation,\n        access,\n        answerPreparation,\n        validities,\n        reachability,\n        answerCleardown,\n        submit,\n        ...terminalPhases,\n      ]\n    }\n\n    const entryValidation = createRequestEntryValidationTask({\n      compiled: stepNode.compiledEntryValidation,\n      path: node.path,\n    })\n\n    return [\n      contextPreparation,\n      access,\n      answerPreparation,\n      validities,\n      reachability,\n      answerCleardown,\n      entryValidation,\n      ...terminalPhases,\n    ]\n  }\n\n  private buildTerminalPhases(routeTree: WorkTask, resolve: WorkTask, stepNode: MountedStepNode): readonly WorkTask[] {\n    const { renderer } = this.config\n\n    if (!renderer) {\n      return [routeTree, resolve]\n    }\n\n    const render = createRequestRenderTask({\n      renderer,\n      componentRegistry: stepNode.componentRegistry,\n    })\n\n    return [routeTree, resolve, render]\n  }\n}\n","import { RequestLocation } from '../../../../framework/types/request.type'\n\nexport type ParsedRedirectTarget =\n  | { kind: 'external'; value: string }\n  | { kind: 'absolute'; value: string }\n  | { kind: 'relative'; value: string }\n\nexport interface ResolvedRedirectTarget {\n  kind: ParsedRedirectTarget['kind']\n  value: string\n  pathname: string\n}\n\nexport function parseRedirectTarget(target: string): ParsedRedirectTarget {\n  if (target.startsWith('http://') || target.startsWith('https://')) {\n    return { kind: 'external', value: target }\n  }\n\n  if (target.startsWith('/')) {\n    return { kind: 'absolute', value: target }\n  }\n\n  return { kind: 'relative', value: target }\n}\n\nexport function resolveRedirectTarget(\n  target: string | ParsedRedirectTarget,\n  location: Pick<RequestLocation, 'origin' | 'pathname'> & { basePath?: string },\n): ResolvedRedirectTarget {\n  const parsedTarget = typeof target === 'string' ? parseRedirectTarget(target) : target\n\n  if (parsedTarget.kind === 'external') {\n    const resolvedUrl = new URL(parsedTarget.value)\n\n    return {\n      kind: parsedTarget.kind,\n      value: resolvedUrl.href,\n      pathname: resolvedUrl.pathname,\n    }\n  }\n\n  if (parsedTarget.kind === 'absolute') {\n    const resolvedUrl = new URL(encodePathTemplate(parsedTarget.value), location.origin)\n    const pathname = decodePathTemplate(resolvedUrl.pathname)\n    const value = decodePathTemplate(`${resolvedUrl.pathname}${resolvedUrl.search}${resolvedUrl.hash}`)\n\n    return {\n      kind: parsedTarget.kind,\n      value,\n      pathname,\n    }\n  }\n\n  const isDotRelative = parsedTarget.value.startsWith('./') || parsedTarget.value.startsWith('../')\n\n  const base =\n    !isDotRelative && location.basePath !== undefined\n      ? `${location.origin}${encodePathTemplate(location.basePath)}/`\n      : `${location.origin}${encodePathTemplate(location.pathname)}`\n\n  const resolvedUrl = new URL(encodePathTemplate(parsedTarget.value), base)\n  const pathname = decodePathTemplate(resolvedUrl.pathname)\n  const value = decodePathTemplate(`${resolvedUrl.pathname}${resolvedUrl.search}${resolvedUrl.hash}`)\n\n  return {\n    kind: parsedTarget.kind,\n    value,\n    pathname,\n  }\n}\n\nfunction encodePathTemplate(path: string): string {\n  return path.replace(/:/g, '%3A')\n}\n\nfunction decodePathTemplate(path: string): string {\n  return path.replace(/%3A/gi, ':')\n}\n","import type { RuntimeContext } from '../../contracts/runtime/evaluationState.type'\nimport type { RequestSnapshot } from '../../../../framework/types/snapshot.type'\nimport { captureContextSnapshot, type ContextSnapshotData } from './contextSnapshot'\nimport type {\n  RequestTrace,\n  RequestTraceError,\n  RequestTracePhase,\n  RequestTraceReachabilityStep,\n  RequestTraceRouteContext,\n  RequestTraceUnit,\n  RuntimeContextSnapshotTrace,\n} from '../../contracts/runtime/trace.type'\nimport type TraceSpan from '../../tracing/TraceSpan'\nimport TraceSpanSerializer from '../../tracing/TraceSpanSerializer'\nimport type {\n  ReachabilityEvaluation,\n  ReachabilityNode,\n} from '../../../concerns/reachability/contracts/reachabilityEvaluation.type'\nimport type { ForgeInstrumentation } from '../../tracing/ForgeTraceSinkDispatcher'\nimport type { RequestPipelineResult } from '../../contracts/runtime/requestPipelineOutput.type'\nimport type { MountedNode } from '../../registries/MountRegistry'\nimport type { NodeId } from '../../contracts/ast/ast.type'\nimport type { RouteTree, RouteTreeNode } from '../../../../framework/types/routeTree.type'\n\ninterface RequestTraceEmissionBase {\n  readonly instrumentation: ForgeInstrumentation\n  readonly snapshot: RequestSnapshot\n  /** The `request.pipeline` root span the work executor produced. */\n  readonly root: TraceSpan\n  readonly node: MountedNode\n  readonly routeTree: RouteTree | undefined\n  readonly reachabilityEvaluation: ReachabilityEvaluation | undefined\n}\n\nexport interface RequestTraceEmission extends RequestTraceEmissionBase {\n  readonly result: RequestPipelineResult\n  /** The fully resolved redirect URL the navigate outcome carries; set only for redirect results. */\n  readonly redirectUrl?: string\n}\n\nexport interface FailedRequestTraceEmission extends RequestTraceEmissionBase {\n  readonly error: unknown\n  readonly context: RuntimeContext\n}\n\nexport default class RequestPipelineTraceProjector {\n  private readonly serializer = new TraceSpanSerializer()\n\n  emit(emission: RequestTraceEmission): void {\n    const { instrumentation, snapshot, root, result, redirectUrl, node, routeTree, reachabilityEvaluation } = emission\n\n    if (!instrumentation.enabled) {\n      return\n    }\n\n    const phases = this.project(root)\n\n    if (phases.length === 0) {\n      return\n    }\n\n    const outcome = this.traceOutcome(result)\n\n    instrumentation.onRequestTrace({\n      snapshot,\n      trace: {\n        outcome,\n        ...this.traceTiming(root),\n        ...this.resultDetail(result, redirectUrl),\n        ...this.reachabilityDetail(reachabilityEvaluation),\n        phases,\n      },\n      route: this.traceRoute(node, routeTree),\n    })\n  }\n\n  emitFailed(emission: FailedRequestTraceEmission): void {\n    const { instrumentation, snapshot, root, error, context, node, routeTree, reachabilityEvaluation } = emission\n\n    if (!instrumentation.enabled) {\n      return\n    }\n\n    const phases = this.projectFailed(root, context)\n\n    if (phases.length === 0) {\n      return\n    }\n\n    instrumentation.onRequestTrace({\n      snapshot,\n      trace: {\n        outcome: 'error',\n        ...this.traceTiming(root),\n        error: this.errorDetail(error),\n        ...this.reachabilityDetail(reachabilityEvaluation),\n        phases,\n      },\n      route: this.traceRoute(node, routeTree),\n    })\n  }\n\n  private project(rootUnit: TraceSpan): RequestTracePhase[] {\n    return rootUnit.children.map(phaseUnit => {\n      const phase = this.phaseName(phaseUnit.kind)\n      const units: RequestTraceUnit[] = phaseUnit.children.map(child => this.serializer.serialize(child))\n\n      if (phaseUnit.completed) {\n        units.push(this.toContextSnapshotUnit(phase, phaseUnit.completeFields as ContextSnapshotData))\n      }\n\n      return { phase, ...this.traceTiming(phaseUnit), units }\n    })\n  }\n\n  projectFailed(rootUnit: TraceSpan, context: RuntimeContext): RequestTracePhase[] {\n    const phases = this.project(rootUnit)\n    const failedIndex = rootUnit.children.length - 1\n    const failedPhase = phases[failedIndex]\n\n    if (failedPhase === undefined || failedPhase.units.some(unit => unit.kind === 'context-snapshot')) {\n      return phases\n    }\n\n    phases[failedIndex] = {\n      ...failedPhase,\n      units: [...failedPhase.units, this.toContextSnapshotUnit(failedPhase.phase, captureContextSnapshot(context))],\n    }\n\n    return phases\n  }\n\n  private toContextSnapshotUnit(phase: string, data: ContextSnapshotData): RuntimeContextSnapshotTrace {\n    return {\n      key: `after-${phase}`,\n      kind: 'context-snapshot',\n      beginFields: {},\n      completeFields: {},\n      completed: true,\n      children: [],\n      answers: data.answers,\n      data: data.data,\n      reachabilityValidities: data.reachabilityValidities,\n      reachability: data.reachability,\n    }\n  }\n\n  private traceOutcome(result: RequestPipelineResult): 'render' | 'redirect' | 'error' {\n    if (result.kind === 'redirect') {\n      return 'redirect'\n    }\n\n    return result.kind\n  }\n\n  private resultDetail(\n    result: RequestPipelineResult,\n    redirectUrl: string | undefined,\n  ): Pick<RequestTrace, 'redirect' | 'error'> {\n    if (result.kind === 'redirect') {\n      return { redirect: { target: redirectUrl ?? result.target } }\n    }\n\n    if (result.kind === 'error') {\n      return { error: { status: result.status, message: result.message } }\n    }\n\n    return {}\n  }\n\n  private errorDetail(error: unknown): RequestTraceError {\n    if (error instanceof Error) {\n      const status = this.errorStatus(error)\n\n      return { message: error.message, stack: error.stack, ...(status === undefined ? {} : { status }) }\n    }\n\n    return { message: String(error) }\n  }\n\n  private errorStatus(error: Error): number | undefined {\n    const status = Reflect.get(error, 'status')\n\n    if (typeof status === 'number') {\n      return status\n    }\n\n    const statusCode = Reflect.get(error, 'statusCode')\n\n    return typeof statusCode === 'number' ? statusCode : undefined\n  }\n\n  private reachabilityDetail(evaluation: ReachabilityEvaluation | undefined): Pick<RequestTrace, 'reachability'> {\n    if (evaluation === undefined) {\n      return {}\n    }\n\n    // The trace is an immutable buffered record; the live evaluation's node arrays are shared and\n    // mutated in place by the graph builder, so copy every array rather than alias it.\n    return {\n      reachability: {\n        currentStepId: evaluation.currentStepId,\n        steps: evaluation.steps.map(step => this.reachabilityStep(step)),\n        defaultEntryRouteTemplatePath: evaluation.defaultEntryRouteTemplatePath,\n        frontierRouteTemplatePath: evaluation.frontierRouteTemplatePath,\n        canonicalPathRouteTemplatePaths: [...evaluation.canonicalPathRouteTemplatePaths],\n        progressExists: evaluation.progressExists,\n        resumeActive: evaluation.resumeActive,\n        resumeOutcome: evaluation.resumeOutcome,\n        unreachableRedirect: evaluation.unreachableRedirect,\n      },\n    }\n  }\n\n  private reachabilityStep(step: ReachabilityNode): RequestTraceReachabilityStep {\n    return {\n      stepId: step.stepId,\n      routeTemplatePath: step.routeTemplatePath,\n      code: step.code,\n      declarationIndex: step.declarationIndex,\n      isEntryPoint: step.isEntryPoint,\n      isConditionalEntry: step.isConditionalEntry,\n      hasValidation: step.hasValidation,\n      isReachable: step.isReachable,\n      isValid: step.isValid,\n      forwardRouteTemplatePaths: [...step.forwardRouteTemplatePaths],\n      ...(step.declaredForwardRouteTemplatePaths\n        ? { declaredForwardRouteTemplatePaths: [...step.declaredForwardRouteTemplatePaths] }\n        : {}),\n      predecessorRouteTemplatePaths: [...step.predecessorRouteTemplatePaths],\n      tieBreakerPriority: step.tieBreakerPriority,\n    }\n  }\n\n  private traceRoute(node: MountedNode, routeTree: RouteTree | undefined): RequestTraceRouteContext {\n    const activeBranch = routeTree ? this.collectActiveBranch(routeTree) : []\n\n    return {\n      journeyCode: node.journeyCode,\n      routeTemplatePath: node.templatePath,\n      journeyTitle: this.journeyTitle(activeBranch),\n      stepTitle: this.stepTitle(activeBranch, node.nodeId),\n    }\n  }\n\n  private journeyTitle(activeBranch: readonly RouteTreeNode[]): string | undefined {\n    return activeBranch.find(node => node.route?.kind === 'journey')?.route?.title\n  }\n\n  private stepTitle(activeBranch: readonly RouteTreeNode[], nodeId: NodeId): string | undefined {\n    const matched = activeBranch.find(node => node.route?.nodeId === nodeId)\n\n    if (matched?.route?.title !== undefined) {\n      return matched.route.title\n    }\n\n    return [...activeBranch].reverse().find(node => node.route !== undefined)?.route?.title\n  }\n\n  private collectActiveBranch(nodes: readonly RouteTreeNode[]): RouteTreeNode[] {\n    const active = nodes.find(node => node.active)\n\n    if (active === undefined) {\n      return []\n    }\n\n    return [active, ...this.collectActiveBranch(active.children)]\n  }\n\n  private traceTiming(traceSpan: TraceSpan): Pick<RequestTrace, 'startedAtMs' | 'completedAtMs' | 'durationMs'> {\n    return {\n      startedAtMs: traceSpan.startedAtMs,\n      completedAtMs: traceSpan.completedAtMs,\n      durationMs: traceSpan.durationMs,\n    }\n  }\n\n  private phaseName(kind: string): string {\n    const prefix = 'request.'\n\n    return kind.startsWith(prefix) ? kind.slice(prefix.length) : kind\n  }\n}\n","import type { CookieOptions } from './response.type'\n\nexport interface ResponseBindings {\n  setHeader(name: string, value: string): void\n  setCookie(name: string, value: string, options?: CookieOptions): void\n}\n\nexport const NO_OP_RESPONSE_BINDINGS: ResponseBindings = {\n  setHeader(_name, _value) {\n    /* no-op */\n  },\n  setCookie(_name, _value, _options) {\n    /* no-op */\n  },\n}\n","import type { RequestSnapshot } from '../../../../framework/types/snapshot.type'\nimport type { ForgeError, ForgeOutcome } from '../../../../framework/types/outcome.type'\nimport type { MountedNode } from '../../registries/MountRegistry'\nimport type RequestState from './RequestState'\nimport type { RequestPipelineResult } from '../../contracts/runtime/requestPipelineOutput.type'\nimport RequestPipelineBootstrap from './RequestPipelineBootstrap'\nimport { resolveRedirectTarget } from '../../../concerns/route/runtime/redirectTarget'\nimport WorkContext from '../../work/WorkContext'\nimport WorkExecutor from '../../work/WorkExecutor'\nimport WorkExecutionError from '../../work/WorkExecutionError'\nimport type { WorkTask } from '../../contracts/work/work.type'\nimport type { ForgeInstrumentation } from '../../tracing/ForgeTraceSinkDispatcher'\nimport type { ForgeRenderer } from '../../../../framework/types/rendering.type'\nimport RequestPipelineTraceProjector from './RequestPipelineTraceProjector'\nimport { resolvePathParams } from '../../../../shared/routePath'\nimport { NO_OP_RESPONSE_BINDINGS, type ResponseBindings } from '../../../../framework/types/responseBindings.type'\n\nexport interface RequestPipelineOptions {\n  readonly instrumentation: ForgeInstrumentation\n  readonly maxIteratorIterations: number\n}\n\nexport interface RequestEvaluationRequest {\n  readonly node: MountedNode\n  readonly snapshot: RequestSnapshot\n  readonly responseBindings?: ResponseBindings\n  readonly renderer?: ForgeRenderer<unknown>\n}\n\ninterface PreparedPipeline {\n  readonly executionContext: RequestState\n  readonly pipelineElement: WorkTask\n}\n\nexport default class RequestPipeline {\n  constructor(\n    private readonly options: RequestPipelineOptions,\n    private readonly traceProjector = new RequestPipelineTraceProjector(),\n  ) {}\n\n  async evaluate(requestInput: RequestEvaluationRequest): Promise<ForgeOutcome<unknown>> {\n    const { node, snapshot, renderer, responseBindings = NO_OP_RESPONSE_BINDINGS } = requestInput\n\n    const instrumentation = this.options.instrumentation.forRequest(snapshot)\n\n    const { executionContext, pipelineElement } = this.preparePipeline(\n      node,\n      snapshot,\n      responseBindings,\n      instrumentation,\n      renderer,\n    )\n\n    const pipelineResult = await this.run(node, executionContext, pipelineElement, snapshot, instrumentation)\n\n    return this.buildOutcome(pipelineResult, snapshot)\n  }\n\n  private preparePipeline(\n    node: MountedNode,\n    snapshot: RequestSnapshot,\n    responseBindings: ResponseBindings,\n    instrumentation: ForgeInstrumentation,\n    renderer?: ForgeRenderer<unknown>,\n  ): PreparedPipeline {\n    const bootstrap = new RequestPipelineBootstrap({\n      method: snapshot.method,\n      node,\n      snapshot,\n      renderer,\n      traceEnabled: instrumentation.enabled,\n      maxIteratorIterations: this.options.maxIteratorIterations,\n      responseBindings,\n    })\n\n    return {\n      executionContext: bootstrap.buildExecutionContext(),\n      pipelineElement: bootstrap.buildPipelineElement(),\n    }\n  }\n\n  private async run(\n    node: MountedNode,\n    requestState: RequestState,\n    pipelineElement: WorkTask,\n    snapshot: RequestSnapshot,\n    instrumentation: ForgeInstrumentation,\n  ): Promise<RequestPipelineResult> {\n    try {\n      const workExecutor = new WorkExecutor(instrumentation.enabled)\n\n      const completed = await workExecutor.executeWithUnit(pipelineElement, new WorkContext(requestState))\n\n      const pipelineResult = requestState.pipelineResult\n\n      this.traceProjector.emit({\n        instrumentation,\n        snapshot,\n        root: completed.traceSpan,\n        result: pipelineResult,\n        redirectUrl:\n          pipelineResult.kind === 'redirect' ? this.resolveRedirectUrl(pipelineResult.target, snapshot) : undefined,\n        node,\n        routeTree: requestState.routeTree,\n        reachabilityEvaluation: requestState.reachabilityEvaluation,\n      })\n\n      return pipelineResult\n    } catch (error) {\n      if (error instanceof WorkExecutionError) {\n        let unwrapped: unknown = error\n\n        while (unwrapped instanceof WorkExecutionError) {\n          unwrapped = unwrapped.original\n        }\n\n        this.traceProjector.emitFailed({\n          instrumentation,\n          snapshot,\n          root: error.traceSpan,\n          error: unwrapped,\n          context: requestState.context,\n          node,\n          routeTree: requestState.routeTree,\n          reachabilityEvaluation: requestState.reachabilityEvaluation,\n        })\n\n        throw unwrapped\n      }\n\n      throw error\n    }\n  }\n\n  private buildOutcome(result: RequestPipelineResult, snapshot: RequestSnapshot): ForgeOutcome<unknown> {\n    if (result.kind === 'redirect') {\n      return {\n        kind: 'navigate',\n        url: this.resolveRedirectUrl(result.target, snapshot),\n      }\n    }\n\n    if (result.kind === 'error') {\n      const error: ForgeError = Object.assign(new Error(result.message), {\n        status: result.status,\n        statusCode: result.status,\n      })\n\n      return {\n        kind: 'error',\n        error,\n      }\n    }\n\n    return {\n      kind: 'render',\n      context: result.context,\n      output: result.output,\n    }\n  }\n\n  private resolveRedirectUrl(target: string, snapshot: RequestSnapshot): string {\n    const withParams = resolvePathParams(target, snapshot.params)\n\n    return resolveRedirectTarget(withParams, snapshot.location).value\n  }\n}\n","// eslint-disable-next-line max-classes-per-file\nimport type { RequestTraceEvent } from '../contracts/runtime/trace.type'\nimport type { RequestSnapshot } from '../../../framework/types/snapshot.type'\nimport type { CompilationTraceEvent } from '../contracts/compilation/trace.type'\n\nexport interface ForgeInstrumentationOptions {\n  readonly sinks?: readonly ForgeInstrumentationSink[]\n}\n\nexport interface ForgeInstrumentationSink {\n  onRequestTrace(event: RequestTraceEvent): void\n  onCompilationTrace?(event: CompilationTraceEvent): void\n\n  /**\n   * Per-request opt-in. When present, request tracing only runs when at least\n   * one sink returns true for the request; sinks without it always want traces.\n   * Decided once per request, and delivery is scoped to the accepting sinks.\n   */\n  shouldTrace?(snapshot: RequestSnapshot): boolean\n}\n\nexport interface ForgeInstrumentation {\n  readonly enabled: boolean\n\n  /**\n   * Resolves the sinks that want this request (shouldTrace, decided once at\n   * request start) into an instrumentation view scoped to those sinks - its\n   * `enabled` and `onRequestTrace` reflect only the accepting sinks.\n   */\n  forRequest(snapshot: RequestSnapshot): ForgeInstrumentation\n  onRequestTrace(event: RequestTraceEvent): void\n  onCompilationTrace(event: CompilationTraceEvent): void\n}\n\nexport default class ForgeTraceSinkDispatcher implements ForgeInstrumentation {\n  private readonly sinks: readonly ForgeInstrumentationSink[]\n\n  constructor(options: ForgeInstrumentationOptions = {}) {\n    this.sinks = options.sinks ?? []\n  }\n\n  get enabled(): boolean {\n    return this.sinks.length > 0\n  }\n\n  forRequest(snapshot: RequestSnapshot): ForgeInstrumentation {\n    const acceptedSinks = this.sinks.filter(sink => sink.shouldTrace?.(snapshot) ?? true)\n\n    return new RequestScopedInstrumentation(acceptedSinks)\n  }\n\n  onRequestTrace(event: RequestTraceEvent): void {\n    this.sinks.forEach(sink => {\n      sink.onRequestTrace(event)\n    })\n  }\n\n  onCompilationTrace(event: CompilationTraceEvent): void {\n    this.sinks.forEach(sink => {\n      sink.onCompilationTrace?.(event)\n    })\n  }\n}\n\nclass RequestScopedInstrumentation implements ForgeInstrumentation {\n  constructor(private readonly sinks: readonly ForgeInstrumentationSink[]) {}\n\n  get enabled(): boolean {\n    return this.sinks.length > 0\n  }\n\n  forRequest(): ForgeInstrumentation {\n    return this\n  }\n\n  onRequestTrace(event: RequestTraceEvent): void {\n    this.sinks.forEach(sink => {\n      sink.onRequestTrace(event)\n    })\n  }\n\n  onCompilationTrace(event: CompilationTraceEvent): void {\n    this.sinks.forEach(sink => {\n      sink.onCompilationTrace?.(event)\n    })\n  }\n}\n","import { formatCallsite } from '../../shared/diagnostics/formatCallsite'\n\ninterface DiagnosticError {\n  readonly name?: unknown\n  readonly message?: unknown\n  readonly formattedPath?: unknown\n  readonly expected?: unknown\n  readonly functionName?: unknown\n  readonly functionType?: unknown\n  readonly variant?: unknown\n  readonly phase?: unknown\n  readonly nodeId?: unknown\n  readonly cause?: unknown\n  readonly callsite?: { readonly stack?: string }\n}\n\nexport default class RegistrationErrorFormatter {\n  static format(error: unknown): unknown {\n    if (error instanceof AggregateError) {\n      return RegistrationErrorFormatter.formatAggregate(error)\n    }\n\n    return error\n  }\n\n  private static formatAggregate(error: AggregateError): string {\n    const entries = error.errors.map((entry, index) => RegistrationErrorFormatter.formatEntry(entry, index))\n\n    return [`Forge registration failed: ${error.message}`, '', ...entries].join('\\n')\n  }\n\n  private static formatEntry(error: unknown, index: number): string {\n    const diagnostic = RegistrationErrorFormatter.toDiagnostic(error)\n    const title = RegistrationErrorFormatter.formatTitle(diagnostic, error)\n    const fields = RegistrationErrorFormatter.formatFields(diagnostic)\n\n    return [`${index + 1}. ${title}`, ...fields.map(field => `   ${field}`)].join('\\n')\n  }\n\n  private static formatTitle(diagnostic: DiagnosticError | undefined, error: unknown): string {\n    const name = RegistrationErrorFormatter.formatValue(diagnostic?.name)\n    const message = RegistrationErrorFormatter.formatValue(diagnostic?.message)\n\n    if (name && message) {\n      return `${name}: ${message}`\n    }\n\n    if (message) {\n      return message\n    }\n\n    return RegistrationErrorFormatter.formatValue(error) ?? String(error)\n  }\n\n  private static formatFields(diagnostic: DiagnosticError | undefined): string[] {\n    if (!diagnostic) {\n      return []\n    }\n\n    const fields = [\n      { label: 'Phase', value: RegistrationErrorFormatter.formatValue(diagnostic.phase) },\n      { label: 'Path', value: RegistrationErrorFormatter.formatValue(diagnostic.formattedPath) },\n      { label: 'Node', value: RegistrationErrorFormatter.formatValue(diagnostic.nodeId) },\n      { label: 'Expected', value: RegistrationErrorFormatter.formatValue(diagnostic.expected) },\n      { label: 'Function', value: RegistrationErrorFormatter.formatValue(diagnostic.functionName) },\n      { label: 'Type', value: RegistrationErrorFormatter.formatValue(diagnostic.functionType) },\n      { label: 'Variant', value: RegistrationErrorFormatter.formatValue(diagnostic.variant) },\n      { label: 'Defined at', value: RegistrationErrorFormatter.formatCallsiteValue(diagnostic.callsite) },\n      { label: 'Cause', value: RegistrationErrorFormatter.formatValue(diagnostic.cause) },\n    ]\n\n    return fields\n      .filter(field => field.value !== undefined)\n      .map(field => `${field.label}: ${field.value}`)\n  }\n\n  private static toDiagnostic(error: unknown): DiagnosticError | undefined {\n    if (!error || typeof error !== 'object') {\n      return undefined\n    }\n\n    return error as DiagnosticError\n  }\n\n  private static formatCallsiteValue(callsite: { readonly stack?: string } | undefined): string | undefined {\n    return typeof callsite?.stack === 'string' ? formatCallsite(callsite) : undefined\n  }\n\n  private static formatValue(value: unknown): string | undefined {\n    if (value === undefined || value === null || value === '') {\n      return undefined\n    }\n\n    return String(value)\n  }\n}\n","import ForgeBaseError from './ForgeBaseError'\n\nexport default class ForgeRegistrationError extends ForgeBaseError {\n  constructor(message: string) {\n    super(message)\n    this.stack = this.message\n  }\n}\n","import PackageInstance from './PackageInstance'\nimport type {\n  ForgeDependencies,\n  ForgePackageFunctions,\n  ForgePackageRegistration,\n} from './chassis/contracts/ast/engine.type'\nimport FunctionRegistry from './chassis/registries/FunctionRegistry'\nimport ComponentRegistry from './chassis/registries/ComponentRegistry'\nimport type { ComponentRegistryEntry } from '../components/types/components.type'\nimport type { BlockDefinition } from '../components/types/structures.type'\nimport { createFunctionsRegistry } from '../authoring/utils/deprecated/createFunctionsRegistry'\nimport { ConditionsRegistry } from '../built-ins/functions/conditions'\nimport { GeneratorsRegistry } from '../built-ins/functions/generators'\nimport { TransformersRegistry } from '../built-ins/functions/transformers'\nimport { coreComponents } from '../built-ins/components'\nimport { isFunctionRegistry } from '../authoring/registries/BaseFunctionRegistry'\nimport { ForgeDeprecations } from '../shared/ForgeDeprecations'\nimport type { FunctionImplementations, FunctionShapeMap } from '../authoring/utils/deprecated/defineFunction.type'\nimport type { Logger } from '../framework/types/adapter.type'\nimport type { ForgeRenderer } from '../framework/types/rendering.type'\nimport type { ForgeError, ForgeOutcome } from '../framework/types/outcome.type'\nimport type { RequestSnapshot } from '../framework/types/snapshot.type'\nimport type { ResponseBindings } from '../framework/types/responseBindings.type'\nimport type { ForgeTopology } from '../framework/types/topology.type'\nimport MountRegistry from './chassis/registries/MountRegistry'\nimport RequestPipeline from './chassis/runtime/pipeline/RequestPipeline'\nimport ForgeTraceSinkDispatcher from './chassis/tracing/ForgeTraceSinkDispatcher'\nimport type { ForgeInstrumentation, ForgeInstrumentationOptions } from './chassis/tracing/ForgeTraceSinkDispatcher'\nimport RegistrationErrorFormatter from './errors/RegistrationErrorFormatter'\nimport ForgeRegistrationError from './errors/ForgeRegistrationError'\nimport ForgeInternalError from './errors/ForgeInternalError'\nimport { DEFAULT_MAX_ITERATOR_ITERATIONS } from './chassis/runtime/pipeline/IteratorBudget'\n\nexport interface ForgeExecutionRequest {\n  readonly snapshot: RequestSnapshot\n  readonly responseBindings?: ResponseBindings\n  readonly renderer?: ForgeRenderer<unknown>\n}\n\n/**\n * @deprecated Build framework routers directly, for example `createExpressRouter(forge, options)`.\n */\nexport interface ForgeRouterAdapter {\n  build(forge: Forge): unknown\n}\n\nexport interface ForgeOptions {\n  /** Skip registering built-in functions (conditions, transformers, effects). Default: false */\n  disableBuiltInFunctions?: boolean\n\n  /** Skip registering built-in components (html, collection-block). Default: false */\n  disableBuiltInComponents?: boolean\n\n  /** Enable debug logging for compilation and evaluation. Default: false */\n  debug?: boolean\n\n  /**\n   * When `true` (default), registration errors from `registerPackage()`\n   * throw immediately — fail fast on invalid journey\n   * definitions, schema errors, duplicate routes, or compilation failures.\n   *\n   * When `false`, registration errors are logged via the configured logger\n   * and the application continues starting — the failing journey simply\n   * won't be available at runtime.\n   *\n   * @default true\n   */\n  strictRegistration?: boolean\n\n  /** Logger instance for forge output */\n  logger?: Logger | Console\n\n  /**\n   * Base path prefix for all routes.\n   *\n   * When set, all routes will be mounted under this path automatically.\n   * Navigation metadata and redirects will include this prefix.\n   *\n   * @example\n   * ```typescript\n   * const forge = new Forge({ basePath: '/forms' })\n   * app.use(createExpressRouter(forge, { nunjucksEnv }))  // Routes at /forms/journey/step\n   * ```\n   *\n   * @default ''\n   */\n  basePath?: string\n\n  instrumentation?: ForgeInstrumentationOptions\n\n  /** Maximum cumulative iterator iterations allowed during one request. Default: 10,000 */\n  maxIteratorIterations?: number\n\n  /**\n   * @deprecated Build framework routers directly, for example `createExpressRouter(forge, options)`.\n   */\n  frameworkAdapter?: ForgeRouterAdapter\n}\n\nexport default class Forge {\n  private readonly options: Required<Omit<ForgeOptions, 'frameworkAdapter'>> & Pick<ForgeOptions, 'frameworkAdapter'>\n\n  private readonly functionRegistry = new FunctionRegistry()\n\n  private readonly componentRegistry = new ComponentRegistry()\n\n  private readonly dependencies: ForgeDependencies\n\n  private readonly mountRegistry: MountRegistry\n\n  private readonly instrumentation: ForgeInstrumentation\n\n  private readonly requestPipeline: RequestPipeline\n\n  /**\n   * Create a new Forge instance\n   * Use this for package registration, component/function registries, and routing.\n   *\n   * @param constructorOptions - Configuration options for Forge\n   *\n   * @example\n   * ```typescript\n   * import { Forge } from '.'\n   * import { createExpressRouter } from '@ministryofjustice/hmpps-forge/express-nunjucks'\n   * import { govukComponents } from '@ministryofjustice/hmpps-forge/govuk-components'\n   *\n   * const forge = new Forge({ logger })\n   *   .registerGlobalComponents(govukComponents(nunjucksEnv))\n   *   .registerPackage(myPackage)\n   *\n   * app.use(createExpressRouter(forge, { nunjucksEnv }))\n   * ```\n   */\n  constructor(constructorOptions: ForgeOptions) {\n    const defaultOptions = {\n      disableBuiltInFunctions: false,\n      disableBuiltInComponents: false,\n      debug: false,\n      strictRegistration: true,\n      logger: console,\n      basePath: '',\n      instrumentation: {},\n      maxIteratorIterations: DEFAULT_MAX_ITERATOR_ITERATIONS,\n    }\n\n    this.options = {\n      ...defaultOptions,\n      ...constructorOptions,\n    }\n\n    if (!this.options.disableBuiltInFunctions) {\n      this.functionRegistry.register(ConditionsRegistry)\n      this.functionRegistry.register(TransformersRegistry)\n      this.functionRegistry.register(GeneratorsRegistry)\n    }\n\n    if (!this.options.disableBuiltInComponents) {\n      this.componentRegistry.registerMany([...coreComponents])\n    }\n\n    this.dependencies = {\n      logger: this.options.logger,\n    }\n\n    this.mountRegistry = new MountRegistry(this.options.basePath)\n    this.instrumentation = new ForgeTraceSinkDispatcher(this.options.instrumentation)\n    this.requestPipeline = new RequestPipeline({\n      instrumentation: this.instrumentation,\n      maxIteratorIterations: this.options.maxIteratorIterations,\n    })\n  }\n\n  /** Add a component to the global registry, making it available to all journeys. */\n  registerGlobalComponent(component: ComponentRegistryEntry<BlockDefinition, unknown>): this {\n    this.componentRegistry.registerMany([component])\n\n    return this\n  }\n\n  /** Add components to the global registry, making them available to all journeys. */\n  registerGlobalComponents(components: ComponentRegistryEntry<BlockDefinition, unknown>[]): this {\n    this.componentRegistry.registerMany(components)\n\n    return this\n  }\n\n  /** Add functions to the global registry, making them available to all journeys. */\n  registerGlobalFunctions<TDeps>(functions: ForgePackageFunctions<TDeps>, deps?: TDeps): this {\n    const resolvedDeps = (deps ?? {}) as TDeps\n\n    if (isFunctionRegistry(functions)) {\n      this.functionRegistry.register(functions.build(resolvedDeps))\n    } else if (Array.isArray(functions)) {\n      functions.forEach(registry => {\n        if (isFunctionRegistry(registry)) {\n          this.functionRegistry.register(registry.build(resolvedDeps))\n        }\n      })\n    } else {\n      this.functionRegistry.register(\n        createFunctionsRegistry(functions as FunctionImplementations<FunctionShapeMap, TDeps>, resolvedDeps),\n      )\n    }\n\n    return this\n  }\n\n  /**\n   * Register a package (journey + custom functions + components) with optional dependencies.\n   *\n   * This is a convenience method that registers components, functions, and the journey\n   * in the correct order.\n   *\n   * @param pkg - The package containing journey, functions, and optional components\n   * @param deps - Dependencies required by the package's functions (optional for packages with no deps)\n   *\n   * @example\n   * ```typescript\n   * // Package with dependencies\n   * forge.registerPackage(myPackage, { api: services.apiClient })\n   *\n   * // Package without dependencies\n   * forge.registerPackage(simplePackage)\n   *\n   * // Conditionally disabled package\n   * forge.registerPackage(createForgePackage({\n   *   enabled: config.featureFlags.myFormEnabled,\n   *   journey: myJourney,\n   * }))\n   * ```\n   */\n  registerPackage<TDeps>(pkg: ForgePackageRegistration<TDeps>, deps?: TDeps): this {\n    if (!pkg || (pkg as { forgePackage?: unknown }).forgePackage !== true) {\n      this.handleRegistrationError(\n        new ForgeRegistrationError(\n          'Packages must be created with createForgePackage(...) before registration. ' +\n            'Wrap your package definition: registerPackage(createForgePackage({ journey, ... }))',\n        ),\n      )\n\n      return this\n    }\n\n    if (pkg.enabled === false) {\n      return this\n    }\n\n    try {\n      const packageInstance = new PackageInstance(pkg, {\n        functionRegistry: this.functionRegistry,\n        componentRegistry: this.componentRegistry,\n        functionDependencies: deps,\n        instrumentation: this.instrumentation,\n      })\n\n      this.registerPackageInstance(packageInstance)\n    } catch (e) {\n      this.handleRegistrationError(e)\n    }\n\n    return this\n  }\n\n  private registerPackageInstance(packageInstance: PackageInstance): void {\n    this.mountRegistry.register(packageInstance)\n  }\n\n  private handleRegistrationError(e: unknown): void {\n    const formatted = RegistrationErrorFormatter.format(e)\n\n    if (this.options.strictRegistration) {\n      if (typeof formatted === 'string') {\n        throw new ForgeRegistrationError(formatted)\n      }\n\n      throw e\n    }\n\n    this.options.logger.error(e instanceof Error ? e : new Error(String(e)))\n  }\n\n  /**\n   * The routes exposed by the registered journeys, as plain data.\n   *\n   * Adapters consume this to register routes with their framework and to map an\n   * incoming request back to a {@link RequestSnapshot.nodeId}.\n   */\n  getTopology(): ForgeTopology {\n    return this.mountRegistry.getTopology()\n  }\n\n  getDependencies(): ForgeDependencies {\n    return this.dependencies\n  }\n\n  /** The configured logger. */\n  getLogger(): Logger | Console {\n    return this.options.logger\n  }\n\n  getInstrumentation(): ForgeInstrumentation {\n    return this.instrumentation\n  }\n\n  /**\n   * @deprecated Build framework routers directly, for example `createExpressRouter(forge, options)`.\n   */\n  getRouter(): unknown {\n    ForgeDeprecations.warn(\n      'FORGE_DEP_getRouter',\n      'frameworkAdapter and getRouter() are deprecated - build framework routers directly, for example createExpressRouter(forge, options).',\n    )\n\n    if (!this.options.frameworkAdapter) {\n      throw new Error(\n        'getRouter() requires a frameworkAdapter. Pass one to new Forge({ frameworkAdapter }), ' +\n          'or build the router directly (e.g. createExpressRouter(forge, options)).',\n      )\n    }\n\n    return this.options.frameworkAdapter.build(this)\n  }\n\n  async execute(request: ForgeExecutionRequest): Promise<ForgeOutcome<unknown>> {\n    try {\n      const node = this.mountRegistry.getNode(request.snapshot.nodeId)\n\n      if (!node) {\n        throw new ForgeInternalError(`No node registered for \"${request.snapshot.nodeId}\"`)\n      }\n\n      return await this.requestPipeline.evaluate({ node, ...request })\n    } catch (error) {\n      return { kind: 'error', error: this.toError(error) }\n    }\n  }\n\n  private toError(error: unknown): ForgeError {\n    if (error instanceof Error) {\n      return error\n    }\n\n    return new Error(String(error), { cause: error })\n  }\n}\n","import type { RenderBlock } from '../../../../framework/types/rendering.type'\nimport { RENDER_BLOCK_BRAND } from '../../render/contracts/renderBlock.brand'\n\nexport function isRenderBlock(obj: unknown): obj is RenderBlock {\n  return obj != null && typeof obj === 'object' && RENDER_BLOCK_BRAND in obj\n}\n"],"mappings":";;;AAIA,SAAS,eAAe,OAA4C;CAClE,IAAI,OAAO,UAAU,YACnB,OAAO;CAGT,OAAQ,MAAkD;AAC5D;AAEA,SAAS,oBAAoB,OAA0C;CACrE,OAAQ,MAA0C;AACpD;AAwBA,SAAgB,wBACd,iBACA,MACwB;CACxB,MAAM,eAAgB,QAAQ,CAAC;CAC/B,MAAM,WAAW,CAAC;CAElB,OAAO,KAAK,eAAe,CAAC,CAAC,SAAQ,SAAQ;EAC3C,MAAM,QAAS,gBAA4C;EAE3D,MAAM,WADU,eAAe,KACR,CAAC,CAAC,YAAY;EACrC,MAAM,eAAe,oBAAoB,KAAK;EAE9C,SAAS,QAAQ;GACf;GACA;GACA;EACF;CACF,CAAC;CAED,OAAO;AACT;;;;;;;;ACtDA,IAAY,eAAL,yBAAA,cAAA;CACL,aAAA,eAAA;CACA,aAAA,iBAAA;CACA,aAAA,eAAA;CACA,aAAA,YAAA;;AACF,EAAA,CAAA,CAAA;;;;;;AA0BA,IAAY,iBAAL,yBAAA,gBAAA;CACL,eAAA,eAAA;CACA,eAAA,cAAA;CACA,eAAA,aAAA;CACA,eAAA,UAAA;CACA,eAAA,gBAAA;CACA,eAAA,aAAA;CACA,eAAA,iBAAA;CACA,eAAA,WAAA;CACA,eAAA,iBAAA;;AACF,EAAA,CAAA,CAAA;;;;;AAMA,IAAY,eAAL,yBAAA,cAAA;CACL,aAAA,SAAA;CACA,aAAA,YAAA;CACA,aAAA,UAAA;CACA,aAAA,UAAA;CACA,aAAA,WAAA;CACA,aAAA,WAAA;;AACF,EAAA,CAAA,CAAA;;;;;AAMA,IAAY,gBAAL,yBAAA,eAAA;CACL,cAAA,UAAA;CACA,cAAA,SAAA;CACA,cAAA,QAAA;CACA,cAAA,SAAA;CACA,cAAA,SAAA;;AACF,EAAA,CAAA,CAAA;;;;;;;AAQA,IAAY,0BAAL,yBA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