typebars 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/analyzer.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { dispatchAnalyze } from \"./dispatch.ts\";\nimport {\n\tcreateMissingArgumentMessage,\n\tcreatePropertyNotFoundMessage,\n\tcreateRootPathTraversalMessage,\n\tcreateTypeMismatchMessage,\n\tcreateUnanalyzableMessage,\n\tcreateUnknownHelperMessage,\n} from \"./errors\";\nimport { DefaultHelpers } from \"./helpers/default-helpers.ts\";\nimport { MapHelpers } from \"./helpers/map-helpers.ts\";\nimport {\n\tdetectLiteralType,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisThisExpression,\n\tparse,\n} from \"./parser\";\nimport {\n\tfindConditionalSchemaLocations,\n\tisPropertyRequired,\n\tresolveArrayItems,\n\tresolveSchemaPath,\n\tsimplifySchema,\n} from \"./schema-resolver\";\nimport type {\n\tAnalysisResult,\n\tDiagnosticCode,\n\tDiagnosticDetails,\n\tHelperDefinition,\n\tTemplateDiagnostic,\n\tTemplateInput,\n} from \"./types.ts\";\nimport {\n\tdeepEqual,\n\textractSourceSnippet,\n\tgetSchemaPropertyNames,\n} from \"./utils\";\n\n// ─── Static Analyzer ─────────────────────────────────────────────────────────\n// Static analysis of a Handlebars template against a JSON Schema v7\n// describing the available context.\n//\n// Merged architecture (v2):\n// A single AST traversal performs both **validation** and **return type\n// inference** simultaneously. This eliminates duplication between the former\n// `validate*` and `infer*` functions and improves performance by avoiding\n// a double traversal.\n//\n// Context:\n// The analysis context uses a **save/restore** pattern instead of creating\n// new objects on each recursion (`{ ...ctx, current: X }`). This reduces\n// GC pressure for deeply nested templates.\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows referencing a variable from a specific\n// schema, identified by an integer N. The optional `identifierSchemas`\n// parameter provides a mapping `{ [id]: JSONSchema7 }`.\n//\n// Resolution rules:\n// - `{{meetingId}}` → validated against `inputSchema` (standard behavior)\n// - `{{meetingId:1}}` → validated against `identifierSchemas[1]`\n// - `{{meetingId:1}}` without `identifierSchemas[1]` → error\n\n// ─── Internal Types ──────────────────────────────────────────────────────────\n\n/** Context passed recursively during AST traversal */\ninterface AnalysisContext {\n\t/** Root schema (for resolving $refs) */\n\troot: JSONSchema7;\n\t/** Current context schema (changes with #each, #with) — mutated via save/restore */\n\tcurrent: JSONSchema7;\n\t/** Diagnostics accumulator */\n\tdiagnostics: TemplateDiagnostic[];\n\t/** Full template source (for extracting error snippets) */\n\ttemplate: string;\n\t/** Schemas by template identifier (for the {{key:N}} syntax) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Registered custom helpers (for static analysis) */\n\thelpers?: Map<string, HelperDefinition>;\n\t/**\n\t * Explicit coercion schema provided by the caller.\n\t * When set, static literal values like `\"123\"` will respect the type\n\t * declared in this schema instead of being auto-detected by\n\t * `detectLiteralType`. Unlike the previous `expectedOutputType`,\n\t * this is NEVER derived from the inputSchema — it must be explicitly\n\t * provided via the `coerceSchema` option.\n\t */\n\tcoerceSchema?: JSONSchema7;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/** Options for the standalone `analyze()` function */\nexport interface AnalyzeOptions {\n\t/** Schemas by template identifier (for the `{{key:N}}` syntax) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/**\n\t * Explicit coercion schema. When provided, static literal values\n\t * will respect the types declared in this schema instead of being\n\t * auto-detected by `detectLiteralType`.\n\t *\n\t * This schema is independent from the `inputSchema` (which describes\n\t * available variables) — it only controls the output type inference\n\t * for static content.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/**\n\t * When `true`, properties whose values contain Handlebars expressions\n\t * (i.e. any `{{…}}` syntax) are excluded from the output schema.\n\t *\n\t * Only the properties with static values (literals, plain strings\n\t * without expressions) are retained. This is useful when you want\n\t * the output schema to describe only the known, compile-time-constant\n\t * portion of the template.\n\t *\n\t * This option only has an effect on **object** and **array** templates.\n\t * A root-level string template with expressions is analyzed normally\n\t * (there is no parent property to exclude it from).\n\t *\n\t * @default false\n\t */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Coerce Text Value ──────────────────────────────────────────────────────\n\n/**\n * Parses a raw text string into the appropriate JS primitive according to the\n * target JSON Schema type. Used when `coerceSchema` overrides the default\n * `detectLiteralType` inference for static literal values.\n */\nfunction coerceTextValue(\n\ttext: string,\n\ttargetType: \"string\" | \"number\" | \"integer\" | \"boolean\" | \"null\",\n): string | number | boolean | null | undefined {\n\tswitch (targetType) {\n\t\tcase \"number\":\n\t\tcase \"integer\": {\n\t\t\tif (text === \"\") return undefined;\n\t\t\tconst num = Number(text);\n\t\t\tif (Number.isNaN(num)) return undefined;\n\t\t\tif (targetType === \"integer\" && !Number.isInteger(num)) return undefined;\n\t\t\treturn num;\n\t\t}\n\t\tcase \"boolean\": {\n\t\t\tconst lower = text.toLowerCase();\n\t\t\tif (lower === \"true\") return true;\n\t\t\tif (lower === \"false\") return false;\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"null\":\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn text;\n\t}\n}\n\n/**\n * Statically analyzes a template against a JSON Schema v7 describing the\n * available context.\n *\n * Backward-compatible version — parses the template internally.\n * Uses `dispatchAnalyze` for the recursive array/object/literal dispatching,\n * delegating only the string (template) case to `analyzeFromAst`.\n *\n * @param template - The template string (e.g. `\"Hello {{user.name}}\"`)\n * @param inputSchema - JSON Schema v7 describing the available variables\n * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n * @returns An `AnalysisResult` containing validity, diagnostics, and the\n * inferred output schema.\n */\nexport function analyze(\n\ttemplate: TemplateInput,\n\tinputSchema: JSONSchema7 = {},\n\toptions?: AnalyzeOptions,\n): AnalysisResult {\n\treturn dispatchAnalyze(\n\t\ttemplate,\n\t\toptions,\n\t\t// String handler — parse and analyze the AST\n\t\t(tpl, coerceSchema) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tcoerceSchema,\n\t\t\t});\n\t\t},\n\t\t// Recursive handler — re-enter analyze() for child elements\n\t\t(child, childOptions) => analyze(child, inputSchema, childOptions),\n\t);\n}\n\n/**\n * Statically analyzes a template from an already-parsed AST.\n *\n * This is the internal function used by `Typebars.compile()` and\n * `CompiledTemplate.analyze()` to avoid costly re-parsing.\n *\n * @param ast - The already-parsed Handlebars AST\n * @param template - The template source (for error snippets)\n * @param inputSchema - JSON Schema v7 describing the available variables\n * @param options - Additional options\n * @returns An `AnalysisResult`\n */\nexport function analyzeFromAst(\n\tast: hbs.AST.Program,\n\ttemplate: string,\n\tinputSchema: JSONSchema7 = {},\n\toptions?: {\n\t\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t\thelpers?: Map<string, HelperDefinition>;\n\t\t/**\n\t\t * Explicit coercion schema. When set, static literal values will\n\t\t * respect the types declared in this schema instead of auto-detecting.\n\t\t * Unlike `expectedOutputType`, this is NEVER derived from inputSchema.\n\t\t */\n\t\tcoerceSchema?: JSONSchema7;\n\t},\n): AnalysisResult {\n\t// ── Initialize the diagnostic context FIRST ────────────────────────\n\tconst ctx: AnalysisContext = {\n\t\troot: inputSchema,\n\t\tcurrent: inputSchema,\n\t\tdiagnostics: [],\n\t\ttemplate,\n\t\tidentifierSchemas: options?.identifierSchemas,\n\t\thelpers: options?.helpers,\n\t\tcoerceSchema: options?.coerceSchema,\n\t};\n\n\t// ── Detect unsupported schema features as diagnostics ──────────────\n\t// Conditional schemas (if/then/else) are non-resolvable without runtime\n\t// data. Instead of throwing, we collect structured diagnostics so the\n\t// caller receives a standard AnalysisResult.\n\tconst conditionalLocations = findConditionalSchemaLocations(inputSchema);\n\tfor (const loc of conditionalLocations) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNSUPPORTED_SCHEMA\",\n\t\t\t\"error\",\n\t\t\t`Unsupported JSON Schema feature: \"${loc.keyword}\" at \"${loc.schemaPath}\". ` +\n\t\t\t\t\"Conditional schemas (if/then/else) cannot be resolved during static analysis \" +\n\t\t\t\t\"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.\",\n\t\t\tundefined,\n\t\t\t{ path: loc.schemaPath },\n\t\t);\n\t}\n\n\tif (options?.identifierSchemas) {\n\t\tfor (const [id, idSchema] of Object.entries(options.identifierSchemas)) {\n\t\t\tconst idLocations = findConditionalSchemaLocations(\n\t\t\t\tidSchema,\n\t\t\t\t`/identifierSchemas/${id}`,\n\t\t\t);\n\t\t\tfor (const loc of idLocations) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"UNSUPPORTED_SCHEMA\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\t`Unsupported JSON Schema feature: \"${loc.keyword}\" at \"${loc.schemaPath}\". ` +\n\t\t\t\t\t\t\"Conditional schemas (if/then/else) cannot be resolved during static analysis \" +\n\t\t\t\t\t\t\"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.\",\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ path: loc.schemaPath },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// If unsupported schemas were found, return early with valid: false\n\tif (ctx.diagnostics.length > 0) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\tdiagnostics: ctx.diagnostics,\n\t\t\toutputSchema: {},\n\t\t};\n\t}\n\n\t// Single pass: type inference + validation in one traversal.\n\tconst outputSchema = inferProgramType(ast, ctx);\n\n\tconst hasErrors = ctx.diagnostics.some((d) => d.severity === \"error\");\n\n\treturn {\n\t\tvalid: !hasErrors,\n\t\tdiagnostics: ctx.diagnostics,\n\t\toutputSchema: simplifySchema(outputSchema),\n\t};\n}\n\n// ─── Unified AST Traversal ───────────────────────────────────────────────────\n// A single set of functions handles both validation (emitting diagnostics)\n// and type inference (returning a JSONSchema7).\n//\n// Main functions:\n// - `inferProgramType` — entry point for a Program (template body or block)\n// - `processStatement` — dispatches a statement (validation side-effects)\n// - `processMustache` — handles a MustacheStatement (expression or inline helper)\n// - `inferBlockType` — handles a BlockStatement (if, each, with, custom…)\n\n/**\n * Dispatches the processing of an individual statement.\n *\n * Called by `inferProgramType` in the \"mixed template\" case to validate\n * each statement while ignoring the returned type (the result is always\n * `string` for a mixed template).\n *\n * @returns The inferred schema for this statement, or `undefined` for\n * statements with no semantics (ContentStatement, CommentStatement).\n */\nfunction processStatement(\n\tstmt: hbs.AST.Statement,\n\tctx: AnalysisContext,\n): JSONSchema7 | undefined {\n\tswitch (stmt.type) {\n\t\tcase \"ContentStatement\":\n\t\tcase \"CommentStatement\":\n\t\t\t// Static text or comment — nothing to validate, no type to infer\n\t\t\treturn undefined;\n\n\t\tcase \"MustacheStatement\":\n\t\t\treturn processMustache(stmt as hbs.AST.MustacheStatement, ctx);\n\n\t\tcase \"BlockStatement\":\n\t\t\treturn inferBlockType(stmt as hbs.AST.BlockStatement, ctx);\n\n\t\tdefault:\n\t\t\t// Unrecognized AST node — emit a warning rather than an error\n\t\t\t// to avoid blocking on future Handlebars extensions.\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"UNANALYZABLE\",\n\t\t\t\t\"warning\",\n\t\t\t\t`Unsupported AST node type: \"${stmt.type}\"`,\n\t\t\t\tstmt,\n\t\t\t);\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Processes a MustacheStatement `{{expression}}` or `{{helper arg}}`.\n *\n * Distinguishes two cases:\n * 1. **Simple expression** (`{{name}}`, `{{user.age}}`) — resolution in the schema\n * 2. **Inline helper** (`{{uppercase name}}`) — params > 0 or hash present\n *\n * @returns The inferred schema for this expression\n */\nfunction processMustache(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\t// Sub-expressions (nested helpers) are not supported for static\n\t// analysis — emit a warning.\n\tif (stmt.path.type === \"SubExpression\") {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNANALYZABLE\",\n\t\t\t\"warning\",\n\t\t\t\"Sub-expressions are not statically analyzable\",\n\t\t\tstmt,\n\t\t);\n\t\treturn {};\n\t}\n\n\t// ── Inline helper detection ──────────────────────────────────────────────\n\t// If the MustacheStatement has parameters or a hash, it's a helper call\n\t// (e.g. `{{uppercase name}}`), not a simple expression.\n\tif (stmt.params.length > 0 || stmt.hash) {\n\t\tconst helperName = getExpressionName(stmt.path);\n\n\t\t// ── Special-case: map helper ─────────────────────────────────────\n\t\t// The `map` helper requires deep static analysis that the generic\n\t\t// helper path cannot perform: it must resolve the first argument as\n\t\t// an array-of-objects schema, then resolve the second argument (a\n\t\t// property name) within the item schema to infer the output type\n\t\t// `{ type: \"array\", items: <property schema> }`.\n\t\tif (helperName === MapHelpers.MAP_HELPER_NAME) {\n\t\t\treturn processMapHelper(stmt, ctx);\n\t\t}\n\n\t\t// ── Special-case: default helper ─────────────────────────────────\n\t\t// The `default` helper requires deep static analysis: the return\n\t\t// type is the union of all argument types, and the chain must\n\t\t// terminate with a guaranteed (non-optional) value.\n\t\tif (helperName === DefaultHelpers.DEFAULT_HELPER_NAME) {\n\t\t\treturn processDefaultHelper(stmt, ctx);\n\t\t}\n\n\t\t// Check if the helper is registered\n\t\tconst helper = ctx.helpers?.get(helperName);\n\t\tif (helper) {\n\t\t\tconst helperParams = helper.params;\n\n\t\t\t// ── Check the number of required parameters ──────────────\n\t\t\tif (helperParams) {\n\t\t\t\tconst requiredCount = helperParams.filter((p) => !p.optional).length;\n\t\t\t\tif (stmt.params.length < requiredCount) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t`Helper \"${helperName}\" expects at least ${requiredCount} argument(s), but got ${stmt.params.length}`,\n\t\t\t\t\t\tstmt,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\texpected: `${requiredCount} argument(s)`,\n\t\t\t\t\t\t\tactual: `${stmt.params.length} argument(s)`,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Validate each parameter (existence + type) ───────────────\n\t\t\tfor (let i = 0; i < stmt.params.length; i++) {\n\t\t\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(\n\t\t\t\t\tstmt.params[i] as hbs.AST.Expression,\n\t\t\t\t\tctx,\n\t\t\t\t\tstmt,\n\t\t\t\t);\n\n\t\t\t\t// Check type compatibility if the helper declares the\n\t\t\t\t// expected type for this parameter\n\t\t\t\tconst helperParam = helperParams?.[i];\n\t\t\t\tif (resolvedSchema && helperParam?.type) {\n\t\t\t\t\tconst expectedType = helperParam.type;\n\t\t\t\t\tif (!isParamTypeCompatible(resolvedSchema, expectedType)) {\n\t\t\t\t\t\tconst paramName = helperParam.name;\n\t\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\t`Helper \"${helperName}\" parameter \"${paramName}\" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,\n\t\t\t\t\t\t\tstmt,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\t\texpected: schemaTypeLabel(expectedType),\n\t\t\t\t\t\t\t\tactual: schemaTypeLabel(resolvedSchema),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn helper.returnType ?? { type: \"string\" };\n\t\t}\n\n\t\t// Unknown inline helper — warning\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\"warning\",\n\t\t\t`Unknown inline helper \"${helperName}\" — cannot analyze statically`,\n\t\t\tstmt,\n\t\t\t{ helperName },\n\t\t);\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Simple expression ────────────────────────────────────────────────────\n\tconst resolved = resolveExpressionWithDiagnostics(stmt.path, ctx, stmt) ?? {};\n\n\t// When the expression points to an optional property (not in `required`),\n\t// the output can be null at runtime. Wrap the resolved schema with null\n\t// so the output schema accurately reflects this.\n\t// $root returns the entire context — optionality does not apply.\n\tif (stmt.path.type === \"PathExpression\") {\n\t\tconst segments = extractPathSegments(stmt.path);\n\t\tif (segments.length > 0) {\n\t\t\tconst { cleanSegments, identifier } =\n\t\t\t\textractExpressionIdentifier(segments);\n\t\t\tif (!isRootSegments(cleanSegments)) {\n\t\t\t\tlet targetSchema =\n\t\t\t\t\tidentifier !== null\n\t\t\t\t\t\t? ctx.identifierSchemas?.[identifier]\n\t\t\t\t\t\t: ctx.current;\n\t\t\t\t// For aggregated identifiers (array schema), check optionality\n\t\t\t\t// within the items schema, not the array itself.\n\t\t\t\tif (targetSchema && identifier !== null) {\n\t\t\t\t\tconst itemSchema = resolveArrayItems(targetSchema, ctx.root);\n\t\t\t\t\tif (itemSchema !== undefined) {\n\t\t\t\t\t\ttargetSchema = itemSchema;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (targetSchema && !isPathFullyRequired(targetSchema, cleanSegments)) {\n\t\t\t\t\treturn withNullType(resolved);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resolved;\n}\n\n// ─── map helper — special-case analysis ──────────────────────────────────────\n// Validates the arguments and infers the precise return type:\n// {{ map <arrayPath> <propertyName> }}\n// → { type: \"array\", items: <schema of the property in the item> }\n//\n// Validation rules:\n// 1. Exactly 2 arguments are required\n// 2. The first argument must resolve to an array schema\n// 3. The array items must be an object schema\n// 4. The second argument must be a string literal (property name)\n// 5. The property must exist in the item schema\n\nfunction processMapHelper(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst helperName = MapHelpers.MAP_HELPER_NAME;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (stmt.params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${stmt.params.length}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${stmt.params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 2. Resolve the first argument (collection path) ──────────────────\n\tconst collectionExpr = stmt.params[0] as hbs.AST.Expression;\n\tconst collectionSchema = resolveExpressionWithDiagnostics(\n\t\tcollectionExpr,\n\t\tctx,\n\t\tstmt,\n\t);\n\n\tif (!collectionSchema) {\n\t\t// Path resolution failed — diagnostic already emitted\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 3. Validate that the collection is an array ──────────────────────\n\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\tif (!itemSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"collection\" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"array\",\n\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 4. Validate that the items are objects ───────────────────────────\n\t// If the items are arrays (e.g. from a nested map), flatten one level\n\t// to match the runtime `flat(1)` behavior and use the inner items instead.\n\tlet effectiveItemSchema = itemSchema;\n\tconst itemType = effectiveItemSchema.type;\n\tif (\n\t\titemType === \"array\" ||\n\t\t(Array.isArray(itemType) && itemType.includes(\"array\"))\n\t) {\n\t\tconst innerItems = resolveArrayItems(effectiveItemSchema, ctx.root);\n\t\tif (innerItems) {\n\t\t\teffectiveItemSchema = innerItems;\n\t\t\t// Emit an informational warning so consumers know the flatten happened\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"MAP_IMPLICIT_FLATTEN\",\n\t\t\t\t\"warning\",\n\t\t\t\t`The \"${helperName}\" helper will automatically flatten the input array one level before mapping. ` +\n\t\t\t\t\t`The item type \"${Array.isArray(itemType) ? itemType.join(\" | \") : itemType}\" was unwrapped to its inner items schema.`,\n\t\t\t\tstmt,\n\t\t\t\t{\n\t\t\t\t\thelperName,\n\t\t\t\t\texpected: \"object\",\n\t\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tconst effectiveItemType = effectiveItemSchema.type;\n\tconst isObject =\n\t\teffectiveItemType === \"object\" ||\n\t\t(Array.isArray(effectiveItemType) &&\n\t\t\teffectiveItemType.includes(\"object\")) ||\n\t\t// If no type but has properties, treat as object\n\t\t(!effectiveItemType && effectiveItemSchema.properties !== undefined);\n\n\tif (!isObject && effectiveItemType !== undefined) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects an array of objects, but the array items have type \"${schemaTypeLabel(effectiveItemSchema)}\"`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"object\",\n\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 5. Validate the second argument (property name) ──────────────────\n\tconst propertyExpr = stmt.params[1] as hbs.AST.Expression;\n\n\t// The property name MUST be a StringLiteral (quoted string like `\"name\"`).\n\t// A bare identifier like `name` is parsed by Handlebars as a PathExpression,\n\t// which would be resolved as a data path at runtime — yielding `undefined`\n\t// when the identifier doesn't exist in the top-level context. This is a\n\t// common mistake, so we provide a clear error message guiding the user.\n\tlet propertyName: string | undefined;\n\n\tif (propertyExpr.type === \"PathExpression\") {\n\t\tconst bare = (propertyExpr as hbs.AST.PathExpression).original;\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" must be a quoted string. ` +\n\t\t\t\t`Use {{ ${helperName} … \"${bare}\" }} instead of {{ ${helperName} … ${bare} }}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: `PathExpression (${bare})`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\tif (propertyExpr.type === \"StringLiteral\") {\n\t\tpropertyName = (propertyExpr as hbs.AST.StringLiteral).value;\n\t}\n\n\tif (!propertyName) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" expects a quoted string literal, but got ${propertyExpr.type}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: propertyExpr.type,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 6. Resolve the property within the item schema ───────────────────\n\tconst propertySchema = resolveSchemaPath(effectiveItemSchema, [propertyName]);\n\tif (!propertySchema) {\n\t\tconst availableProperties = getSchemaPropertyNames(effectiveItemSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(propertyName, availableProperties),\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\tpath: propertyName,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 7. Return the inferred output schema ─────────────────────────────\n\treturn { type: \"array\", items: propertySchema };\n}\n\n// ─── default helper — special-case analysis ──────────────────────────────────\n// Validates the arguments and infers the return type as the union of all\n// argument types. The chain must terminate with a guaranteed value.\n//\n// Validation rules:\n// 1. At least 2 arguments are required\n// 2. All arguments must be type-compatible\n// 3. The chain must end with a guaranteed value (literal, required property,\n// or sub-expression)\n\n/**\n * Analyzes a `default` helper MustacheStatement and returns the inferred\n * output schema. Shared logic with `processDefaultSubExpression`.\n */\nfunction processDefaultHelper(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\treturn analyzeDefaultArgs(stmt.params as hbs.AST.Expression[], ctx, stmt);\n}\n\n/**\n * Analyzes a `default` helper SubExpression and returns the inferred\n * output schema.\n */\nfunction processDefaultSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 {\n\treturn analyzeDefaultArgs(\n\t\texpr.params as hbs.AST.Expression[],\n\t\tctx,\n\t\tparentNode ?? expr,\n\t);\n}\n\n/**\n * Core analysis logic for the `default` helper (shared by Mustache and\n * SubExpression paths).\n *\n * 1. Validates argument count (≥ 2)\n * 2. Resolves the schema of each argument\n * 3. Checks type compatibility between all arguments\n * 4. Verifies that at least one argument is guaranteed (non-optional)\n * 5. Returns the simplified union of all argument types\n */\nfunction analyzeDefaultArgs(\n\tparams: hbs.AST.Expression[],\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 {\n\tconst helperName = DefaultHelpers.DEFAULT_HELPER_NAME;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${params.length}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn {};\n\t}\n\n\t// ── 2. Resolve the schema of each argument ───────────────────────────\n\tconst resolvedSchemas: JSONSchema7[] = [];\n\tlet hasGuaranteedValue = false;\n\n\tfor (let i = 0; i < params.length; i++) {\n\t\tconst param = params[i] as hbs.AST.Expression;\n\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(param, ctx, node);\n\n\t\tif (resolvedSchema) {\n\t\t\tresolvedSchemas.push(resolvedSchema);\n\t\t}\n\n\t\t// ── 3. Check if this argument is guaranteed ──────────────────────\n\t\tif (isGuaranteedExpression(param, ctx)) {\n\t\t\thasGuaranteedValue = true;\n\t\t}\n\t}\n\n\t// ── 4. Check type compatibility between all arguments ────────────────\n\t// All arguments must be compatible with each other. We compare each\n\t// pair of resolved schemas (only those with type info).\n\tif (resolvedSchemas.length >= 2) {\n\t\tconst firstWithType = resolvedSchemas.find((s) => s.type);\n\t\tif (firstWithType) {\n\t\t\tfor (let i = 0; i < resolvedSchemas.length; i++) {\n\t\t\t\tconst schema = resolvedSchemas[i] as JSONSchema7;\n\t\t\t\tif (schema.type && !isParamTypeCompatible(schema, firstWithType)) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t`Helper \"${helperName}\" argument ${i + 1} has type ${schemaTypeLabel(schema)}, incompatible with ${schemaTypeLabel(firstWithType)}`,\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\texpected: schemaTypeLabel(firstWithType),\n\t\t\t\t\t\t\tactual: schemaTypeLabel(schema),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── 5. Verify the chain terminates with a guaranteed value ───────────\n\tif (!hasGuaranteedValue) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"DEFAULT_NO_GUARANTEED_VALUE\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" argument chain has no guaranteed fallback — ` +\n\t\t\t\t\"the last argument must be a literal or a non-optional property\",\n\t\t\tnode,\n\t\t\t{ helperName },\n\t\t);\n\t}\n\n\t// ── 6. Return the union of all argument types ────────────────────────\n\tif (resolvedSchemas.length === 0) return {};\n\tif (resolvedSchemas.length === 1) return resolvedSchemas[0] as JSONSchema7;\n\n\treturn simplifySchema({ oneOf: resolvedSchemas });\n}\n\n/**\n * Determines whether a template expression is **guaranteed** to produce a\n * non-nullish value at runtime.\n *\n * An expression is guaranteed when:\n * - It is a literal (StringLiteral, NumberLiteral, BooleanLiteral)\n * - It is a SubExpression (helpers always return a value)\n * - It is a PathExpression pointing to a **required** property in the schema\n */\nfunction isGuaranteedExpression(\n\texpr: hbs.AST.Expression,\n\tctx: AnalysisContext,\n): boolean {\n\t// Literals are always guaranteed\n\tif (\n\t\texpr.type === \"StringLiteral\" ||\n\t\texpr.type === \"NumberLiteral\" ||\n\t\texpr.type === \"BooleanLiteral\"\n\t) {\n\t\treturn true;\n\t}\n\n\t// Sub-expressions (helper calls) are considered guaranteed\n\tif (expr.type === \"SubExpression\") {\n\t\treturn true;\n\t}\n\n\t// PathExpression: check if the property is required in the schema\n\tif (expr.type === \"PathExpression\") {\n\t\tconst segments = extractPathSegments(expr);\n\t\tif (segments.length === 0) return false;\n\n\t\tconst { cleanSegments } = extractExpressionIdentifier(segments);\n\t\treturn isPropertyRequired(ctx.current, cleanSegments);\n\t}\n\n\treturn false;\n}\n\n/**\n * Checks whether a resolved type is compatible with the type expected\n * by a helper parameter.\n *\n * Compatibility rules:\n * - If either schema has no `type`, validation is not possible → compatible\n * - `integer` is compatible with `number` (integer ⊂ number)\n * - For multiple types (e.g. `[\"string\", \"number\"]`), at least one resolved\n * type must match one expected type\n */\nfunction isParamTypeCompatible(\n\tresolved: JSONSchema7,\n\texpected: JSONSchema7,\n): boolean {\n\t// If either has no type info, we cannot validate\n\tif (!expected.type || !resolved.type) return true;\n\n\tconst expectedTypes = Array.isArray(expected.type)\n\t\t? expected.type\n\t\t: [expected.type];\n\tconst resolvedTypes = Array.isArray(resolved.type)\n\t\t? resolved.type\n\t\t: [resolved.type];\n\n\t// At least one resolved type must be compatible with one expected type\n\treturn resolvedTypes.some((rt) =>\n\t\texpectedTypes.some(\n\t\t\t(et) =>\n\t\t\t\trt === et ||\n\t\t\t\t// integer is a subtype of number\n\t\t\t\t(et === \"number\" && rt === \"integer\") ||\n\t\t\t\t(et === \"integer\" && rt === \"number\"),\n\t\t),\n\t);\n}\n\n/**\n * Infers the output type of a `Program` (template body or block body).\n *\n * Handles 4 cases, from most specific to most general:\n *\n * 1. **Single expression** `{{expr}}` → type of the expression\n * 2. **Single block** `{{#if}}…{{/if}}` → type of the block\n * 3. **Pure text content** → literal detection (number, boolean, null)\n * 4. **Mixed template** → always `string` (concatenation)\n *\n * Validation is performed alongside inference: each expression and block\n * is validated during processing.\n */\nfunction inferProgramType(\n\tprogram: hbs.AST.Program,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst effective = getEffectiveBody(program);\n\n\t// No significant statements → empty string\n\tif (effective.length === 0) {\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Case 1: single expression {{expr}} ─────────────────────────────────\n\tconst singleExpr = getEffectivelySingleExpression(program);\n\tif (singleExpr) {\n\t\treturn processMustache(singleExpr, ctx);\n\t}\n\n\t// ── Case 2: single block {{#if}}, {{#each}}, {{#with}}, … ──────────────\n\tconst singleBlock = getEffectivelySingleBlock(program);\n\tif (singleBlock) {\n\t\treturn inferBlockType(singleBlock, ctx);\n\t}\n\n\t// ── Case 3: only ContentStatements (no expressions) ────────────────────\n\t// If the concatenated (trimmed) text is a typed literal (number, boolean,\n\t// null), we infer the corresponding type.\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\tconst text = effective\n\t\t\t.map((s) => (s as hbs.AST.ContentStatement).value)\n\t\t\t.join(\"\")\n\t\t\t.trim();\n\n\t\tif (text === \"\") return { type: \"string\" };\n\n\t\t// If an explicit coerceSchema was provided and declares a specific\n\t\t// primitive type, respect it instead of auto-detecting. For example,\n\t\t// \"123\" with coerceSchema `{ type: \"string\" }` should stay \"string\".\n\t\t// This only applies when coerceSchema is explicitly set — the\n\t\t// inputSchema is NEVER used for coercion.\n\t\t//\n\t\t// Only the **type** is extracted from coerceSchema. Value-level\n\t\t// constraints (enum, const, format, pattern, minLength, …) are NOT\n\t\t// propagated because they describe what the *consumer* accepts, not\n\t\t// what the literal *produces*. The actual literal value is set as\n\t\t// `const` so downstream compatibility checkers can detect mismatches.\n\t\tconst coercedType = ctx.coerceSchema?.type;\n\t\tif (\n\t\t\ttypeof coercedType === \"string\" &&\n\t\t\t(coercedType === \"string\" ||\n\t\t\t\tcoercedType === \"number\" ||\n\t\t\t\tcoercedType === \"integer\" ||\n\t\t\t\tcoercedType === \"boolean\" ||\n\t\t\t\tcoercedType === \"null\")\n\t\t) {\n\t\t\tconst coercedValue = coerceTextValue(text, coercedType);\n\t\t\treturn { type: coercedType, const: coercedValue } as JSONSchema7;\n\t\t}\n\n\t\tconst literalType = detectLiteralType(text);\n\t\tif (literalType) return { type: literalType };\n\t}\n\n\t// ── Case 4: multiple blocks only (no significant text between them) ────\n\t// When the effective body consists entirely of BlockStatements, gather\n\t// each block's inferred type and combine them via oneOf. This handles\n\t// templates like:\n\t// {{#if showName}}{{name}}{{/if}}\n\t// {{#if showAge}}{{age}}{{/if}}\n\t// where the output could be string OR number depending on which branch\n\t// is active.\n\tconst allBlocks = effective.every((s) => s.type === \"BlockStatement\");\n\tif (allBlocks) {\n\t\tconst types: JSONSchema7[] = [];\n\t\tfor (const stmt of effective) {\n\t\t\tconst t = inferBlockType(stmt as hbs.AST.BlockStatement, ctx);\n\t\t\tif (t) types.push(t);\n\t\t}\n\t\tif (types.length === 1) return types[0] as JSONSchema7;\n\t\tif (types.length > 1) return simplifySchema({ oneOf: types });\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Case 5: mixed template (text + expressions, blocks…) ───────────────\n\t// Traverse all statements for validation (side-effects: diagnostics).\n\t// The result is always string (concatenation).\n\tfor (const stmt of program.body) {\n\t\tprocessStatement(stmt, ctx);\n\t}\n\treturn { type: \"string\" };\n}\n\n/**\n * Infers the output type of a BlockStatement and validates its content.\n *\n * Supports built-in helpers (`if`, `unless`, `each`, `with`) and custom\n * helpers registered via `Typebars.registerHelper()`.\n *\n * Uses the **save/restore** pattern for context: instead of creating a new\n * object `{ ...ctx, current: X }` on each recursion, we save `ctx.current`,\n * mutate it, process the body, then restore. This reduces GC pressure for\n * deeply nested templates.\n */\nfunction inferBlockType(\n\tstmt: hbs.AST.BlockStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst helperName = getBlockHelperName(stmt);\n\n\tswitch (helperName) {\n\t\t// ── if / unless ──────────────────────────────────────────────────────\n\t\t// Validate the condition argument, then infer types from both branches.\n\t\tcase \"if\":\n\t\tcase \"unless\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (arg) {\n\t\t\t\tresolveExpressionWithDiagnostics(arg, ctx, stmt);\n\t\t\t} else {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(helperName),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Infer the type of the \"then\" branch\n\t\t\tconst thenType = inferProgramType(stmt.program, ctx);\n\n\t\t\tif (stmt.inverse) {\n\t\t\t\tconst elseType = inferProgramType(stmt.inverse, ctx);\n\t\t\t\t// If both branches have the same type → single type\n\t\t\t\tif (deepEqual(thenType, elseType)) return thenType;\n\t\t\t\t// Otherwise → union of both types\n\t\t\t\treturn simplifySchema({ oneOf: [thenType, elseType] });\n\t\t\t}\n\n\t\t\t// No else branch → the result is the type of the then branch\n\t\t\t// (conceptually optional, but Handlebars returns \"\" for falsy)\n\t\t\treturn thenType;\n\t\t}\n\n\t\t// ── each ─────────────────────────────────────────────────────────────\n\t\t// Resolve the collection schema, then validate the body with the item\n\t\t// schema as the new context.\n\t\tcase \"each\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (!arg) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(\"each\"),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName: \"each\" },\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context (best-effort)\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\tconst collectionSchema = resolveExpressionWithDiagnostics(arg, ctx, stmt);\n\t\t\tif (!collectionSchema) {\n\t\t\t\t// The path could not be resolved — diagnostic already emitted.\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Resolve the schema of the array elements\n\t\t\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\t\t\tif (!itemSchema) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateTypeMismatchMessage(\n\t\t\t\t\t\t\"each\",\n\t\t\t\t\t\t\"an array\",\n\t\t\t\t\t\tschemaTypeLabel(collectionSchema),\n\t\t\t\t\t),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{\n\t\t\t\t\t\thelperName: \"each\",\n\t\t\t\t\t\texpected: \"array\",\n\t\t\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context (best-effort)\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Validate the body with the item schema as the new context\n\t\t\tconst saved = ctx.current;\n\t\t\tctx.current = itemSchema;\n\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\tctx.current = saved;\n\n\t\t\t// The inverse branch ({{else}}) keeps the parent context\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\n\t\t\t// An each concatenates renders → always string\n\t\t\treturn { type: \"string\" };\n\t\t}\n\n\t\t// ── with ─────────────────────────────────────────────────────────────\n\t\t// Resolve the inner schema, then validate the body with it as the\n\t\t// new context.\n\t\tcase \"with\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (!arg) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(\"with\"),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName: \"with\" },\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tconst result = inferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tconst innerSchema = resolveExpressionWithDiagnostics(arg, ctx, stmt);\n\n\t\t\tconst saved = ctx.current;\n\t\t\tctx.current = innerSchema ?? {};\n\t\t\tconst result = inferProgramType(stmt.program, ctx);\n\t\t\tctx.current = saved;\n\n\t\t\t// The inverse branch keeps the parent context\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\n\t\t\treturn result;\n\t\t}\n\n\t\t// ── Custom or unknown helper ─────────────────────────────────────────\n\t\tdefault: {\n\t\t\tconst helper = ctx.helpers?.get(helperName);\n\t\t\tif (helper) {\n\t\t\t\t// Registered custom helper — validate parameters\n\t\t\t\tfor (const param of stmt.params) {\n\t\t\t\t\tresolveExpressionWithDiagnostics(\n\t\t\t\t\t\tparam as hbs.AST.Expression,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstmt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Validate the body with the current context\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn helper.returnType ?? { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Unknown helper — warning\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\t\"warning\",\n\t\t\t\tcreateUnknownHelperMessage(helperName),\n\t\t\t\tstmt,\n\t\t\t\t{ helperName },\n\t\t\t);\n\t\t\t// Still validate the body with the current context (best-effort)\n\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\treturn { type: \"string\" };\n\t\t}\n\t}\n}\n\n// ─── Expression Resolution ───────────────────────────────────────────────────\n\n/**\n * Resolves an AST expression to a sub-schema, emitting a diagnostic\n * if the path cannot be resolved.\n *\n * Handles the `{{key:N}}` syntax:\n * - If the expression has an identifier N → resolution in `identifierSchemas[N]`\n * - If identifier N has no associated schema → error\n * - If no identifier → resolution in `ctx.current` (standard behavior)\n *\n * @returns The resolved sub-schema, or `undefined` if the path is invalid.\n */\nfunction resolveExpressionWithDiagnostics(\n\texpr: hbs.AST.Expression,\n\tctx: AnalysisContext,\n\t/** Parent AST node (for diagnostic location) */\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\t// Handle `this` / `.` → return the current context\n\tif (isThisExpression(expr)) {\n\t\treturn ctx.current;\n\t}\n\n\t// ── SubExpression (nested helper call, e.g. `(lt account.balance 500)`) ──\n\tif (expr.type === \"SubExpression\") {\n\t\treturn resolveSubExpression(expr as hbs.AST.SubExpression, ctx, parentNode);\n\t}\n\n\tconst segments = extractPathSegments(expr);\n\tif (segments.length === 0) {\n\t\t// Expression that is not a PathExpression (e.g. literal)\n\t\tif (expr.type === \"StringLiteral\") return { type: \"string\" };\n\t\tif (expr.type === \"NumberLiteral\") return { type: \"number\" };\n\t\tif (expr.type === \"BooleanLiteral\") return { type: \"boolean\" };\n\t\tif (expr.type === \"NullLiteral\") return { type: \"null\" };\n\t\tif (expr.type === \"UndefinedLiteral\") return {};\n\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNANALYZABLE\",\n\t\t\t\"warning\",\n\t\t\tcreateUnanalyzableMessage(expr.type),\n\t\t\tparentNode ?? expr,\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// ── Identifier extraction ──────────────────────────────────────────────\n\t// Extract the `:N` suffix BEFORE checking for `$root` so that both\n\t// `{{$root}}` and `{{$root:2}}` are handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// ── $root token ──────────────────────────────────────────────────────\n\t// Path traversal ($root.name, $root.address.city) is always forbidden,\n\t// regardless of whether an identifier is present.\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\tconst fullPath = cleanSegments.join(\".\");\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"ROOT_PATH_TRAVERSAL\",\n\t\t\t\"error\",\n\t\t\tcreateRootPathTraversalMessage(fullPath),\n\t\t\tparentNode ?? expr,\n\t\t\t{ path: fullPath },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// `{{$root}}` → return the entire current context schema\n\t// `{{$root:N}}` → return the entire schema for identifier N\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null) {\n\t\t\treturn resolveRootWithIdentifier(identifier, ctx, parentNode ?? expr);\n\t\t}\n\t\treturn ctx.current;\n\t}\n\n\tif (identifier !== null) {\n\t\t// The expression uses the {{key:N}} syntax — resolve from\n\t\t// the schema of identifier N.\n\t\treturn resolveWithIdentifier(\n\t\t\tcleanSegments,\n\t\t\tidentifier,\n\t\t\tctx,\n\t\t\tparentNode ?? expr,\n\t\t);\n\t}\n\n\t// ── Standard resolution (no identifier) ────────────────────────────────\n\tconst resolved = resolveSchemaPath(ctx.current, cleanSegments);\n\tif (resolved === undefined) {\n\t\tconst fullPath = cleanSegments.join(\".\");\n\t\tconst availableProperties = getSchemaPropertyNames(ctx.current);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(fullPath, availableProperties),\n\t\t\tparentNode ?? expr,\n\t\t\t{ path: fullPath, availableProperties },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn resolved;\n}\n\n/**\n * Resolves `{{$root:N}}` — returns the **entire** schema for identifier N.\n *\n * This is the identifier-aware counterpart of returning `ctx.current` for\n * a plain `{{$root}}`. Instead of navigating into properties, it returns\n * the identifier's root schema directly.\n *\n * When the identifier schema is an array (aggregated multi-version data),\n * the full array schema is returned as-is — the caller receives the\n * complete `{ type: \"array\", items: ... }` schema.\n *\n * Emits an error diagnostic if:\n * - No `identifierSchemas` were provided\n * - Identifier N has no associated schema\n */\nfunction resolveRootWithIdentifier(\n\tidentifier: number,\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\t// No identifierSchemas provided at all\n\tif (!ctx.identifierSchemas) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_IDENTIFIER_SCHEMAS\",\n\t\t\t\"error\",\n\t\t\t`Property \"$root:${identifier}\" uses an identifier but no identifier schemas were provided`,\n\t\t\tnode,\n\t\t\t{ path: `$root:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// The identifier does not exist in the provided schemas\n\tconst idSchema = ctx.identifierSchemas[identifier];\n\tif (!idSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_IDENTIFIER\",\n\t\t\t\"error\",\n\t\t\t`Property \"$root:${identifier}\" references identifier ${identifier} but no schema exists for this identifier`,\n\t\t\tnode,\n\t\t\t{ path: `$root:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// Return the entire schema for identifier N.\n\t// For aggregated identifiers (array schemas), this returns the full\n\t// array schema — e.g. { type: \"array\", items: { type: \"object\", ... } }\n\treturn idSchema;\n}\n\n/**\n * Resolves an expression with identifier `{{key:N}}` by looking up the\n * schema associated with identifier N.\n *\n * When the identifier schema is an array (aggregated multi-version data),\n * the property is resolved within the array's `items` schema, and the\n * result is wrapped in `{ type: \"array\", items: <resolved> }`. This\n * models the runtime behavior where `{{accountId:4}}` on an array of\n * objects extracts the property from each element, producing an array.\n *\n * Emits an error diagnostic if:\n * - No `identifierSchemas` were provided\n * - Identifier N has no associated schema\n * - The property does not exist in the identifier's schema\n */\nfunction resolveWithIdentifier(\n\tcleanSegments: string[],\n\tidentifier: number,\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\tconst fullPath = cleanSegments.join(\".\");\n\n\t// No identifierSchemas provided at all\n\tif (!ctx.identifierSchemas) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_IDENTIFIER_SCHEMAS\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}:${identifier}\" uses an identifier but no identifier schemas were provided`,\n\t\t\tnode,\n\t\t\t{ path: `${fullPath}:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// The identifier does not exist in the provided schemas\n\tconst idSchema = ctx.identifierSchemas[identifier];\n\tif (!idSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_IDENTIFIER\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}:${identifier}\" references identifier ${identifier} but no schema exists for this identifier`,\n\t\t\tnode,\n\t\t\t{ path: `${fullPath}:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// ── Aggregated identifier (array schema) ─────────────────────────────\n\t// When the identifier schema is an array of objects (e.g. from a\n\t// multi-versioned workflow node), resolve the property within the\n\t// items schema and wrap the result in an array type.\n\t//\n\t// Example: identifierSchemas[4] = { type: \"array\", items: { type: \"object\",\n\t// properties: { accountId: { type: \"string\" } } } }\n\t// Expression: {{accountId:4}}\n\t// Result: { type: \"array\", items: { type: \"string\" } }\n\tconst itemSchema = resolveArrayItems(idSchema, ctx.root);\n\tif (itemSchema !== undefined) {\n\t\t// The identifier schema is an array — resolve within items\n\t\tconst resolved = resolveSchemaPath(itemSchema, cleanSegments);\n\t\tif (resolved === undefined) {\n\t\t\tconst availableProperties = getSchemaPropertyNames(itemSchema);\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"IDENTIFIER_PROPERTY_NOT_FOUND\",\n\t\t\t\t\"error\",\n\t\t\t\t`Property \"${fullPath}\" does not exist in the items schema for identifier ${identifier}`,\n\t\t\t\tnode,\n\t\t\t\t{\n\t\t\t\t\tpath: fullPath,\n\t\t\t\t\tidentifier,\n\t\t\t\t\tavailableProperties,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\t// Wrap the resolved property schema in an array\n\t\treturn { type: \"array\", items: resolved };\n\t}\n\n\t// ── Standard identifier (single object schema) ───────────────────────\n\t// Resolve the path within the identifier's schema directly.\n\tconst resolved = resolveSchemaPath(idSchema, cleanSegments);\n\tif (resolved === undefined) {\n\t\tconst availableProperties = getSchemaPropertyNames(idSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"IDENTIFIER_PROPERTY_NOT_FOUND\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}\" does not exist in the schema for identifier ${identifier}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\tpath: fullPath,\n\t\t\t\tidentifier,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn resolved;\n}\n\n// ─── Nullable Schema Wrapping ────────────────────────────────────────────────\n\n/**\n * Wraps a JSON Schema with `null` to indicate the value can be nullish.\n *\n * - If the schema already includes `null`, it is returned as-is.\n * - For schemas with a simple `type` string, the type becomes an array\n * (e.g. `{ type: \"string\" }` → `{ type: [\"string\", \"null\"] }`).\n * - For schemas with a type array, `\"null\"` is appended.\n * - For complex schemas (oneOf, anyOf, etc.), a `oneOf` wrapper is used.\n */\nfunction withNullType(schema: JSONSchema7): JSONSchema7 {\n\tif (schema.type === \"null\") return schema;\n\n\tif (typeof schema.type === \"string\") {\n\t\treturn { ...schema, type: [schema.type, \"null\"] };\n\t}\n\n\tif (Array.isArray(schema.type)) {\n\t\tif (schema.type.includes(\"null\")) return schema;\n\t\treturn { ...schema, type: [...schema.type, \"null\"] };\n\t}\n\n\t// Complex schema (oneOf, anyOf, allOf, etc.) — wrap with oneOf\n\treturn simplifySchema({ oneOf: [schema, { type: \"null\" }] });\n}\n\n/**\n * Checks whether EVERY segment along a property path is required.\n *\n * Unlike `isPropertyRequired` (which only checks the last segment),\n * this function verifies that no intermediate segment is optional.\n * If any segment along the path is optional, the entire expression\n * can produce `null`/`undefined` at runtime.\n *\n * Example: for path `[\"user\", \"name\"]`, checks both that `user` is\n * required in the root schema AND that `name` is required in `user`.\n */\nfunction isPathFullyRequired(schema: JSONSchema7, segments: string[]): boolean {\n\tfor (let i = 1; i <= segments.length; i++) {\n\t\tif (!isPropertyRequired(schema, segments.slice(0, i))) return false;\n\t}\n\treturn true;\n}\n\n// ─── Utilities ───────────────────────────────────────────────────────────────\n\n/**\n * Extracts the first argument of a BlockStatement.\n *\n * In the Handlebars AST, for `{{#if active}}`:\n * - `stmt.path` → PathExpression(\"if\") ← the helper name\n * - `stmt.params[0]` → PathExpression(\"active\") ← the actual argument\n *\n * @returns The argument expression, or `undefined` if the block has no argument.\n */\n// ─── SubExpression Resolution ────────────────────────────────────────────────\n\n/**\n * Resolves a SubExpression (nested helper call) such as `(lt account.balance 500)`.\n *\n * This mirrors the helper-call logic in `processMustache` but applies to\n * expressions used as arguments (e.g. inside `{{#if (lt a b)}}`).\n *\n * Steps:\n * 1. Extract the helper name from the SubExpression's path.\n * 2. Look up the helper in `ctx.helpers`.\n * 3. Validate argument count and types.\n * 4. Return the helper's declared `returnType` (defaults to `{ type: \"string\" }`).\n */\nfunction resolveSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\tconst helperName = getExpressionName(expr.path);\n\n\t// ── Special-case: map helper ─────────────────────────────────────\n\t// The `map` helper requires deep static analysis to infer the\n\t// precise return type `{ type: \"array\", items: <property schema> }`.\n\t// The generic path would only return `{ type: \"array\" }` (the static\n\t// returnType), losing the item schema needed by nested map calls.\n\tif (helperName === MapHelpers.MAP_HELPER_NAME) {\n\t\treturn processMapSubExpression(expr, ctx, parentNode);\n\t}\n\n\t// ── Special-case: default helper ─────────────────────────────────\n\tif (helperName === DefaultHelpers.DEFAULT_HELPER_NAME) {\n\t\treturn processDefaultSubExpression(expr, ctx, parentNode);\n\t}\n\n\tconst helper = ctx.helpers?.get(helperName);\n\tif (!helper) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\"warning\",\n\t\t\t`Unknown sub-expression helper \"${helperName}\" — cannot analyze statically`,\n\t\t\tparentNode ?? expr,\n\t\t\t{ helperName },\n\t\t);\n\t\treturn { type: \"string\" };\n\t}\n\n\tconst helperParams = helper.params;\n\n\t// ── Check the number of required parameters ──────────────────────\n\tif (helperParams) {\n\t\tconst requiredCount = helperParams.filter((p) => !p.optional).length;\n\t\tif (expr.params.length < requiredCount) {\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\"error\",\n\t\t\t\t`Helper \"${helperName}\" expects at least ${requiredCount} argument(s), but got ${expr.params.length}`,\n\t\t\t\tparentNode ?? expr,\n\t\t\t\t{\n\t\t\t\t\thelperName,\n\t\t\t\t\texpected: `${requiredCount} argument(s)`,\n\t\t\t\t\tactual: `${expr.params.length} argument(s)`,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Validate each parameter (existence + type) ───────────────────\n\tfor (let i = 0; i < expr.params.length; i++) {\n\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(\n\t\t\texpr.params[i] as hbs.AST.Expression,\n\t\t\tctx,\n\t\t\tparentNode ?? expr,\n\t\t);\n\n\t\tconst helperParam = helperParams?.[i];\n\t\tif (resolvedSchema && helperParam?.type) {\n\t\t\tconst expectedType = helperParam.type;\n\t\t\tif (!isParamTypeCompatible(resolvedSchema, expectedType)) {\n\t\t\t\tconst paramName = helperParam.name;\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\t`Helper \"${helperName}\" parameter \"${paramName}\" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,\n\t\t\t\t\tparentNode ?? expr,\n\t\t\t\t\t{\n\t\t\t\t\t\thelperName,\n\t\t\t\t\t\texpected: schemaTypeLabel(expectedType),\n\t\t\t\t\t\tactual: schemaTypeLabel(resolvedSchema),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn helper.returnType ?? { type: \"string\" };\n}\n\n// ─── map helper — sub-expression analysis ────────────────────────────────────\n// Mirrors processMapHelper but for SubExpression nodes (e.g.\n// `(map users 'cartItems')` used as an argument to another helper).\n// This enables nested map: `{{ map (map users 'cartItems') 'productId' }}`\n\nfunction processMapSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 {\n\tconst helperName = MapHelpers.MAP_HELPER_NAME;\n\tconst node = parentNode ?? expr;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (expr.params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${expr.params.length}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${expr.params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 2. Resolve the first argument (collection path) ──────────────────\n\tconst collectionExpr = expr.params[0] as hbs.AST.Expression;\n\tconst collectionSchema = resolveExpressionWithDiagnostics(\n\t\tcollectionExpr,\n\t\tctx,\n\t\tnode,\n\t);\n\n\tif (!collectionSchema) {\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 3. Validate that the collection is an array ──────────────────────\n\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\tif (!itemSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"collection\" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"array\",\n\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 4. Validate that the items are objects ───────────────────────────\n\t// If the items are arrays (e.g. from a nested map), flatten one level\n\t// to match the runtime `flat(1)` behavior and use the inner items instead.\n\tlet effectiveItemSchema = itemSchema;\n\tconst itemType = effectiveItemSchema.type;\n\tif (\n\t\titemType === \"array\" ||\n\t\t(Array.isArray(itemType) && itemType.includes(\"array\"))\n\t) {\n\t\tconst innerItems = resolveArrayItems(effectiveItemSchema, ctx.root);\n\t\tif (innerItems) {\n\t\t\teffectiveItemSchema = innerItems;\n\t\t}\n\t}\n\n\tconst effectiveItemType = effectiveItemSchema.type;\n\tconst isObject =\n\t\teffectiveItemType === \"object\" ||\n\t\t(Array.isArray(effectiveItemType) &&\n\t\t\teffectiveItemType.includes(\"object\")) ||\n\t\t(!effectiveItemType && effectiveItemSchema.properties !== undefined);\n\n\tif (!isObject && effectiveItemType !== undefined) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects an array of objects, but the array items have type \"${schemaTypeLabel(effectiveItemSchema)}\"`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"object\",\n\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 5. Validate the second argument (property name) ──────────────────\n\tconst propertyExpr = expr.params[1] as hbs.AST.Expression;\n\tlet propertyName: string | undefined;\n\n\tif (propertyExpr.type === \"PathExpression\") {\n\t\tconst bare = (propertyExpr as hbs.AST.PathExpression).original;\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" must be a quoted string. ` +\n\t\t\t\t`Use (${helperName} … \"${bare}\") instead of (${helperName} … ${bare})`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: `PathExpression (${bare})`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\tif (propertyExpr.type === \"StringLiteral\") {\n\t\tpropertyName = (propertyExpr as hbs.AST.StringLiteral).value;\n\t}\n\n\tif (!propertyName) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" expects a quoted string literal, but got ${propertyExpr.type}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: propertyExpr.type,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 6. Resolve the property within the item schema ───────────────────\n\tconst propertySchema = resolveSchemaPath(effectiveItemSchema, [propertyName]);\n\tif (!propertySchema) {\n\t\tconst availableProperties = getSchemaPropertyNames(effectiveItemSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(propertyName, availableProperties),\n\t\t\tnode,\n\t\t\t{\n\t\t\t\tpath: propertyName,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 7. Return the inferred output schema ─────────────────────────────\n\treturn { type: \"array\", items: propertySchema };\n}\n\nfunction getBlockArgument(\n\tstmt: hbs.AST.BlockStatement,\n): hbs.AST.Expression | undefined {\n\treturn stmt.params[0] as hbs.AST.Expression | undefined;\n}\n\n/**\n * Retrieves the helper name from a BlockStatement (e.g. \"if\", \"each\", \"with\").\n */\nfunction getBlockHelperName(stmt: hbs.AST.BlockStatement): string {\n\tif (stmt.path.type === \"PathExpression\") {\n\t\treturn (stmt.path as hbs.AST.PathExpression).original;\n\t}\n\treturn \"\";\n}\n\n/**\n * Retrieves the name of an expression (first segment of the PathExpression).\n * Used to identify inline helpers.\n */\nfunction getExpressionName(expr: hbs.AST.Expression): string {\n\tif (expr.type === \"PathExpression\") {\n\t\treturn (expr as hbs.AST.PathExpression).original;\n\t}\n\treturn \"\";\n}\n\n/**\n * Adds an enriched diagnostic to the analysis context.\n *\n * Each diagnostic includes:\n * - A machine-readable `code` for the frontend\n * - A human-readable `message` describing the problem\n * - A `source` snippet from the template (if the position is available)\n * - Structured `details` for debugging\n */\nfunction addDiagnostic(\n\tctx: AnalysisContext,\n\tcode: DiagnosticCode,\n\tseverity: \"error\" | \"warning\",\n\tmessage: string,\n\tnode?: hbs.AST.Node,\n\tdetails?: DiagnosticDetails,\n): void {\n\tconst diagnostic: TemplateDiagnostic = { severity, code, message };\n\n\t// Extract the position and source snippet if available\n\tif (node && \"loc\" in node && node.loc) {\n\t\tdiagnostic.loc = {\n\t\t\tstart: { line: node.loc.start.line, column: node.loc.start.column },\n\t\t\tend: { line: node.loc.end.line, column: node.loc.end.column },\n\t\t};\n\t\t// Extract the template fragment around the error\n\t\tdiagnostic.source = extractSourceSnippet(ctx.template, diagnostic.loc);\n\t}\n\n\tif (details) {\n\t\tdiagnostic.details = details;\n\t}\n\n\tctx.diagnostics.push(diagnostic);\n}\n\n/**\n * Returns a human-readable label for a schema's type (for error messages).\n */\nfunction schemaTypeLabel(schema: JSONSchema7): string {\n\tif (schema.type) {\n\t\treturn Array.isArray(schema.type) ? schema.type.join(\" | \") : schema.type;\n\t}\n\tif (schema.oneOf) return \"oneOf(...)\";\n\tif (schema.anyOf) return \"anyOf(...)\";\n\tif (schema.allOf) return \"allOf(...)\";\n\tif (schema.enum) return \"enum\";\n\treturn \"unknown\";\n}\n\n// ─── Export for Internal Use ─────────────────────────────────────────────────\n// `inferBlockType` is exported to allow targeted unit tests\n// on block type inference.\nexport { inferBlockType };\n"],"names":["dispatchAnalyze","createMissingArgumentMessage","createPropertyNotFoundMessage","createRootPathTraversalMessage","createTypeMismatchMessage","createUnanalyzableMessage","createUnknownHelperMessage","DefaultHelpers","MapHelpers","detectLiteralType","extractExpressionIdentifier","extractPathSegments","getEffectiveBody","getEffectivelySingleBlock","getEffectivelySingleExpression","isRootPathTraversal","isRootSegments","isThisExpression","parse","findConditionalSchemaLocations","isPropertyRequired","resolveArrayItems","resolveSchemaPath","simplifySchema","deepEqual","extractSourceSnippet","getSchemaPropertyNames","coerceTextValue","text","targetType","undefined","num","Number","isNaN","isInteger","lower","toLowerCase","analyze","template","inputSchema","options","tpl","coerceSchema","ast","analyzeFromAst","identifierSchemas","child","childOptions","ctx","root","current","diagnostics","helpers","conditionalLocations","loc","addDiagnostic","keyword","schemaPath","path","id","idSchema","Object","entries","idLocations","length","valid","outputSchema","inferProgramType","hasErrors","some","d","severity","processStatement","stmt","type","processMustache","inferBlockType","params","hash","helperName","getExpressionName","MAP_HELPER_NAME","processMapHelper","DEFAULT_HELPER_NAME","processDefaultHelper","helper","get","helperParams","requiredCount","filter","p","optional","expected","actual","i","resolvedSchema","resolveExpressionWithDiagnostics","helperParam","expectedType","isParamTypeCompatible","paramName","name","schemaTypeLabel","returnType","resolved","segments","cleanSegments","identifier","targetSchema","itemSchema","isPathFullyRequired","withNullType","collectionExpr","collectionSchema","effectiveItemSchema","itemType","Array","isArray","includes","innerItems","join","effectiveItemType","isObject","properties","propertyExpr","propertyName","bare","original","value","propertySchema","availableProperties","items","analyzeDefaultArgs","processDefaultSubExpression","expr","parentNode","node","resolvedSchemas","hasGuaranteedValue","param","push","isGuaranteedExpression","firstWithType","find","s","schema","oneOf","expectedTypes","resolvedTypes","rt","et","program","effective","singleExpr","singleBlock","allContent","every","map","trim","coercedType","coercedValue","const","literalType","allBlocks","types","t","body","getBlockHelperName","arg","getBlockArgument","thenType","inverse","elseType","saved","result","innerSchema","resolveSubExpression","fullPath","resolveRootWithIdentifier","resolveWithIdentifier","slice","processMapSubExpression","code","message","details","diagnostic","start","line","column","end","source","anyOf","allOf","enum"],"mappings":"AACA,OAASA,eAAe,KAAQ,eAAgB,AAChD,QACCC,4BAA4B,CAC5BC,6BAA6B,CAC7BC,8BAA8B,CAC9BC,yBAAyB,CACzBC,yBAAyB,CACzBC,0BAA0B,KACpB,UAAW,AAClB,QAASC,cAAc,KAAQ,8BAA+B,AAC9D,QAASC,UAAU,KAAQ,0BAA2B,AACtD,QACCC,iBAAiB,CACjBC,2BAA2B,CAC3BC,mBAAmB,CACnBC,gBAAgB,CAChBC,yBAAyB,CACzBC,8BAA8B,CAC9BC,mBAAmB,CACnBC,cAAc,CACdC,gBAAgB,CAChBC,KAAK,KACC,UAAW,AAClB,QACCC,8BAA8B,CAC9BC,kBAAkB,CAClBC,iBAAiB,CACjBC,iBAAiB,CACjBC,cAAc,KACR,mBAAoB,AAS3B,QACCC,SAAS,CACTC,oBAAoB,CACpBC,sBAAsB,KAChB,SAAU,CA+FjB,SAASC,gBACRC,IAAY,CACZC,UAAgE,EAEhE,OAAQA,YACP,IAAK,SACL,IAAK,UAAW,CACf,GAAID,OAAS,GAAI,OAAOE,UACxB,MAAMC,IAAMC,OAAOJ,MACnB,GAAII,OAAOC,KAAK,CAACF,KAAM,OAAOD,UAC9B,GAAID,aAAe,WAAa,CAACG,OAAOE,SAAS,CAACH,KAAM,OAAOD,UAC/D,OAAOC,GACR,CACA,IAAK,UAAW,CACf,MAAMI,MAAQP,KAAKQ,WAAW,GAC9B,GAAID,QAAU,OAAQ,OAAO,KAC7B,GAAIA,QAAU,QAAS,OAAO,MAC9B,OAAOL,SACR,CACA,IAAK,OACJ,OAAO,IACR,SACC,OAAO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rH,cAAc,CAAG"}
1
+ {"version":3,"sources":["../../src/analyzer.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { dispatchAnalyze } from \"./dispatch.ts\";\nimport {\n\tcreateMissingArgumentMessage,\n\tcreatePropertyNotFoundMessage,\n\tcreateRootPathTraversalMessage,\n\tcreateTypeMismatchMessage,\n\tcreateUnanalyzableMessage,\n\tcreateUnknownHelperMessage,\n} from \"./errors\";\nimport { DefaultHelpers } from \"./helpers/default-helpers.ts\";\nimport { MapHelpers } from \"./helpers/map-helpers.ts\";\nimport {\n\tdetectLiteralType,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisDataExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisThisExpression,\n\tparse,\n} from \"./parser\";\nimport {\n\tfindConditionalSchemaLocations,\n\tisPropertyRequired,\n\tresolveArrayItems,\n\tresolveSchemaPath,\n\tsimplifySchema,\n} from \"./schema-resolver\";\nimport type {\n\tAnalysisResult,\n\tDiagnosticCode,\n\tDiagnosticDetails,\n\tHelperDefinition,\n\tTemplateDiagnostic,\n\tTemplateInput,\n} from \"./types.ts\";\nimport {\n\tdeepEqual,\n\textractSourceSnippet,\n\tgetSchemaPropertyNames,\n} from \"./utils\";\n\n// ─── Static Analyzer ─────────────────────────────────────────────────────────\n// Static analysis of a Handlebars template against a JSON Schema v7\n// describing the available context.\n//\n// Merged architecture (v2):\n// A single AST traversal performs both **validation** and **return type\n// inference** simultaneously. This eliminates duplication between the former\n// `validate*` and `infer*` functions and improves performance by avoiding\n// a double traversal.\n//\n// Context:\n// The analysis context uses a **save/restore** pattern instead of creating\n// new objects on each recursion (`{ ...ctx, current: X }`). This reduces\n// GC pressure for deeply nested templates.\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows referencing a variable from a specific\n// schema, identified by an integer N. The optional `identifierSchemas`\n// parameter provides a mapping `{ [id]: JSONSchema7 }`.\n//\n// Resolution rules:\n// - `{{meetingId}}` → validated against `inputSchema` (standard behavior)\n// - `{{meetingId:1}}` → validated against `identifierSchemas[1]`\n// - `{{meetingId:1}}` without `identifierSchemas[1]` → error\n\n// ─── Internal Types ──────────────────────────────────────────────────────────\n\n/** Context passed recursively during AST traversal */\ninterface AnalysisContext {\n\t/** Root schema (for resolving $refs) */\n\troot: JSONSchema7;\n\t/** Current context schema (changes with #each, #with) — mutated via save/restore */\n\tcurrent: JSONSchema7;\n\t/** Diagnostics accumulator */\n\tdiagnostics: TemplateDiagnostic[];\n\t/** Full template source (for extracting error snippets) */\n\ttemplate: string;\n\t/** Schemas by template identifier (for the {{key:N}} syntax) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Registered custom helpers (for static analysis) */\n\thelpers?: Map<string, HelperDefinition>;\n\t/**\n\t * Explicit coercion schema provided by the caller.\n\t * When set, static literal values like `\"123\"` will respect the type\n\t * declared in this schema instead of being auto-detected by\n\t * `detectLiteralType`. Unlike the previous `expectedOutputType`,\n\t * this is NEVER derived from the inputSchema — it must be explicitly\n\t * provided via the `coerceSchema` option.\n\t */\n\tcoerceSchema?: JSONSchema7;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/** Options for the standalone `analyze()` function */\nexport interface AnalyzeOptions {\n\t/** Schemas by template identifier (for the `{{key:N}}` syntax) */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/**\n\t * Explicit coercion schema. When provided, static literal values\n\t * will respect the types declared in this schema instead of being\n\t * auto-detected by `detectLiteralType`.\n\t *\n\t * This schema is independent from the `inputSchema` (which describes\n\t * available variables) — it only controls the output type inference\n\t * for static content.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/**\n\t * When `true`, properties whose values contain Handlebars expressions\n\t * (i.e. any `{{…}}` syntax) are excluded from the output schema.\n\t *\n\t * Only the properties with static values (literals, plain strings\n\t * without expressions) are retained. This is useful when you want\n\t * the output schema to describe only the known, compile-time-constant\n\t * portion of the template.\n\t *\n\t * This option only has an effect on **object** and **array** templates.\n\t * A root-level string template with expressions is analyzed normally\n\t * (there is no parent property to exclude it from).\n\t *\n\t * @default false\n\t */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Coerce Text Value ──────────────────────────────────────────────────────\n\n/**\n * Parses a raw text string into the appropriate JS primitive according to the\n * target JSON Schema type. Used when `coerceSchema` overrides the default\n * `detectLiteralType` inference for static literal values.\n */\nfunction coerceTextValue(\n\ttext: string,\n\ttargetType: \"string\" | \"number\" | \"integer\" | \"boolean\" | \"null\",\n): string | number | boolean | null | undefined {\n\tswitch (targetType) {\n\t\tcase \"number\":\n\t\tcase \"integer\": {\n\t\t\tif (text === \"\") return undefined;\n\t\t\tconst num = Number(text);\n\t\t\tif (Number.isNaN(num)) return undefined;\n\t\t\tif (targetType === \"integer\" && !Number.isInteger(num)) return undefined;\n\t\t\treturn num;\n\t\t}\n\t\tcase \"boolean\": {\n\t\t\tconst lower = text.toLowerCase();\n\t\t\tif (lower === \"true\") return true;\n\t\t\tif (lower === \"false\") return false;\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"null\":\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn text;\n\t}\n}\n\n/**\n * Statically analyzes a template against a JSON Schema v7 describing the\n * available context.\n *\n * Backward-compatible version — parses the template internally.\n * Uses `dispatchAnalyze` for the recursive array/object/literal dispatching,\n * delegating only the string (template) case to `analyzeFromAst`.\n *\n * @param template - The template string (e.g. `\"Hello {{user.name}}\"`)\n * @param inputSchema - JSON Schema v7 describing the available variables\n * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n * @returns An `AnalysisResult` containing validity, diagnostics, and the\n * inferred output schema.\n */\nexport function analyze(\n\ttemplate: TemplateInput,\n\tinputSchema: JSONSchema7 = {},\n\toptions?: AnalyzeOptions,\n): AnalysisResult {\n\treturn dispatchAnalyze(\n\t\ttemplate,\n\t\toptions,\n\t\t// String handler — parse and analyze the AST\n\t\t(tpl, coerceSchema) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tcoerceSchema,\n\t\t\t});\n\t\t},\n\t\t// Recursive handler — re-enter analyze() for child elements\n\t\t(child, childOptions) => analyze(child, inputSchema, childOptions),\n\t);\n}\n\n/**\n * Statically analyzes a template from an already-parsed AST.\n *\n * This is the internal function used by `Typebars.compile()` and\n * `CompiledTemplate.analyze()` to avoid costly re-parsing.\n *\n * @param ast - The already-parsed Handlebars AST\n * @param template - The template source (for error snippets)\n * @param inputSchema - JSON Schema v7 describing the available variables\n * @param options - Additional options\n * @returns An `AnalysisResult`\n */\nexport function analyzeFromAst(\n\tast: hbs.AST.Program,\n\ttemplate: string,\n\tinputSchema: JSONSchema7 = {},\n\toptions?: {\n\t\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t\thelpers?: Map<string, HelperDefinition>;\n\t\t/**\n\t\t * Explicit coercion schema. When set, static literal values will\n\t\t * respect the types declared in this schema instead of auto-detecting.\n\t\t * Unlike `expectedOutputType`, this is NEVER derived from inputSchema.\n\t\t */\n\t\tcoerceSchema?: JSONSchema7;\n\t},\n): AnalysisResult {\n\t// ── Initialize the diagnostic context FIRST ────────────────────────\n\tconst ctx: AnalysisContext = {\n\t\troot: inputSchema,\n\t\tcurrent: inputSchema,\n\t\tdiagnostics: [],\n\t\ttemplate,\n\t\tidentifierSchemas: options?.identifierSchemas,\n\t\thelpers: options?.helpers,\n\t\tcoerceSchema: options?.coerceSchema,\n\t};\n\n\t// ── Detect unsupported schema features as diagnostics ──────────────\n\t// Conditional schemas (if/then/else) are non-resolvable without runtime\n\t// data. Instead of throwing, we collect structured diagnostics so the\n\t// caller receives a standard AnalysisResult.\n\tconst conditionalLocations = findConditionalSchemaLocations(inputSchema);\n\tfor (const loc of conditionalLocations) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNSUPPORTED_SCHEMA\",\n\t\t\t\"error\",\n\t\t\t`Unsupported JSON Schema feature: \"${loc.keyword}\" at \"${loc.schemaPath}\". ` +\n\t\t\t\t\"Conditional schemas (if/then/else) cannot be resolved during static analysis \" +\n\t\t\t\t\"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.\",\n\t\t\tundefined,\n\t\t\t{ path: loc.schemaPath },\n\t\t);\n\t}\n\n\tif (options?.identifierSchemas) {\n\t\tfor (const [id, idSchema] of Object.entries(options.identifierSchemas)) {\n\t\t\tconst idLocations = findConditionalSchemaLocations(\n\t\t\t\tidSchema,\n\t\t\t\t`/identifierSchemas/${id}`,\n\t\t\t);\n\t\t\tfor (const loc of idLocations) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"UNSUPPORTED_SCHEMA\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\t`Unsupported JSON Schema feature: \"${loc.keyword}\" at \"${loc.schemaPath}\". ` +\n\t\t\t\t\t\t\"Conditional schemas (if/then/else) cannot be resolved during static analysis \" +\n\t\t\t\t\t\t\"because they depend on runtime data. Consider using oneOf/anyOf combinators instead.\",\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ path: loc.schemaPath },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// If unsupported schemas were found, return early with valid: false\n\tif (ctx.diagnostics.length > 0) {\n\t\treturn {\n\t\t\tvalid: false,\n\t\t\tdiagnostics: ctx.diagnostics,\n\t\t\toutputSchema: {},\n\t\t};\n\t}\n\n\t// Single pass: type inference + validation in one traversal.\n\tconst outputSchema = inferProgramType(ast, ctx);\n\n\tconst hasErrors = ctx.diagnostics.some((d) => d.severity === \"error\");\n\n\treturn {\n\t\tvalid: !hasErrors,\n\t\tdiagnostics: ctx.diagnostics,\n\t\toutputSchema: simplifySchema(outputSchema),\n\t};\n}\n\n// ─── Unified AST Traversal ───────────────────────────────────────────────────\n// A single set of functions handles both validation (emitting diagnostics)\n// and type inference (returning a JSONSchema7).\n//\n// Main functions:\n// - `inferProgramType` — entry point for a Program (template body or block)\n// - `processStatement` — dispatches a statement (validation side-effects)\n// - `processMustache` — handles a MustacheStatement (expression or inline helper)\n// - `inferBlockType` — handles a BlockStatement (if, each, with, custom…)\n\n/**\n * Dispatches the processing of an individual statement.\n *\n * Called by `inferProgramType` in the \"mixed template\" case to validate\n * each statement while ignoring the returned type (the result is always\n * `string` for a mixed template).\n *\n * @returns The inferred schema for this statement, or `undefined` for\n * statements with no semantics (ContentStatement, CommentStatement).\n */\nfunction processStatement(\n\tstmt: hbs.AST.Statement,\n\tctx: AnalysisContext,\n): JSONSchema7 | undefined {\n\tswitch (stmt.type) {\n\t\tcase \"ContentStatement\":\n\t\tcase \"CommentStatement\":\n\t\t\t// Static text or comment — nothing to validate, no type to infer\n\t\t\treturn undefined;\n\n\t\tcase \"MustacheStatement\":\n\t\t\treturn processMustache(stmt as hbs.AST.MustacheStatement, ctx);\n\n\t\tcase \"BlockStatement\":\n\t\t\treturn inferBlockType(stmt as hbs.AST.BlockStatement, ctx);\n\n\t\tdefault:\n\t\t\t// Unrecognized AST node — emit a warning rather than an error\n\t\t\t// to avoid blocking on future Handlebars extensions.\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"UNANALYZABLE\",\n\t\t\t\t\"warning\",\n\t\t\t\t`Unsupported AST node type: \"${stmt.type}\"`,\n\t\t\t\tstmt,\n\t\t\t);\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Processes a MustacheStatement `{{expression}}` or `{{helper arg}}`.\n *\n * Distinguishes two cases:\n * 1. **Simple expression** (`{{name}}`, `{{user.age}}`) — resolution in the schema\n * 2. **Inline helper** (`{{uppercase name}}`) — params > 0 or hash present\n *\n * @returns The inferred schema for this expression\n */\nfunction processMustache(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\t// Sub-expressions (nested helpers) are not supported for static\n\t// analysis — emit a warning.\n\tif (stmt.path.type === \"SubExpression\") {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNANALYZABLE\",\n\t\t\t\"warning\",\n\t\t\t\"Sub-expressions are not statically analyzable\",\n\t\t\tstmt,\n\t\t);\n\t\treturn {};\n\t}\n\n\t// ── Inline helper detection ──────────────────────────────────────────────\n\t// If the MustacheStatement has parameters or a hash, it's a helper call\n\t// (e.g. `{{uppercase name}}`), not a simple expression.\n\tif (stmt.params.length > 0 || stmt.hash) {\n\t\tconst helperName = getExpressionName(stmt.path);\n\n\t\t// ── Special-case: map helper ─────────────────────────────────────\n\t\t// The `map` helper requires deep static analysis that the generic\n\t\t// helper path cannot perform: it must resolve the first argument as\n\t\t// an array-of-objects schema, then resolve the second argument (a\n\t\t// property name) within the item schema to infer the output type\n\t\t// `{ type: \"array\", items: <property schema> }`.\n\t\tif (helperName === MapHelpers.MAP_HELPER_NAME) {\n\t\t\treturn processMapHelper(stmt, ctx);\n\t\t}\n\n\t\t// ── Special-case: default helper ─────────────────────────────────\n\t\t// The `default` helper requires deep static analysis: the return\n\t\t// type is the union of all argument types, and the chain must\n\t\t// terminate with a guaranteed (non-optional) value.\n\t\tif (helperName === DefaultHelpers.DEFAULT_HELPER_NAME) {\n\t\t\treturn processDefaultHelper(stmt, ctx);\n\t\t}\n\n\t\t// Check if the helper is registered\n\t\tconst helper = ctx.helpers?.get(helperName);\n\t\tif (helper) {\n\t\t\tconst helperParams = helper.params;\n\n\t\t\t// ── Check the number of required parameters ──────────────\n\t\t\tif (helperParams) {\n\t\t\t\tconst requiredCount = helperParams.filter((p) => !p.optional).length;\n\t\t\t\tif (stmt.params.length < requiredCount) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t`Helper \"${helperName}\" expects at least ${requiredCount} argument(s), but got ${stmt.params.length}`,\n\t\t\t\t\t\tstmt,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\texpected: `${requiredCount} argument(s)`,\n\t\t\t\t\t\t\tactual: `${stmt.params.length} argument(s)`,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Validate each parameter (existence + type) ───────────────\n\t\t\tfor (let i = 0; i < stmt.params.length; i++) {\n\t\t\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(\n\t\t\t\t\tstmt.params[i] as hbs.AST.Expression,\n\t\t\t\t\tctx,\n\t\t\t\t\tstmt,\n\t\t\t\t);\n\n\t\t\t\t// Check type compatibility if the helper declares the\n\t\t\t\t// expected type for this parameter\n\t\t\t\tconst helperParam = helperParams?.[i];\n\t\t\t\tif (resolvedSchema && helperParam?.type) {\n\t\t\t\t\tconst expectedType = helperParam.type;\n\t\t\t\t\tif (!isParamTypeCompatible(resolvedSchema, expectedType)) {\n\t\t\t\t\t\tconst paramName = helperParam.name;\n\t\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\t`Helper \"${helperName}\" parameter \"${paramName}\" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,\n\t\t\t\t\t\t\tstmt,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\t\texpected: schemaTypeLabel(expectedType),\n\t\t\t\t\t\t\t\tactual: schemaTypeLabel(resolvedSchema),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn helper.returnType ?? { type: \"string\" };\n\t\t}\n\n\t\t// Unknown inline helper — warning\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\"warning\",\n\t\t\t`Unknown inline helper \"${helperName}\" — cannot analyze statically`,\n\t\t\tstmt,\n\t\t\t{ helperName },\n\t\t);\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Simple expression ────────────────────────────────────────────────────\n\tconst resolved = resolveExpressionWithDiagnostics(stmt.path, ctx, stmt) ?? {};\n\n\t// @data variables (@index, @first, @last, @key) are runtime-provided —\n\t// optionality checks against the input schema do not apply.\n\tif (isDataExpression(stmt.path)) {\n\t\treturn resolved;\n\t}\n\n\t// When the expression points to an optional property (not in `required`),\n\t// the output can be null at runtime. Wrap the resolved schema with null\n\t// so the output schema accurately reflects this.\n\t// $root returns the entire context — optionality does not apply.\n\tif (stmt.path.type === \"PathExpression\") {\n\t\tconst segments = extractPathSegments(stmt.path);\n\t\tif (segments.length > 0) {\n\t\t\tconst { cleanSegments, identifier } =\n\t\t\t\textractExpressionIdentifier(segments);\n\t\t\tif (!isRootSegments(cleanSegments)) {\n\t\t\t\tlet targetSchema =\n\t\t\t\t\tidentifier !== null\n\t\t\t\t\t\t? ctx.identifierSchemas?.[identifier]\n\t\t\t\t\t\t: ctx.current;\n\t\t\t\t// For aggregated identifiers (array schema), check optionality\n\t\t\t\t// within the items schema, not the array itself.\n\t\t\t\tif (targetSchema && identifier !== null) {\n\t\t\t\t\tconst itemSchema = resolveArrayItems(targetSchema, ctx.root);\n\t\t\t\t\tif (itemSchema !== undefined) {\n\t\t\t\t\t\ttargetSchema = itemSchema;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (targetSchema && !isPathFullyRequired(targetSchema, cleanSegments)) {\n\t\t\t\t\treturn withNullType(resolved);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resolved;\n}\n\n// ─── map helper — special-case analysis ──────────────────────────────────────\n// Validates the arguments and infers the precise return type:\n// {{ map <arrayPath> <propertyName> }}\n// → { type: \"array\", items: <schema of the property in the item> }\n//\n// Validation rules:\n// 1. Exactly 2 arguments are required\n// 2. The first argument must resolve to an array schema\n// 3. The array items must be an object schema\n// 4. The second argument must be a string literal (property name)\n// 5. The property must exist in the item schema\n\nfunction processMapHelper(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst helperName = MapHelpers.MAP_HELPER_NAME;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (stmt.params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${stmt.params.length}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${stmt.params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 2. Resolve the first argument (collection path) ──────────────────\n\tconst collectionExpr = stmt.params[0] as hbs.AST.Expression;\n\tconst collectionSchema = resolveExpressionWithDiagnostics(\n\t\tcollectionExpr,\n\t\tctx,\n\t\tstmt,\n\t);\n\n\tif (!collectionSchema) {\n\t\t// Path resolution failed — diagnostic already emitted\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 3. Validate that the collection is an array ──────────────────────\n\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\tif (!itemSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"collection\" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"array\",\n\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 4. Validate that the items are objects ───────────────────────────\n\t// If the items are arrays (e.g. from a nested map), flatten one level\n\t// to match the runtime `flat(1)` behavior and use the inner items instead.\n\tlet effectiveItemSchema = itemSchema;\n\tconst itemType = effectiveItemSchema.type;\n\tif (\n\t\titemType === \"array\" ||\n\t\t(Array.isArray(itemType) && itemType.includes(\"array\"))\n\t) {\n\t\tconst innerItems = resolveArrayItems(effectiveItemSchema, ctx.root);\n\t\tif (innerItems) {\n\t\t\teffectiveItemSchema = innerItems;\n\t\t\t// Emit an informational warning so consumers know the flatten happened\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"MAP_IMPLICIT_FLATTEN\",\n\t\t\t\t\"warning\",\n\t\t\t\t`The \"${helperName}\" helper will automatically flatten the input array one level before mapping. ` +\n\t\t\t\t\t`The item type \"${Array.isArray(itemType) ? itemType.join(\" | \") : itemType}\" was unwrapped to its inner items schema.`,\n\t\t\t\tstmt,\n\t\t\t\t{\n\t\t\t\t\thelperName,\n\t\t\t\t\texpected: \"object\",\n\t\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\tconst effectiveItemType = effectiveItemSchema.type;\n\tconst isObject =\n\t\teffectiveItemType === \"object\" ||\n\t\t(Array.isArray(effectiveItemType) &&\n\t\t\teffectiveItemType.includes(\"object\")) ||\n\t\t// If no type but has properties, treat as object\n\t\t(!effectiveItemType && effectiveItemSchema.properties !== undefined);\n\n\tif (!isObject && effectiveItemType !== undefined) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects an array of objects, but the array items have type \"${schemaTypeLabel(effectiveItemSchema)}\"`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"object\",\n\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 5. Validate the second argument (property name) ──────────────────\n\tconst propertyExpr = stmt.params[1] as hbs.AST.Expression;\n\n\t// The property name MUST be a StringLiteral (quoted string like `\"name\"`).\n\t// A bare identifier like `name` is parsed by Handlebars as a PathExpression,\n\t// which would be resolved as a data path at runtime — yielding `undefined`\n\t// when the identifier doesn't exist in the top-level context. This is a\n\t// common mistake, so we provide a clear error message guiding the user.\n\tlet propertyName: string | undefined;\n\n\tif (propertyExpr.type === \"PathExpression\") {\n\t\tconst bare = (propertyExpr as hbs.AST.PathExpression).original;\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" must be a quoted string. ` +\n\t\t\t\t`Use {{ ${helperName} … \"${bare}\" }} instead of {{ ${helperName} … ${bare} }}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: `PathExpression (${bare})`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\tif (propertyExpr.type === \"StringLiteral\") {\n\t\tpropertyName = (propertyExpr as hbs.AST.StringLiteral).value;\n\t}\n\n\tif (!propertyName) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" expects a quoted string literal, but got ${propertyExpr.type}`,\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: propertyExpr.type,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 6. Resolve the property within the item schema ───────────────────\n\tconst propertySchema = resolveSchemaPath(effectiveItemSchema, [propertyName]);\n\tif (!propertySchema) {\n\t\tconst availableProperties = getSchemaPropertyNames(effectiveItemSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(propertyName, availableProperties),\n\t\t\tstmt,\n\t\t\t{\n\t\t\t\tpath: propertyName,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 7. Return the inferred output schema ─────────────────────────────\n\treturn { type: \"array\", items: propertySchema };\n}\n\n// ─── default helper — special-case analysis ──────────────────────────────────\n// Validates the arguments and infers the return type as the union of all\n// argument types. The chain must terminate with a guaranteed value.\n//\n// Validation rules:\n// 1. At least 2 arguments are required\n// 2. All arguments must be type-compatible\n// 3. The chain must end with a guaranteed value (literal, required property,\n// or sub-expression)\n\n/**\n * Analyzes a `default` helper MustacheStatement and returns the inferred\n * output schema. Shared logic with `processDefaultSubExpression`.\n */\nfunction processDefaultHelper(\n\tstmt: hbs.AST.MustacheStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\treturn analyzeDefaultArgs(stmt.params as hbs.AST.Expression[], ctx, stmt);\n}\n\n/**\n * Analyzes a `default` helper SubExpression and returns the inferred\n * output schema.\n */\nfunction processDefaultSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 {\n\treturn analyzeDefaultArgs(\n\t\texpr.params as hbs.AST.Expression[],\n\t\tctx,\n\t\tparentNode ?? expr,\n\t);\n}\n\n/**\n * Core analysis logic for the `default` helper (shared by Mustache and\n * SubExpression paths).\n *\n * 1. Validates argument count (≥ 2)\n * 2. Resolves the schema of each argument\n * 3. Checks type compatibility between all arguments\n * 4. Verifies that at least one argument is guaranteed (non-optional)\n * 5. Returns the simplified union of all argument types\n */\nfunction analyzeDefaultArgs(\n\tparams: hbs.AST.Expression[],\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 {\n\tconst helperName = DefaultHelpers.DEFAULT_HELPER_NAME;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${params.length}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn {};\n\t}\n\n\t// ── 2. Resolve the schema of each argument ───────────────────────────\n\tconst resolvedSchemas: JSONSchema7[] = [];\n\tlet hasGuaranteedValue = false;\n\n\tfor (let i = 0; i < params.length; i++) {\n\t\tconst param = params[i] as hbs.AST.Expression;\n\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(param, ctx, node);\n\n\t\tif (resolvedSchema) {\n\t\t\tresolvedSchemas.push(resolvedSchema);\n\t\t}\n\n\t\t// ── 3. Check if this argument is guaranteed ──────────────────────\n\t\tif (isGuaranteedExpression(param, ctx)) {\n\t\t\thasGuaranteedValue = true;\n\t\t}\n\t}\n\n\t// ── 4. Check type compatibility between all arguments ────────────────\n\t// All arguments must be compatible with each other. We compare each\n\t// pair of resolved schemas (only those with type info).\n\tif (resolvedSchemas.length >= 2) {\n\t\tconst firstWithType = resolvedSchemas.find((s) => s.type);\n\t\tif (firstWithType) {\n\t\t\tfor (let i = 0; i < resolvedSchemas.length; i++) {\n\t\t\t\tconst schema = resolvedSchemas[i] as JSONSchema7;\n\t\t\t\tif (schema.type && !isParamTypeCompatible(schema, firstWithType)) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t`Helper \"${helperName}\" argument ${i + 1} has type ${schemaTypeLabel(schema)}, incompatible with ${schemaTypeLabel(firstWithType)}`,\n\t\t\t\t\t\tnode,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thelperName,\n\t\t\t\t\t\t\texpected: schemaTypeLabel(firstWithType),\n\t\t\t\t\t\t\tactual: schemaTypeLabel(schema),\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── 5. Verify the chain terminates with a guaranteed value ───────────\n\tif (!hasGuaranteedValue) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"DEFAULT_NO_GUARANTEED_VALUE\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" argument chain has no guaranteed fallback — ` +\n\t\t\t\t\"the last argument must be a literal or a non-optional property\",\n\t\t\tnode,\n\t\t\t{ helperName },\n\t\t);\n\t}\n\n\t// ── 6. Return the union of all argument types ────────────────────────\n\tif (resolvedSchemas.length === 0) return {};\n\tif (resolvedSchemas.length === 1) return resolvedSchemas[0] as JSONSchema7;\n\n\treturn simplifySchema({ oneOf: resolvedSchemas });\n}\n\n/**\n * Determines whether a template expression is **guaranteed** to produce a\n * non-nullish value at runtime.\n *\n * An expression is guaranteed when:\n * - It is a literal (StringLiteral, NumberLiteral, BooleanLiteral)\n * - It is a SubExpression (helpers always return a value)\n * - It is a PathExpression pointing to a **required** property in the schema\n */\nfunction isGuaranteedExpression(\n\texpr: hbs.AST.Expression,\n\tctx: AnalysisContext,\n): boolean {\n\t// Literals are always guaranteed\n\tif (\n\t\texpr.type === \"StringLiteral\" ||\n\t\texpr.type === \"NumberLiteral\" ||\n\t\texpr.type === \"BooleanLiteral\"\n\t) {\n\t\treturn true;\n\t}\n\n\t// Sub-expressions (helper calls) are considered guaranteed\n\tif (expr.type === \"SubExpression\") {\n\t\treturn true;\n\t}\n\n\t// PathExpression: check if the property is required in the schema\n\tif (expr.type === \"PathExpression\") {\n\t\tconst segments = extractPathSegments(expr);\n\t\tif (segments.length === 0) return false;\n\n\t\tconst { cleanSegments } = extractExpressionIdentifier(segments);\n\t\treturn isPropertyRequired(ctx.current, cleanSegments);\n\t}\n\n\treturn false;\n}\n\n/**\n * Checks whether a resolved type is compatible with the type expected\n * by a helper parameter.\n *\n * Compatibility rules:\n * - If either schema has no `type`, validation is not possible → compatible\n * - `integer` is compatible with `number` (integer ⊂ number)\n * - For multiple types (e.g. `[\"string\", \"number\"]`), at least one resolved\n * type must match one expected type\n */\nfunction isParamTypeCompatible(\n\tresolved: JSONSchema7,\n\texpected: JSONSchema7,\n): boolean {\n\t// If either has no type info, we cannot validate\n\tif (!expected.type || !resolved.type) return true;\n\n\tconst expectedTypes = Array.isArray(expected.type)\n\t\t? expected.type\n\t\t: [expected.type];\n\tconst resolvedTypes = Array.isArray(resolved.type)\n\t\t? resolved.type\n\t\t: [resolved.type];\n\n\t// At least one resolved type must be compatible with one expected type\n\treturn resolvedTypes.some((rt) =>\n\t\texpectedTypes.some(\n\t\t\t(et) =>\n\t\t\t\trt === et ||\n\t\t\t\t// integer is a subtype of number\n\t\t\t\t(et === \"number\" && rt === \"integer\") ||\n\t\t\t\t(et === \"integer\" && rt === \"number\"),\n\t\t),\n\t);\n}\n\n/**\n * Infers the output type of a `Program` (template body or block body).\n *\n * Handles 4 cases, from most specific to most general:\n *\n * 1. **Single expression** `{{expr}}` → type of the expression\n * 2. **Single block** `{{#if}}…{{/if}}` → type of the block\n * 3. **Pure text content** → literal detection (number, boolean, null)\n * 4. **Mixed template** → always `string` (concatenation)\n *\n * Validation is performed alongside inference: each expression and block\n * is validated during processing.\n */\nfunction inferProgramType(\n\tprogram: hbs.AST.Program,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst effective = getEffectiveBody(program);\n\n\t// No significant statements → empty string\n\tif (effective.length === 0) {\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Case 1: single expression {{expr}} ─────────────────────────────────\n\tconst singleExpr = getEffectivelySingleExpression(program);\n\tif (singleExpr) {\n\t\treturn processMustache(singleExpr, ctx);\n\t}\n\n\t// ── Case 2: single block {{#if}}, {{#each}}, {{#with}}, … ──────────────\n\tconst singleBlock = getEffectivelySingleBlock(program);\n\tif (singleBlock) {\n\t\treturn inferBlockType(singleBlock, ctx);\n\t}\n\n\t// ── Case 3: only ContentStatements (no expressions) ────────────────────\n\t// If the concatenated (trimmed) text is a typed literal (number, boolean,\n\t// null), we infer the corresponding type.\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\tconst text = effective\n\t\t\t.map((s) => (s as hbs.AST.ContentStatement).value)\n\t\t\t.join(\"\")\n\t\t\t.trim();\n\n\t\tif (text === \"\") return { type: \"string\" };\n\n\t\t// If an explicit coerceSchema was provided and declares a specific\n\t\t// primitive type, respect it instead of auto-detecting. For example,\n\t\t// \"123\" with coerceSchema `{ type: \"string\" }` should stay \"string\".\n\t\t// This only applies when coerceSchema is explicitly set — the\n\t\t// inputSchema is NEVER used for coercion.\n\t\t//\n\t\t// Only the **type** is extracted from coerceSchema. Value-level\n\t\t// constraints (enum, const, format, pattern, minLength, …) are NOT\n\t\t// propagated because they describe what the *consumer* accepts, not\n\t\t// what the literal *produces*. The actual literal value is set as\n\t\t// `const` so downstream compatibility checkers can detect mismatches.\n\t\tconst coercedType = ctx.coerceSchema?.type;\n\t\tif (\n\t\t\ttypeof coercedType === \"string\" &&\n\t\t\t(coercedType === \"string\" ||\n\t\t\t\tcoercedType === \"number\" ||\n\t\t\t\tcoercedType === \"integer\" ||\n\t\t\t\tcoercedType === \"boolean\" ||\n\t\t\t\tcoercedType === \"null\")\n\t\t) {\n\t\t\tconst coercedValue = coerceTextValue(text, coercedType);\n\t\t\treturn { type: coercedType, const: coercedValue } as JSONSchema7;\n\t\t}\n\n\t\tconst literalType = detectLiteralType(text);\n\t\tif (literalType) return { type: literalType };\n\t}\n\n\t// ── Case 4: multiple blocks only (no significant text between them) ────\n\t// When the effective body consists entirely of BlockStatements, gather\n\t// each block's inferred type and combine them via oneOf. This handles\n\t// templates like:\n\t// {{#if showName}}{{name}}{{/if}}\n\t// {{#if showAge}}{{age}}{{/if}}\n\t// where the output could be string OR number depending on which branch\n\t// is active.\n\tconst allBlocks = effective.every((s) => s.type === \"BlockStatement\");\n\tif (allBlocks) {\n\t\tconst types: JSONSchema7[] = [];\n\t\tfor (const stmt of effective) {\n\t\t\tconst t = inferBlockType(stmt as hbs.AST.BlockStatement, ctx);\n\t\t\tif (t) types.push(t);\n\t\t}\n\t\tif (types.length === 1) return types[0] as JSONSchema7;\n\t\tif (types.length > 1) return simplifySchema({ oneOf: types });\n\t\treturn { type: \"string\" };\n\t}\n\n\t// ── Case 5: mixed template (text + expressions, blocks…) ───────────────\n\t// Traverse all statements for validation (side-effects: diagnostics).\n\t// The result is always string (concatenation).\n\tfor (const stmt of program.body) {\n\t\tprocessStatement(stmt, ctx);\n\t}\n\treturn { type: \"string\" };\n}\n\n/**\n * Infers the output type of a BlockStatement and validates its content.\n *\n * Supports built-in helpers (`if`, `unless`, `each`, `with`) and custom\n * helpers registered via `Typebars.registerHelper()`.\n *\n * Uses the **save/restore** pattern for context: instead of creating a new\n * object `{ ...ctx, current: X }` on each recursion, we save `ctx.current`,\n * mutate it, process the body, then restore. This reduces GC pressure for\n * deeply nested templates.\n */\nfunction inferBlockType(\n\tstmt: hbs.AST.BlockStatement,\n\tctx: AnalysisContext,\n): JSONSchema7 {\n\tconst helperName = getBlockHelperName(stmt);\n\n\tswitch (helperName) {\n\t\t// ── if / unless ──────────────────────────────────────────────────────\n\t\t// Validate the condition argument, then infer types from both branches.\n\t\tcase \"if\":\n\t\tcase \"unless\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (arg) {\n\t\t\t\tresolveExpressionWithDiagnostics(arg, ctx, stmt);\n\t\t\t} else {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(helperName),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Infer the type of the \"then\" branch\n\t\t\tconst thenType = inferProgramType(stmt.program, ctx);\n\n\t\t\tif (stmt.inverse) {\n\t\t\t\tconst elseType = inferProgramType(stmt.inverse, ctx);\n\t\t\t\t// If both branches have the same type → single type\n\t\t\t\tif (deepEqual(thenType, elseType)) return thenType;\n\t\t\t\t// Otherwise → union of both types\n\t\t\t\treturn simplifySchema({ oneOf: [thenType, elseType] });\n\t\t\t}\n\n\t\t\t// No else branch → the result is the type of the then branch\n\t\t\t// (conceptually optional, but Handlebars returns \"\" for falsy)\n\t\t\treturn thenType;\n\t\t}\n\n\t\t// ── each ─────────────────────────────────────────────────────────────\n\t\t// Resolve the collection schema, then validate the body with the item\n\t\t// schema as the new context.\n\t\tcase \"each\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (!arg) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(\"each\"),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName: \"each\" },\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context (best-effort)\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\tconst collectionSchema = resolveExpressionWithDiagnostics(arg, ctx, stmt);\n\t\t\tif (!collectionSchema) {\n\t\t\t\t// The path could not be resolved — diagnostic already emitted.\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Resolve the schema of the array elements\n\t\t\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\t\t\tif (!itemSchema) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateTypeMismatchMessage(\n\t\t\t\t\t\t\"each\",\n\t\t\t\t\t\t\"an array\",\n\t\t\t\t\t\tschemaTypeLabel(collectionSchema),\n\t\t\t\t\t),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{\n\t\t\t\t\t\thelperName: \"each\",\n\t\t\t\t\t\texpected: \"array\",\n\t\t\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context (best-effort)\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Validate the body with the item schema as the new context\n\t\t\tconst saved = ctx.current;\n\t\t\tctx.current = itemSchema;\n\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\tctx.current = saved;\n\n\t\t\t// The inverse branch ({{else}}) keeps the parent context\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\n\t\t\t// An each concatenates renders → always string\n\t\t\treturn { type: \"string\" };\n\t\t}\n\n\t\t// ── with ─────────────────────────────────────────────────────────────\n\t\t// Resolve the inner schema, then validate the body with it as the\n\t\t// new context.\n\t\tcase \"with\": {\n\t\t\tconst arg = getBlockArgument(stmt);\n\t\t\tif (!arg) {\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\tcreateMissingArgumentMessage(\"with\"),\n\t\t\t\t\tstmt,\n\t\t\t\t\t{ helperName: \"with\" },\n\t\t\t\t);\n\t\t\t\t// Validate the body with an empty context\n\t\t\t\tconst saved = ctx.current;\n\t\t\t\tctx.current = {};\n\t\t\t\tconst result = inferProgramType(stmt.program, ctx);\n\t\t\t\tctx.current = saved;\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tconst innerSchema = resolveExpressionWithDiagnostics(arg, ctx, stmt);\n\n\t\t\tconst saved = ctx.current;\n\t\t\tctx.current = innerSchema ?? {};\n\t\t\tconst result = inferProgramType(stmt.program, ctx);\n\t\t\tctx.current = saved;\n\n\t\t\t// The inverse branch keeps the parent context\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\n\t\t\treturn result;\n\t\t}\n\n\t\t// ── Custom or unknown helper ─────────────────────────────────────────\n\t\tdefault: {\n\t\t\tconst helper = ctx.helpers?.get(helperName);\n\t\t\tif (helper) {\n\t\t\t\t// Registered custom helper — validate parameters\n\t\t\t\tfor (const param of stmt.params) {\n\t\t\t\t\tresolveExpressionWithDiagnostics(\n\t\t\t\t\t\tparam as hbs.AST.Expression,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstmt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Validate the body with the current context\n\t\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\t\treturn helper.returnType ?? { type: \"string\" };\n\t\t\t}\n\n\t\t\t// Unknown helper — warning\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\t\"warning\",\n\t\t\t\tcreateUnknownHelperMessage(helperName),\n\t\t\t\tstmt,\n\t\t\t\t{ helperName },\n\t\t\t);\n\t\t\t// Still validate the body with the current context (best-effort)\n\t\t\tinferProgramType(stmt.program, ctx);\n\t\t\tif (stmt.inverse) inferProgramType(stmt.inverse, ctx);\n\t\t\treturn { type: \"string\" };\n\t\t}\n\t}\n}\n\n// ─── Expression Resolution ───────────────────────────────────────────────────\n\n/**\n * Resolves an AST expression to a sub-schema, emitting a diagnostic\n * if the path cannot be resolved.\n *\n * Handles the `{{key:N}}` syntax:\n * - If the expression has an identifier N → resolution in `identifierSchemas[N]`\n * - If identifier N has no associated schema → error\n * - If no identifier → resolution in `ctx.current` (standard behavior)\n *\n * @returns The resolved sub-schema, or `undefined` if the path is invalid.\n */\n\n// ─── @data variable types ────────────────────────────────────────────────────\n// Handlebars injects these variables inside block helpers at runtime.\n// We map each known variable to its static type so the analyzer can\n// validate templates that use them without false UNKNOWN_PROPERTY errors.\n\nconst DATA_VARIABLE_SCHEMAS: Record<string, JSONSchema7> = {\n\tindex: { type: \"number\" },\n\tfirst: { type: \"boolean\" },\n\tlast: { type: \"boolean\" },\n\tkey: { type: \"string\" },\n};\n\n/**\n * Returns the inferred schema for a Handlebars `@data` variable.\n * Known variables (`@index`, `@first`, `@last`, `@key`) return their\n * concrete type; unknown `@data` variables return the open schema `{}`\n * (any type) to avoid blocking valid templates.\n */\nfunction resolveDataExpression(expr: hbs.AST.PathExpression): JSONSchema7 {\n\tconst name = expr.parts[0];\n\tif (name && name in DATA_VARIABLE_SCHEMAS) {\n\t\treturn DATA_VARIABLE_SCHEMAS[name] as JSONSchema7;\n\t}\n\t// Unknown @data variable — return open schema (best-effort)\n\treturn {};\n}\n\nfunction resolveExpressionWithDiagnostics(\n\texpr: hbs.AST.Expression,\n\tctx: AnalysisContext,\n\t/** Parent AST node (for diagnostic location) */\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\t// Handle `this` / `.` → return the current context\n\tif (isThisExpression(expr)) {\n\t\treturn ctx.current;\n\t}\n\n\t// ── Handlebars @data variables (@index, @first, @last, @key) ────────────\n\t// These are runtime-provided by Handlebars inside block helpers (e.g.\n\t// `#each`). They are NOT part of the user's input schema, so we must\n\t// short-circuit here to avoid false UNKNOWN_PROPERTY diagnostics.\n\tif (isDataExpression(expr)) {\n\t\treturn resolveDataExpression(expr as hbs.AST.PathExpression);\n\t}\n\n\t// ── SubExpression (nested helper call, e.g. `(lt account.balance 500)`) ──\n\tif (expr.type === \"SubExpression\") {\n\t\treturn resolveSubExpression(expr as hbs.AST.SubExpression, ctx, parentNode);\n\t}\n\n\tconst segments = extractPathSegments(expr);\n\tif (segments.length === 0) {\n\t\t// Expression that is not a PathExpression (e.g. literal)\n\t\tif (expr.type === \"StringLiteral\") return { type: \"string\" };\n\t\tif (expr.type === \"NumberLiteral\") return { type: \"number\" };\n\t\tif (expr.type === \"BooleanLiteral\") return { type: \"boolean\" };\n\t\tif (expr.type === \"NullLiteral\") return { type: \"null\" };\n\t\tif (expr.type === \"UndefinedLiteral\") return {};\n\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNANALYZABLE\",\n\t\t\t\"warning\",\n\t\t\tcreateUnanalyzableMessage(expr.type),\n\t\t\tparentNode ?? expr,\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// ── Identifier extraction ──────────────────────────────────────────────\n\t// Extract the `:N` suffix BEFORE checking for `$root` so that both\n\t// `{{$root}}` and `{{$root:2}}` are handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// ── $root token ──────────────────────────────────────────────────────\n\t// Path traversal ($root.name, $root.address.city) is always forbidden,\n\t// regardless of whether an identifier is present.\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\tconst fullPath = cleanSegments.join(\".\");\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"ROOT_PATH_TRAVERSAL\",\n\t\t\t\"error\",\n\t\t\tcreateRootPathTraversalMessage(fullPath),\n\t\t\tparentNode ?? expr,\n\t\t\t{ path: fullPath },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// `{{$root}}` → return the entire current context schema\n\t// `{{$root:N}}` → return the entire schema for identifier N\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null) {\n\t\t\treturn resolveRootWithIdentifier(identifier, ctx, parentNode ?? expr);\n\t\t}\n\t\treturn ctx.current;\n\t}\n\n\tif (identifier !== null) {\n\t\t// The expression uses the {{key:N}} syntax — resolve from\n\t\t// the schema of identifier N.\n\t\treturn resolveWithIdentifier(\n\t\t\tcleanSegments,\n\t\t\tidentifier,\n\t\t\tctx,\n\t\t\tparentNode ?? expr,\n\t\t);\n\t}\n\n\t// ── Standard resolution (no identifier) ────────────────────────────────\n\tconst resolved = resolveSchemaPath(ctx.current, cleanSegments);\n\tif (resolved === undefined) {\n\t\tconst fullPath = cleanSegments.join(\".\");\n\t\tconst availableProperties = getSchemaPropertyNames(ctx.current);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(fullPath, availableProperties),\n\t\t\tparentNode ?? expr,\n\t\t\t{ path: fullPath, availableProperties },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn resolved;\n}\n\n/**\n * Resolves `{{$root:N}}` — returns the **entire** schema for identifier N.\n *\n * This is the identifier-aware counterpart of returning `ctx.current` for\n * a plain `{{$root}}`. Instead of navigating into properties, it returns\n * the identifier's root schema directly.\n *\n * When the identifier schema is an array (aggregated multi-version data),\n * the full array schema is returned as-is — the caller receives the\n * complete `{ type: \"array\", items: ... }` schema.\n *\n * Emits an error diagnostic if:\n * - No `identifierSchemas` were provided\n * - Identifier N has no associated schema\n */\nfunction resolveRootWithIdentifier(\n\tidentifier: number,\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\t// No identifierSchemas provided at all\n\tif (!ctx.identifierSchemas) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_IDENTIFIER_SCHEMAS\",\n\t\t\t\"error\",\n\t\t\t`Property \"$root:${identifier}\" uses an identifier but no identifier schemas were provided`,\n\t\t\tnode,\n\t\t\t{ path: `$root:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// The identifier does not exist in the provided schemas\n\tconst idSchema = ctx.identifierSchemas[identifier];\n\tif (!idSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_IDENTIFIER\",\n\t\t\t\"error\",\n\t\t\t`Property \"$root:${identifier}\" references identifier ${identifier} but no schema exists for this identifier`,\n\t\t\tnode,\n\t\t\t{ path: `$root:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// Return the entire schema for identifier N.\n\t// For aggregated identifiers (array schemas), this returns the full\n\t// array schema — e.g. { type: \"array\", items: { type: \"object\", ... } }\n\treturn idSchema;\n}\n\n/**\n * Resolves an expression with identifier `{{key:N}}` by looking up the\n * schema associated with identifier N.\n *\n * When the identifier schema is an array (aggregated multi-version data),\n * the property is resolved within the array's `items` schema, and the\n * result is wrapped in `{ type: \"array\", items: <resolved> }`. This\n * models the runtime behavior where `{{accountId:4}}` on an array of\n * objects extracts the property from each element, producing an array.\n *\n * Emits an error diagnostic if:\n * - No `identifierSchemas` were provided\n * - Identifier N has no associated schema\n * - The property does not exist in the identifier's schema\n */\nfunction resolveWithIdentifier(\n\tcleanSegments: string[],\n\tidentifier: number,\n\tctx: AnalysisContext,\n\tnode: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\tconst fullPath = cleanSegments.join(\".\");\n\n\t// No identifierSchemas provided at all\n\tif (!ctx.identifierSchemas) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_IDENTIFIER_SCHEMAS\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}:${identifier}\" uses an identifier but no identifier schemas were provided`,\n\t\t\tnode,\n\t\t\t{ path: `${fullPath}:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// The identifier does not exist in the provided schemas\n\tconst idSchema = ctx.identifierSchemas[identifier];\n\tif (!idSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_IDENTIFIER\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}:${identifier}\" references identifier ${identifier} but no schema exists for this identifier`,\n\t\t\tnode,\n\t\t\t{ path: `${fullPath}:${identifier}`, identifier },\n\t\t);\n\t\treturn undefined;\n\t}\n\n\t// ── Aggregated identifier (array schema) ─────────────────────────────\n\t// When the identifier schema is an array of objects (e.g. from a\n\t// multi-versioned workflow node), resolve the property within the\n\t// items schema and wrap the result in an array type.\n\t//\n\t// Example: identifierSchemas[4] = { type: \"array\", items: { type: \"object\",\n\t// properties: { accountId: { type: \"string\" } } } }\n\t// Expression: {{accountId:4}}\n\t// Result: { type: \"array\", items: { type: \"string\" } }\n\tconst itemSchema = resolveArrayItems(idSchema, ctx.root);\n\tif (itemSchema !== undefined) {\n\t\t// The identifier schema is an array — resolve within items\n\t\tconst resolved = resolveSchemaPath(itemSchema, cleanSegments);\n\t\tif (resolved === undefined) {\n\t\t\tconst availableProperties = getSchemaPropertyNames(itemSchema);\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"IDENTIFIER_PROPERTY_NOT_FOUND\",\n\t\t\t\t\"error\",\n\t\t\t\t`Property \"${fullPath}\" does not exist in the items schema for identifier ${identifier}`,\n\t\t\t\tnode,\n\t\t\t\t{\n\t\t\t\t\tpath: fullPath,\n\t\t\t\t\tidentifier,\n\t\t\t\t\tavailableProperties,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\t// Wrap the resolved property schema in an array\n\t\treturn { type: \"array\", items: resolved };\n\t}\n\n\t// ── Standard identifier (single object schema) ───────────────────────\n\t// Resolve the path within the identifier's schema directly.\n\tconst resolved = resolveSchemaPath(idSchema, cleanSegments);\n\tif (resolved === undefined) {\n\t\tconst availableProperties = getSchemaPropertyNames(idSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"IDENTIFIER_PROPERTY_NOT_FOUND\",\n\t\t\t\"error\",\n\t\t\t`Property \"${fullPath}\" does not exist in the schema for identifier ${identifier}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\tpath: fullPath,\n\t\t\t\tidentifier,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn resolved;\n}\n\n// ─── Nullable Schema Wrapping ────────────────────────────────────────────────\n\n/**\n * Wraps a JSON Schema with `null` to indicate the value can be nullish.\n *\n * - If the schema already includes `null`, it is returned as-is.\n * - For schemas with a simple `type` string, the type becomes an array\n * (e.g. `{ type: \"string\" }` → `{ type: [\"string\", \"null\"] }`).\n * - For schemas with a type array, `\"null\"` is appended.\n * - For complex schemas (oneOf, anyOf, etc.), a `oneOf` wrapper is used.\n */\nfunction withNullType(schema: JSONSchema7): JSONSchema7 {\n\tif (schema.type === \"null\") return schema;\n\n\tif (typeof schema.type === \"string\") {\n\t\treturn { ...schema, type: [schema.type, \"null\"] };\n\t}\n\n\tif (Array.isArray(schema.type)) {\n\t\tif (schema.type.includes(\"null\")) return schema;\n\t\treturn { ...schema, type: [...schema.type, \"null\"] };\n\t}\n\n\t// Complex schema (oneOf, anyOf, allOf, etc.) — wrap with oneOf\n\treturn simplifySchema({ oneOf: [schema, { type: \"null\" }] });\n}\n\n/**\n * Checks whether EVERY segment along a property path is required.\n *\n * Unlike `isPropertyRequired` (which only checks the last segment),\n * this function verifies that no intermediate segment is optional.\n * If any segment along the path is optional, the entire expression\n * can produce `null`/`undefined` at runtime.\n *\n * Intrinsic array accesses (`.length`, `.[N]`) are always considered\n * required — they are synthesized by the schema resolver and do not\n * appear in any `required` array.\n *\n * Example: for path `[\"user\", \"name\"]`, checks both that `user` is\n * required in the root schema AND that `name` is required in `user`.\n */\nfunction isPathFullyRequired(schema: JSONSchema7, segments: string[]): boolean {\n\tfor (let i = 1; i <= segments.length; i++) {\n\t\tif (!isPropertyRequired(schema, segments.slice(0, i))) {\n\t\t\t// Intrinsic array access: .length and .[N] are always available\n\t\t\t// on array schemas. They are not listed in `required` because\n\t\t\t// they are synthesized by the schema resolver, not real properties.\n\t\t\tif (i >= 2) {\n\t\t\t\tconst parentSchema = resolveSchemaPath(\n\t\t\t\t\tschema,\n\t\t\t\t\tsegments.slice(0, i - 1),\n\t\t\t\t);\n\t\t\t\tif (parentSchema && parentSchema.type === \"array\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n// ─── Utilities ───────────────────────────────────────────────────────────────\n\n/**\n * Extracts the first argument of a BlockStatement.\n *\n * In the Handlebars AST, for `{{#if active}}`:\n * - `stmt.path` → PathExpression(\"if\") ← the helper name\n * - `stmt.params[0]` → PathExpression(\"active\") ← the actual argument\n *\n * @returns The argument expression, or `undefined` if the block has no argument.\n */\n// ─── SubExpression Resolution ────────────────────────────────────────────────\n\n/**\n * Resolves a SubExpression (nested helper call) such as `(lt account.balance 500)`.\n *\n * This mirrors the helper-call logic in `processMustache` but applies to\n * expressions used as arguments (e.g. inside `{{#if (lt a b)}}`).\n *\n * Steps:\n * 1. Extract the helper name from the SubExpression's path.\n * 2. Look up the helper in `ctx.helpers`.\n * 3. Validate argument count and types.\n * 4. Return the helper's declared `returnType` (defaults to `{ type: \"string\" }`).\n */\nfunction resolveSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 | undefined {\n\tconst helperName = getExpressionName(expr.path);\n\n\t// ── Special-case: map helper ─────────────────────────────────────\n\t// The `map` helper requires deep static analysis to infer the\n\t// precise return type `{ type: \"array\", items: <property schema> }`.\n\t// The generic path would only return `{ type: \"array\" }` (the static\n\t// returnType), losing the item schema needed by nested map calls.\n\tif (helperName === MapHelpers.MAP_HELPER_NAME) {\n\t\treturn processMapSubExpression(expr, ctx, parentNode);\n\t}\n\n\t// ── Special-case: default helper ─────────────────────────────────\n\tif (helperName === DefaultHelpers.DEFAULT_HELPER_NAME) {\n\t\treturn processDefaultSubExpression(expr, ctx, parentNode);\n\t}\n\n\tconst helper = ctx.helpers?.get(helperName);\n\tif (!helper) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_HELPER\",\n\t\t\t\"warning\",\n\t\t\t`Unknown sub-expression helper \"${helperName}\" — cannot analyze statically`,\n\t\t\tparentNode ?? expr,\n\t\t\t{ helperName },\n\t\t);\n\t\treturn { type: \"string\" };\n\t}\n\n\tconst helperParams = helper.params;\n\n\t// ── Check the number of required parameters ──────────────────────\n\tif (helperParams) {\n\t\tconst requiredCount = helperParams.filter((p) => !p.optional).length;\n\t\tif (expr.params.length < requiredCount) {\n\t\t\taddDiagnostic(\n\t\t\t\tctx,\n\t\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\t\"error\",\n\t\t\t\t`Helper \"${helperName}\" expects at least ${requiredCount} argument(s), but got ${expr.params.length}`,\n\t\t\t\tparentNode ?? expr,\n\t\t\t\t{\n\t\t\t\t\thelperName,\n\t\t\t\t\texpected: `${requiredCount} argument(s)`,\n\t\t\t\t\tactual: `${expr.params.length} argument(s)`,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t// ── Validate each parameter (existence + type) ───────────────────\n\tfor (let i = 0; i < expr.params.length; i++) {\n\t\tconst resolvedSchema = resolveExpressionWithDiagnostics(\n\t\t\texpr.params[i] as hbs.AST.Expression,\n\t\t\tctx,\n\t\t\tparentNode ?? expr,\n\t\t);\n\n\t\tconst helperParam = helperParams?.[i];\n\t\tif (resolvedSchema && helperParam?.type) {\n\t\t\tconst expectedType = helperParam.type;\n\t\t\tif (!isParamTypeCompatible(resolvedSchema, expectedType)) {\n\t\t\t\tconst paramName = helperParam.name;\n\t\t\t\taddDiagnostic(\n\t\t\t\t\tctx,\n\t\t\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\t\t\"error\",\n\t\t\t\t\t`Helper \"${helperName}\" parameter \"${paramName}\" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,\n\t\t\t\t\tparentNode ?? expr,\n\t\t\t\t\t{\n\t\t\t\t\t\thelperName,\n\t\t\t\t\t\texpected: schemaTypeLabel(expectedType),\n\t\t\t\t\t\tactual: schemaTypeLabel(resolvedSchema),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn helper.returnType ?? { type: \"string\" };\n}\n\n// ─── map helper — sub-expression analysis ────────────────────────────────────\n// Mirrors processMapHelper but for SubExpression nodes (e.g.\n// `(map users 'cartItems')` used as an argument to another helper).\n// This enables nested map: `{{ map (map users 'cartItems') 'productId' }}`\n\nfunction processMapSubExpression(\n\texpr: hbs.AST.SubExpression,\n\tctx: AnalysisContext,\n\tparentNode?: hbs.AST.Node,\n): JSONSchema7 {\n\tconst helperName = MapHelpers.MAP_HELPER_NAME;\n\tconst node = parentNode ?? expr;\n\n\t// ── 1. Check argument count ──────────────────────────────────────────\n\tif (expr.params.length < 2) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"MISSING_ARGUMENT\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects at least 2 argument(s), but got ${expr.params.length}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"2 argument(s)\",\n\t\t\t\tactual: `${expr.params.length} argument(s)`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 2. Resolve the first argument (collection path) ──────────────────\n\tconst collectionExpr = expr.params[0] as hbs.AST.Expression;\n\tconst collectionSchema = resolveExpressionWithDiagnostics(\n\t\tcollectionExpr,\n\t\tctx,\n\t\tnode,\n\t);\n\n\tif (!collectionSchema) {\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 3. Validate that the collection is an array ──────────────────────\n\tconst itemSchema = resolveArrayItems(collectionSchema, ctx.root);\n\tif (!itemSchema) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"collection\" expects an array, but got ${schemaTypeLabel(collectionSchema)}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"array\",\n\t\t\t\tactual: schemaTypeLabel(collectionSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 4. Validate that the items are objects ───────────────────────────\n\t// If the items are arrays (e.g. from a nested map), flatten one level\n\t// to match the runtime `flat(1)` behavior and use the inner items instead.\n\tlet effectiveItemSchema = itemSchema;\n\tconst itemType = effectiveItemSchema.type;\n\tif (\n\t\titemType === \"array\" ||\n\t\t(Array.isArray(itemType) && itemType.includes(\"array\"))\n\t) {\n\t\tconst innerItems = resolveArrayItems(effectiveItemSchema, ctx.root);\n\t\tif (innerItems) {\n\t\t\teffectiveItemSchema = innerItems;\n\t\t}\n\t}\n\n\tconst effectiveItemType = effectiveItemSchema.type;\n\tconst isObject =\n\t\teffectiveItemType === \"object\" ||\n\t\t(Array.isArray(effectiveItemType) &&\n\t\t\teffectiveItemType.includes(\"object\")) ||\n\t\t(!effectiveItemType && effectiveItemSchema.properties !== undefined);\n\n\tif (!isObject && effectiveItemType !== undefined) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" expects an array of objects, but the array items have type \"${schemaTypeLabel(effectiveItemSchema)}\"`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: \"object\",\n\t\t\t\tactual: schemaTypeLabel(effectiveItemSchema),\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 5. Validate the second argument (property name) ──────────────────\n\tconst propertyExpr = expr.params[1] as hbs.AST.Expression;\n\tlet propertyName: string | undefined;\n\n\tif (propertyExpr.type === \"PathExpression\") {\n\t\tconst bare = (propertyExpr as hbs.AST.PathExpression).original;\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" must be a quoted string. ` +\n\t\t\t\t`Use (${helperName} … \"${bare}\") instead of (${helperName} … ${bare})`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: `PathExpression (${bare})`,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\tif (propertyExpr.type === \"StringLiteral\") {\n\t\tpropertyName = (propertyExpr as hbs.AST.StringLiteral).value;\n\t}\n\n\tif (!propertyName) {\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"TYPE_MISMATCH\",\n\t\t\t\"error\",\n\t\t\t`Helper \"${helperName}\" parameter \"property\" expects a quoted string literal, but got ${propertyExpr.type}`,\n\t\t\tnode,\n\t\t\t{\n\t\t\t\thelperName,\n\t\t\t\texpected: 'StringLiteral (e.g. \"property\")',\n\t\t\t\tactual: propertyExpr.type,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 6. Resolve the property within the item schema ───────────────────\n\tconst propertySchema = resolveSchemaPath(effectiveItemSchema, [propertyName]);\n\tif (!propertySchema) {\n\t\tconst availableProperties = getSchemaPropertyNames(effectiveItemSchema);\n\t\taddDiagnostic(\n\t\t\tctx,\n\t\t\t\"UNKNOWN_PROPERTY\",\n\t\t\t\"error\",\n\t\t\tcreatePropertyNotFoundMessage(propertyName, availableProperties),\n\t\t\tnode,\n\t\t\t{\n\t\t\t\tpath: propertyName,\n\t\t\t\tavailableProperties,\n\t\t\t},\n\t\t);\n\t\treturn { type: \"array\" };\n\t}\n\n\t// ── 7. Return the inferred output schema ─────────────────────────────\n\treturn { type: \"array\", items: propertySchema };\n}\n\nfunction getBlockArgument(\n\tstmt: hbs.AST.BlockStatement,\n): hbs.AST.Expression | undefined {\n\treturn stmt.params[0] as hbs.AST.Expression | undefined;\n}\n\n/**\n * Retrieves the helper name from a BlockStatement (e.g. \"if\", \"each\", \"with\").\n */\nfunction getBlockHelperName(stmt: hbs.AST.BlockStatement): string {\n\tif (stmt.path.type === \"PathExpression\") {\n\t\treturn (stmt.path as hbs.AST.PathExpression).original;\n\t}\n\treturn \"\";\n}\n\n/**\n * Retrieves the name of an expression (first segment of the PathExpression).\n * Used to identify inline helpers.\n */\nfunction getExpressionName(expr: hbs.AST.Expression): string {\n\tif (expr.type === \"PathExpression\") {\n\t\treturn (expr as hbs.AST.PathExpression).original;\n\t}\n\treturn \"\";\n}\n\n/**\n * Adds an enriched diagnostic to the analysis context.\n *\n * Each diagnostic includes:\n * - A machine-readable `code` for the frontend\n * - A human-readable `message` describing the problem\n * - A `source` snippet from the template (if the position is available)\n * - Structured `details` for debugging\n */\nfunction addDiagnostic(\n\tctx: AnalysisContext,\n\tcode: DiagnosticCode,\n\tseverity: \"error\" | \"warning\",\n\tmessage: string,\n\tnode?: hbs.AST.Node,\n\tdetails?: DiagnosticDetails,\n): void {\n\tconst diagnostic: TemplateDiagnostic = { severity, code, message };\n\n\t// Extract the position and source snippet if available\n\tif (node && \"loc\" in node && node.loc) {\n\t\tdiagnostic.loc = {\n\t\t\tstart: { line: node.loc.start.line, column: node.loc.start.column },\n\t\t\tend: { line: node.loc.end.line, column: node.loc.end.column },\n\t\t};\n\t\t// Extract the template fragment around the error\n\t\tdiagnostic.source = extractSourceSnippet(ctx.template, diagnostic.loc);\n\t}\n\n\tif (details) {\n\t\tdiagnostic.details = details;\n\t}\n\n\tctx.diagnostics.push(diagnostic);\n}\n\n/**\n * Returns a human-readable label for a schema's type (for error messages).\n */\nfunction schemaTypeLabel(schema: JSONSchema7): string {\n\tif (schema.type) {\n\t\treturn Array.isArray(schema.type) ? schema.type.join(\" | \") : schema.type;\n\t}\n\tif (schema.oneOf) return \"oneOf(...)\";\n\tif (schema.anyOf) return \"anyOf(...)\";\n\tif (schema.allOf) return \"allOf(...)\";\n\tif (schema.enum) return \"enum\";\n\treturn \"unknown\";\n}\n\n// ─── Export for Internal Use ─────────────────────────────────────────────────\n// `inferBlockType` is exported to allow targeted unit tests\n// on block type inference.\nexport { inferBlockType };\n"],"names":["dispatchAnalyze","createMissingArgumentMessage","createPropertyNotFoundMessage","createRootPathTraversalMessage","createTypeMismatchMessage","createUnanalyzableMessage","createUnknownHelperMessage","DefaultHelpers","MapHelpers","detectLiteralType","extractExpressionIdentifier","extractPathSegments","getEffectiveBody","getEffectivelySingleBlock","getEffectivelySingleExpression","isDataExpression","isRootPathTraversal","isRootSegments","isThisExpression","parse","findConditionalSchemaLocations","isPropertyRequired","resolveArrayItems","resolveSchemaPath","simplifySchema","deepEqual","extractSourceSnippet","getSchemaPropertyNames","coerceTextValue","text","targetType","undefined","num","Number","isNaN","isInteger","lower","toLowerCase","analyze","template","inputSchema","options","tpl","coerceSchema","ast","analyzeFromAst","identifierSchemas","child","childOptions","ctx","root","current","diagnostics","helpers","conditionalLocations","loc","addDiagnostic","keyword","schemaPath","path","id","idSchema","Object","entries","idLocations","length","valid","outputSchema","inferProgramType","hasErrors","some","d","severity","processStatement","stmt","type","processMustache","inferBlockType","params","hash","helperName","getExpressionName","MAP_HELPER_NAME","processMapHelper","DEFAULT_HELPER_NAME","processDefaultHelper","helper","get","helperParams","requiredCount","filter","p","optional","expected","actual","i","resolvedSchema","resolveExpressionWithDiagnostics","helperParam","expectedType","isParamTypeCompatible","paramName","name","schemaTypeLabel","returnType","resolved","segments","cleanSegments","identifier","targetSchema","itemSchema","isPathFullyRequired","withNullType","collectionExpr","collectionSchema","effectiveItemSchema","itemType","Array","isArray","includes","innerItems","join","effectiveItemType","isObject","properties","propertyExpr","propertyName","bare","original","value","propertySchema","availableProperties","items","analyzeDefaultArgs","processDefaultSubExpression","expr","parentNode","node","resolvedSchemas","hasGuaranteedValue","param","push","isGuaranteedExpression","firstWithType","find","s","schema","oneOf","expectedTypes","resolvedTypes","rt","et","program","effective","singleExpr","singleBlock","allContent","every","map","trim","coercedType","coercedValue","const","literalType","allBlocks","types","t","body","getBlockHelperName","arg","getBlockArgument","thenType","inverse","elseType","saved","result","innerSchema","DATA_VARIABLE_SCHEMAS","index","first","last","key","resolveDataExpression","parts","resolveSubExpression","fullPath","resolveRootWithIdentifier","resolveWithIdentifier","slice","parentSchema","processMapSubExpression","code","message","details","diagnostic","start","line","column","end","source","anyOf","allOf","enum"],"mappings":"AACA,OAASA,eAAe,KAAQ,eAAgB,AAChD,QACCC,4BAA4B,CAC5BC,6BAA6B,CAC7BC,8BAA8B,CAC9BC,yBAAyB,CACzBC,yBAAyB,CACzBC,0BAA0B,KACpB,UAAW,AAClB,QAASC,cAAc,KAAQ,8BAA+B,AAC9D,QAASC,UAAU,KAAQ,0BAA2B,AACtD,QACCC,iBAAiB,CACjBC,2BAA2B,CAC3BC,mBAAmB,CACnBC,gBAAgB,CAChBC,yBAAyB,CACzBC,8BAA8B,CAC9BC,gBAAgB,CAChBC,mBAAmB,CACnBC,cAAc,CACdC,gBAAgB,CAChBC,KAAK,KACC,UAAW,AAClB,QACCC,8BAA8B,CAC9BC,kBAAkB,CAClBC,iBAAiB,CACjBC,iBAAiB,CACjBC,cAAc,KACR,mBAAoB,AAS3B,QACCC,SAAS,CACTC,oBAAoB,CACpBC,sBAAsB,KAChB,SAAU,CA+FjB,SAASC,gBACRC,IAAY,CACZC,UAAgE,EAEhE,OAAQA,YACP,IAAK,SACL,IAAK,UAAW,CACf,GAAID,OAAS,GAAI,OAAOE,UACxB,MAAMC,IAAMC,OAAOJ,MACnB,GAAII,OAAOC,KAAK,CAACF,KAAM,OAAOD,UAC9B,GAAID,aAAe,WAAa,CAACG,OAAOE,SAAS,CAACH,KAAM,OAAOD,UAC/D,OAAOC,GACR,CACA,IAAK,UAAW,CACf,MAAMI,MAAQP,KAAKQ,WAAW,GAC9B,GAAID,QAAU,OAAQ,OAAO,KAC7B,GAAIA,QA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AAK,CAACE,MAAM,AAAC,EAClEC,IAAK,CAAEF,KAAM3D,KAAKlF,GAAG,CAAC+I,GAAG,CAACF,IAAI,CAAEC,OAAQ5D,KAAKlF,GAAG,CAAC+I,GAAG,CAACD,MAAM,AAAC,CAC7D,CAEAH,CAAAA,WAAWK,MAAM,CAAG7K,qBAAqBuB,IAAIV,QAAQ,CAAE2J,WAAW3I,GAAG,CACtE,CAEA,GAAI0I,QAAS,CACZC,WAAWD,OAAO,CAAGA,OACtB,CAEAhJ,IAAIG,WAAW,CAACyF,IAAI,CAACqD,WACtB,CAKA,SAAS3F,gBAAgB2C,MAAmB,EAC3C,GAAIA,OAAOvE,IAAI,CAAE,CAChB,OAAO0C,MAAMC,OAAO,CAAC4B,OAAOvE,IAAI,EAAIuE,OAAOvE,IAAI,CAAC8C,IAAI,CAAC,OAASyB,OAAOvE,IAAI,AAC1E,CACA,GAAIuE,OAAOC,KAAK,CAAE,MAAO,aACzB,GAAID,OAAOsD,KAAK,CAAE,MAAO,aACzB,GAAItD,OAAOuD,KAAK,CAAE,MAAO,aACzB,GAAIvD,OAAOwD,IAAI,CAAE,MAAO,OACxB,MAAO,SACR,CAKA,OAAS7H,cAAc,CAAG"}
@@ -38,6 +38,14 @@ export declare function extractPathSegments(expr: hbs.AST.Expression): string[];
38
38
  * (used inside `{{#each}}` blocks).
39
39
  */
40
40
  export declare function isThisExpression(expr: hbs.AST.Expression): boolean;
41
+ /**
42
+ * Checks whether an AST expression is a Handlebars `@data` variable
43
+ * (e.g. `@index`, `@first`, `@last`, `@key`).
44
+ *
45
+ * These variables are injected by Handlebars at runtime inside block helpers
46
+ * and are not part of the user-provided input schema.
47
+ */
48
+ export declare function isDataExpression(expr: hbs.AST.Expression): boolean;
41
49
  /**
42
50
  * Checks whether an AST expression is a `PathExpression` whose first
43
51
  * segment is the `$root` token.
@@ -1,2 +1,2 @@
1
- import Handlebars from"handlebars";import{TemplateParseError}from"./errors.js";export const ROOT_TOKEN="$root";const IDENTIFIER_RE=/^(.+):(-?\d+)$/;const NUMERIC_LITERAL_RE=/^-?\d+(\.\d+)?$/;export function parse(template){try{return Handlebars.parse(template)}catch(error){const message=error instanceof Error?error.message:String(error);const locMatch=message.match(/line\s+(\d+).*?column\s+(\d+)/i);const loc=locMatch?{line:parseInt(locMatch[1]??"0",10),column:parseInt(locMatch[2]??"0",10)}:undefined;throw new TemplateParseError(message,loc)}}export function isSingleExpression(ast){const{body}=ast;return body.length===1&&body[0]?.type==="MustacheStatement"}export function extractPathSegments(expr){if(expr.type==="PathExpression"){return expr.parts}return[]}export function isThisExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.original==="this"||path.original==="."}export function isRootExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.parts.length>0&&path.parts[0]===ROOT_TOKEN}export function isRootSegments(cleanSegments){return cleanSegments.length===1&&cleanSegments[0]===ROOT_TOKEN}export function isRootPathTraversal(cleanSegments){return cleanSegments.length>1&&cleanSegments[0]===ROOT_TOKEN}export function getEffectiveBody(program){return program.body.filter(s=>!(s.type==="ContentStatement"&&s.value.trim()===""))}export function getEffectivelySingleBlock(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="BlockStatement"){return effective[0]}return null}export function getEffectivelySingleExpression(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="MustacheStatement"){return effective[0]}return null}export function hasHandlebarsExpression(value){return value.includes("{{")}export function canUseFastPath(ast){return ast.body.every(s=>s.type==="ContentStatement"||s.type==="MustacheStatement"&&s.params.length===0&&!s.hash)}export function detectLiteralType(text){if(NUMERIC_LITERAL_RE.test(text))return"number";if(text==="true"||text==="false")return"boolean";if(text==="null")return"null";return null}export function coerceLiteral(raw){const trimmed=raw.trim();const type=detectLiteralType(trimmed);if(type==="number")return Number(trimmed);if(type==="boolean")return trimmed==="true";if(type==="null")return null;return raw}export function parseIdentifier(segment){const match=segment.match(IDENTIFIER_RE);if(match){return{key:match[1]??segment,identifier:parseInt(match[2]??"0",10)}}return{key:segment,identifier:null}}export function extractExpressionIdentifier(segments){if(segments.length===0){return{cleanSegments:[],identifier:null}}const lastSegment=segments[segments.length-1];const parsed=parseIdentifier(lastSegment);if(parsed.identifier!==null){const cleanSegments=[...segments.slice(0,-1),parsed.key];return{cleanSegments,identifier:parsed.identifier}}return{cleanSegments:segments,identifier:null}}
1
+ import Handlebars from"handlebars";import{TemplateParseError}from"./errors.js";export const ROOT_TOKEN="$root";const IDENTIFIER_RE=/^(.+):(-?\d+)$/;const NUMERIC_LITERAL_RE=/^-?\d+(\.\d+)?$/;export function parse(template){try{return Handlebars.parse(template)}catch(error){const message=error instanceof Error?error.message:String(error);const locMatch=message.match(/line\s+(\d+).*?column\s+(\d+)/i);const loc=locMatch?{line:parseInt(locMatch[1]??"0",10),column:parseInt(locMatch[2]??"0",10)}:undefined;throw new TemplateParseError(message,loc)}}export function isSingleExpression(ast){const{body}=ast;return body.length===1&&body[0]?.type==="MustacheStatement"}export function extractPathSegments(expr){if(expr.type==="PathExpression"){return expr.parts}return[]}export function isThisExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.original==="this"||path.original==="."}export function isDataExpression(expr){if(expr.type!=="PathExpression")return false;return expr.data===true}export function isRootExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.parts.length>0&&path.parts[0]===ROOT_TOKEN}export function isRootSegments(cleanSegments){return cleanSegments.length===1&&cleanSegments[0]===ROOT_TOKEN}export function isRootPathTraversal(cleanSegments){return cleanSegments.length>1&&cleanSegments[0]===ROOT_TOKEN}export function getEffectiveBody(program){return program.body.filter(s=>!(s.type==="ContentStatement"&&s.value.trim()===""))}export function getEffectivelySingleBlock(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="BlockStatement"){return effective[0]}return null}export function getEffectivelySingleExpression(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="MustacheStatement"){return effective[0]}return null}export function hasHandlebarsExpression(value){return value.includes("{{")}export function canUseFastPath(ast){return ast.body.every(s=>s.type==="ContentStatement"||s.type==="MustacheStatement"&&s.params.length===0&&!s.hash)}export function detectLiteralType(text){if(NUMERIC_LITERAL_RE.test(text))return"number";if(text==="true"||text==="false")return"boolean";if(text==="null")return"null";return null}export function coerceLiteral(raw){const trimmed=raw.trim();const type=detectLiteralType(trimmed);if(type==="number")return Number(trimmed);if(type==="boolean")return trimmed==="true";if(type==="null")return null;return raw}export function parseIdentifier(segment){const match=segment.match(IDENTIFIER_RE);if(match){return{key:match[1]??segment,identifier:parseInt(match[2]??"0",10)}}return{key:segment,identifier:null}}export function extractExpressionIdentifier(segments){if(segments.length===0){return{cleanSegments:[],identifier:null}}const lastSegment=segments[segments.length-1];const parsed=parseIdentifier(lastSegment);if(parsed.identifier!==null){const cleanSegments=[...segments.slice(0,-1),parsed.key];return{cleanSegments,identifier:parsed.identifier}}return{cleanSegments:segments,identifier:null}}
2
2
  //# sourceMappingURL=parser.js.map