typebars 1.0.3 → 1.0.5

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.
Files changed (131) hide show
  1. package/README.md +1 -2
  2. package/dist/{analyzer.d.ts → cjs/analyzer.d.ts} +1 -1
  3. package/dist/cjs/analyzer.js +2 -0
  4. package/dist/cjs/analyzer.js.map +1 -0
  5. package/dist/{compiled-template.d.ts → cjs/compiled-template.d.ts} +2 -2
  6. package/dist/cjs/compiled-template.js +2 -0
  7. package/dist/cjs/compiled-template.js.map +1 -0
  8. package/dist/{errors.d.ts → cjs/errors.d.ts} +1 -1
  9. package/dist/cjs/errors.js +3 -0
  10. package/dist/cjs/errors.js.map +1 -0
  11. package/dist/{executor.d.ts → cjs/executor.d.ts} +2 -2
  12. package/dist/cjs/executor.js +2 -0
  13. package/dist/cjs/executor.js.map +1 -0
  14. package/dist/{helpers → cjs/helpers}/helper-factory.d.ts +1 -1
  15. package/dist/cjs/helpers/helper-factory.js +2 -0
  16. package/dist/cjs/helpers/helper-factory.js.map +1 -0
  17. package/dist/cjs/helpers/index.d.ts +4 -0
  18. package/dist/cjs/helpers/index.js +2 -0
  19. package/dist/cjs/helpers/index.js.map +1 -0
  20. package/dist/{helpers → cjs/helpers}/logical-helpers.d.ts +2 -2
  21. package/dist/cjs/helpers/logical-helpers.js +2 -0
  22. package/dist/cjs/helpers/logical-helpers.js.map +1 -0
  23. package/dist/{helpers → cjs/helpers}/math-helpers.d.ts +2 -2
  24. package/dist/cjs/helpers/math-helpers.js +2 -0
  25. package/dist/cjs/helpers/math-helpers.js.map +1 -0
  26. package/dist/cjs/helpers/utils.js +2 -0
  27. package/dist/cjs/helpers/utils.js.map +1 -0
  28. package/dist/cjs/index.d.ts +3 -0
  29. package/dist/cjs/index.js +2 -0
  30. package/dist/cjs/index.js.map +1 -0
  31. package/dist/cjs/package.json +3 -0
  32. package/dist/cjs/parser.js +2 -0
  33. package/dist/cjs/parser.js.map +1 -0
  34. package/dist/cjs/schema-resolver.js +2 -0
  35. package/dist/cjs/schema-resolver.js.map +1 -0
  36. package/dist/{typebars.d.ts → cjs/typebars.d.ts} +2 -2
  37. package/dist/cjs/typebars.js +2 -0
  38. package/dist/cjs/typebars.js.map +1 -0
  39. package/dist/cjs/types.js +2 -0
  40. package/dist/cjs/types.js.map +1 -0
  41. package/dist/{utils.d.ts → cjs/utils.d.ts} +1 -1
  42. package/dist/cjs/utils.js +2 -0
  43. package/dist/cjs/utils.js.map +1 -0
  44. package/dist/esm/analyzer.d.ts +59 -0
  45. package/dist/esm/analyzer.js +2 -0
  46. package/dist/esm/analyzer.js.map +1 -0
  47. package/dist/esm/compiled-template.d.ts +130 -0
  48. package/dist/esm/compiled-template.js +2 -0
  49. package/dist/esm/compiled-template.js.map +1 -0
  50. package/dist/esm/errors.d.ts +105 -0
  51. package/dist/esm/errors.js +3 -0
  52. package/dist/esm/errors.js.map +1 -0
  53. package/dist/esm/executor.d.ts +55 -0
  54. package/dist/esm/executor.js +2 -0
  55. package/dist/esm/executor.js.map +1 -0
  56. package/dist/esm/helpers/helper-factory.d.ts +56 -0
  57. package/dist/esm/helpers/helper-factory.js +2 -0
  58. package/dist/esm/helpers/helper-factory.js.map +1 -0
  59. package/dist/esm/helpers/index.d.ts +4 -0
  60. package/dist/esm/helpers/index.js +2 -0
  61. package/dist/esm/helpers/index.js.map +1 -0
  62. package/dist/esm/helpers/logical-helpers.d.ts +15 -0
  63. package/dist/esm/helpers/logical-helpers.js +2 -0
  64. package/dist/esm/helpers/logical-helpers.js.map +1 -0
  65. package/dist/esm/helpers/math-helpers.d.ts +13 -0
  66. package/dist/esm/helpers/math-helpers.js +2 -0
  67. package/dist/esm/helpers/math-helpers.js.map +1 -0
  68. package/dist/esm/helpers/utils.d.ts +19 -0
  69. package/dist/esm/helpers/utils.js +2 -0
  70. package/dist/esm/helpers/utils.js.map +1 -0
  71. package/dist/esm/index.d.ts +3 -0
  72. package/dist/esm/index.js +2 -0
  73. package/dist/esm/index.js.map +1 -0
  74. package/dist/esm/parser.d.ts +146 -0
  75. package/dist/esm/parser.js +2 -0
  76. package/dist/esm/parser.js.map +1 -0
  77. package/dist/esm/schema-resolver.d.ts +88 -0
  78. package/dist/esm/schema-resolver.js +2 -0
  79. package/dist/esm/schema-resolver.js.map +1 -0
  80. package/dist/esm/typebars.d.ts +130 -0
  81. package/dist/esm/typebars.js +2 -0
  82. package/dist/esm/typebars.js.map +1 -0
  83. package/dist/esm/types.d.ts +334 -0
  84. package/dist/esm/types.js +2 -0
  85. package/dist/esm/types.js.map +1 -0
  86. package/dist/esm/utils.d.ts +113 -0
  87. package/dist/esm/utils.js +2 -0
  88. package/dist/esm/utils.js.map +1 -0
  89. package/package.json +29 -6
  90. package/dist/analyzer.js +0 -4
  91. package/dist/analyzer.js.map +0 -9
  92. package/dist/chunk-5znsrn10.js +0 -5
  93. package/dist/chunk-5znsrn10.js.map +0 -10
  94. package/dist/chunk-867xywnk.js +0 -5
  95. package/dist/chunk-867xywnk.js.map +0 -10
  96. package/dist/chunk-8xza8tca.js +0 -5
  97. package/dist/chunk-8xza8tca.js.map +0 -10
  98. package/dist/chunk-9jxzj2h4.js +0 -7
  99. package/dist/chunk-9jxzj2h4.js.map +0 -10
  100. package/dist/chunk-dpffacsy.js +0 -4
  101. package/dist/chunk-dpffacsy.js.map +0 -10
  102. package/dist/chunk-gayk9ew1.js +0 -7
  103. package/dist/chunk-gayk9ew1.js.map +0 -10
  104. package/dist/chunk-s96k41p3.js +0 -5
  105. package/dist/chunk-s96k41p3.js.map +0 -10
  106. package/dist/chunk-wvnn9g55.js +0 -5
  107. package/dist/chunk-wvnn9g55.js.map +0 -10
  108. package/dist/compiled-template.js +0 -4
  109. package/dist/compiled-template.js.map +0 -9
  110. package/dist/errors.js +0 -4
  111. package/dist/errors.js.map +0 -9
  112. package/dist/executor.js +0 -4
  113. package/dist/executor.js.map +0 -9
  114. package/dist/helpers/index.d.ts +0 -4
  115. package/dist/index.d.ts +0 -3
  116. package/dist/index.js +0 -4
  117. package/dist/index.js.map +0 -9
  118. package/dist/parser.js +0 -4
  119. package/dist/parser.js.map +0 -9
  120. package/dist/schema-resolver.js +0 -4
  121. package/dist/schema-resolver.js.map +0 -9
  122. package/dist/typebars.js +0 -4
  123. package/dist/typebars.js.map +0 -14
  124. package/dist/types.js +0 -4
  125. package/dist/types.js.map +0 -9
  126. package/dist/utils.js +0 -4
  127. package/dist/utils.js.map +0 -9
  128. /package/dist/{helpers → cjs/helpers}/utils.d.ts +0 -0
  129. /package/dist/{parser.d.ts → cjs/parser.d.ts} +0 -0
  130. /package/dist/{schema-resolver.d.ts → cjs/schema-resolver.d.ts} +0 -0
  131. /package/dist/{types.d.ts → cjs/types.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/analyzer.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport {\n\tcreateMissingArgumentMessage,\n\tcreatePropertyNotFoundMessage,\n\tcreateTypeMismatchMessage,\n\tcreateUnanalyzableMessage,\n\tcreateUnknownHelperMessage,\n} from \"./errors\";\nimport {\n\tdetectLiteralType,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisThisExpression,\n\tparse,\n} from \"./parser\";\nimport {\n\tassertNoConditionalSchema,\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\tTemplateInputObject,\n} from \"./types.ts\";\nimport {\n\tinferPrimitiveSchema,\n\tisLiteralInput,\n\tisObjectInput,\n} from \"./types.ts\";\nimport {\n\taggregateObjectAnalysis,\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}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\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 *\n * @param template - The template string (e.g. `\"Hello {{user.name}}\"`)\n * @param inputSchema - JSON Schema v7 describing the available variables\n * @param identifierSchemas - (optional) Schemas by identifier `{ [id]: JSONSchema7 }`\n * @returns An `AnalysisResult` containing validity, diagnostics, and the\n * inferred output schema.\n */\nexport function analyze(\n\ttemplate: TemplateInput,\n\tinputSchema: JSONSchema7,\n\tidentifierSchemas?: Record<number, JSONSchema7>,\n): AnalysisResult {\n\tif (isObjectInput(template)) {\n\t\treturn analyzeObjectTemplate(template, inputSchema, identifierSchemas);\n\t}\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tvalid: true,\n\t\t\tdiagnostics: [],\n\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t};\n\t}\n\tconst ast = parse(template);\n\treturn analyzeFromAst(ast, template, inputSchema, { identifierSchemas });\n}\n\n/**\n * Analyzes an object template recursively (standalone version).\n * Each property is analyzed individually, diagnostics are merged,\n * and the `outputSchema` reflects the object structure.\n */\nfunction analyzeObjectTemplate(\n\ttemplate: TemplateInputObject,\n\tinputSchema: JSONSchema7,\n\tidentifierSchemas?: Record<number, JSONSchema7>,\n): AnalysisResult {\n\treturn aggregateObjectAnalysis(Object.keys(template), (key) =>\n\t\tanalyze(template[key] as TemplateInput, inputSchema, identifierSchemas),\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},\n): AnalysisResult {\n\t// ── Reject unsupported schema features before analysis ────────────\n\t// Conditional schemas (if/then/else) are non-resolvable without runtime\n\t// data. Fail fast with a clear error rather than producing silently\n\t// incorrect results.\n\tassertNoConditionalSchema(inputSchema);\n\n\tif (options?.identifierSchemas) {\n\t\tfor (const [id, idSchema] of Object.entries(options.identifierSchemas)) {\n\t\t\tassertNoConditionalSchema(idSchema, `/identifierSchemas/${id}`);\n\t\t}\n\t}\n\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};\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// 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\treturn resolveExpressionWithDiagnostics(stmt.path, ctx, stmt) ?? {};\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\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, collect\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\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\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 an expression with identifier `{{key:N}}` by looking up the\n * schema associated with identifier N.\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// Resolve the path within the identifier's schema\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// ─── 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\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\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":["createMissingArgumentMessage","createPropertyNotFoundMessage","createTypeMismatchMessage","createUnanalyzableMessage","createUnknownHelperMessage","detectLiteralType","extractExpressionIdentifier","extractPathSegments","getEffectiveBody","getEffectivelySingleBlock","getEffectivelySingleExpression","isThisExpression","parse","assertNoConditionalSchema","resolveArrayItems","resolveSchemaPath","simplifySchema","inferPrimitiveSchema","isLiteralInput","isObjectInput","aggregateObjectAnalysis","deepEqual","extractSourceSnippet","getSchemaPropertyNames","analyze","template","inputSchema","identifierSchemas","analyzeObjectTemplate","valid","diagnostics","outputSchema","ast","analyzeFromAst","Object","keys","key","options","id","idSchema","entries","ctx","root","current","helpers","inferProgramType","hasErrors","some","d","severity","processStatement","stmt","type","undefined","processMustache","inferBlockType","addDiagnostic","path","params","length","hash","helperName","getExpressionName","helper","get","helperParams","requiredCount","filter","p","optional","expected","actual","i","resolvedSchema","resolveExpressionWithDiagnostics","helperParam","expectedType","isParamTypeCompatible","paramName","name","schemaTypeLabel","returnType","resolved","expectedTypes","Array","isArray","resolvedTypes","rt","et","program","effective","singleExpr","singleBlock","allContent","every","s","text","map","value","join","trim","literalType","allBlocks","types","t","push","oneOf","body","getBlockHelperName","arg","getBlockArgument","thenType","inverse","elseType","saved","collectionSchema","itemSchema","result","innerSchema","param","expr","parentNode","resolveSubExpression","segments","cleanSegments","identifier","resolveWithIdentifier","fullPath","availableProperties","node","original","code","message","details","diagnostic","loc","start","line","column","end","source","schema","anyOf","allOf","enum"],"mappings":"AACA,OACCA,4BAA4B,CAC5BC,6BAA6B,CAC7BC,yBAAyB,CACzBC,yBAAyB,CACzBC,0BAA0B,KACpB,UAAW,AAClB,QACCC,iBAAiB,CACjBC,2BAA2B,CAC3BC,mBAAmB,CACnBC,gBAAgB,CAChBC,yBAAyB,CACzBC,8BAA8B,CAC9BC,gBAAgB,CAChBC,KAAK,KACC,UAAW,AAClB,QACCC,yBAAyB,CACzBC,iBAAiB,CACjBC,iBAAiB,CACjBC,cAAc,KACR,mBAAoB,AAU3B,QACCC,oBAAoB,CACpBC,cAAc,CACdC,aAAa,KACP,YAAa,AACpB,QACCC,uBAAuB,CACvBC,SAAS,CACTC,oBAAoB,CACpBC,sBAAsB,KAChB,SAAU,AA2DjB,QAAO,SAASC,QACfC,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CAACC,KAAK,CAACC,IAAI,CAAEC,OAAQT,KAAKM,GAAG,CAACC,KAAK,CAACE,MAAM,AAAC,EAClEC,IAAK,CAAEF,KAAMR,KAAKM,GAAG,CAACI,GAAG,CAACF,IAAI,CAAEC,OAAQT,KAAKM,GAAG,CAACI,GAAG,CAACD,MAAM,AAAC,CAC7D,CAEAJ,CAAAA,WAAWM,MAAM,CAAGtH,qBAAqBmB,IAAIhB,QAAQ,CAAE6G,WAAWC,GAAG,CACtE,CAEA,GAAIF,QAAS,CACZC,WAAWD,OAAO,CAAGA,OACtB,CAEA5F,IAAIX,WAAW,CAAC2E,IAAI,CAAC6B,WACtB,CAKA,SAAStD,gBAAgB6D,MAAmB,EAC3C,GAAIA,OAAOzF,IAAI,CAAE,CAChB,OAAOgC,MAAMC,OAAO,CAACwD,OAAOzF,IAAI,EAAIyF,OAAOzF,IAAI,CAAC+C,IAAI,CAAC,OAAS0C,OAAOzF,IAAI,AAC1E,CACA,GAAIyF,OAAOnC,KAAK,CAAE,MAAO,aACzB,GAAImC,OAAOC,KAAK,CAAE,MAAO,aACzB,GAAID,OAAOE,KAAK,CAAE,MAAO,aACzB,GAAIF,OAAOG,IAAI,CAAE,MAAO,OACxB,MAAO,SACR,CAKA,OAASzF,cAAc,CAAG"}
@@ -0,0 +1,130 @@
1
+ import type Handlebars from "handlebars";
2
+ import type { JSONSchema7 } from "json-schema";
3
+ import type { AnalysisResult, ExecuteOptions, HelperDefinition, ValidationResult } from "./types.js";
4
+ import { type LRUCache } from "./utils.js";
5
+ /** Internal options passed by Typebars during compilation */
6
+ export interface CompiledTemplateOptions {
7
+ /** Custom helpers registered on the engine */
8
+ helpers: Map<string, HelperDefinition>;
9
+ /** Isolated Handlebars environment (with registered helpers) */
10
+ hbs: typeof Handlebars;
11
+ /** Compilation cache shared by the engine */
12
+ compilationCache: LRUCache<string, HandlebarsTemplateDelegate>;
13
+ }
14
+ export declare class CompiledTemplate {
15
+ /** Discriminated internal state */
16
+ private readonly state;
17
+ /** Options inherited from the parent Typebars instance */
18
+ private readonly options;
19
+ /** Compiled Handlebars template (lazy — created on the first `execute()` that needs it) */
20
+ private hbsCompiled;
21
+ /** The pre-parsed Handlebars AST — `null` in literal or object mode */
22
+ get ast(): hbs.AST.Program | null;
23
+ /** The original template source — empty string in literal or object mode */
24
+ get template(): string;
25
+ private constructor();
26
+ /**
27
+ * Creates a CompiledTemplate for a parsed Handlebars template.
28
+ *
29
+ * @param ast - The pre-parsed Handlebars AST
30
+ * @param source - The original template source
31
+ * @param options - Options inherited from Typebars
32
+ */
33
+ static fromTemplate(ast: hbs.AST.Program, source: string, options: CompiledTemplateOptions): CompiledTemplate;
34
+ /**
35
+ * Creates a CompiledTemplate in passthrough mode for a literal value
36
+ * (number, boolean, null). No parsing or compilation is performed.
37
+ *
38
+ * @param value - The primitive value
39
+ * @param options - Options inherited from Typebars
40
+ * @returns A CompiledTemplate that always returns `value`
41
+ */
42
+ static fromLiteral(value: number | boolean | null, options: CompiledTemplateOptions): CompiledTemplate;
43
+ /**
44
+ * Creates a CompiledTemplate in object mode, where each property is a
45
+ * child CompiledTemplate. All operations are recursively delegated
46
+ * to the children.
47
+ *
48
+ * @param children - The compiled child templates `{ [key]: CompiledTemplate }`
49
+ * @param options - Options inherited from Typebars
50
+ * @returns A CompiledTemplate that delegates to children
51
+ */
52
+ static fromObject(children: Record<string, CompiledTemplate>, options: CompiledTemplateOptions): CompiledTemplate;
53
+ /**
54
+ * Statically analyzes this template against a JSON Schema v7.
55
+ *
56
+ * Returns an `AnalysisResult` containing:
57
+ * - `valid` — `true` if no errors
58
+ * - `diagnostics` — list of diagnostics (errors + warnings)
59
+ * - `outputSchema` — JSON Schema describing the return type
60
+ *
61
+ * Since the AST is pre-parsed, this method never re-parses the template.
62
+ *
63
+ * @param inputSchema - JSON Schema describing the available variables
64
+ * @param identifierSchemas - (optional) Schemas by identifier `{ [id]: JSONSchema7 }`
65
+ */
66
+ analyze(inputSchema: JSONSchema7, identifierSchemas?: Record<number, JSONSchema7>): AnalysisResult;
67
+ /**
68
+ * Validates the template against a schema without returning the output type.
69
+ *
70
+ * This is an API shortcut for `analyze()` that only returns `valid` and
71
+ * `diagnostics`, without `outputSchema`. The full analysis (including type
72
+ * inference) is executed internally — this method provides no performance
73
+ * gain, only a simplified API.
74
+ *
75
+ * @param inputSchema - JSON Schema describing the available variables
76
+ * @param identifierSchemas - (optional) Schemas by identifier
77
+ */
78
+ validate(inputSchema: JSONSchema7, identifierSchemas?: Record<number, JSONSchema7>): ValidationResult;
79
+ /**
80
+ * Executes this template with the provided data.
81
+ *
82
+ * The return type depends on the template structure:
83
+ * - Single expression `{{expr}}` → raw value (number, boolean, object…)
84
+ * - Mixed template or with blocks → `string`
85
+ * - Primitive literal → the value as-is
86
+ * - Object template → object with resolved values
87
+ *
88
+ * If a `schema` is provided in options, static analysis is performed
89
+ * before execution. A `TemplateAnalysisError` is thrown on errors.
90
+ *
91
+ * @param data - The context data for rendering
92
+ * @param options - Execution options (schema, identifierData, etc.)
93
+ * @returns The execution result
94
+ */
95
+ execute(data: Record<string, unknown>, options?: ExecuteOptions): unknown;
96
+ /**
97
+ * Analyzes and executes the template in a single call.
98
+ *
99
+ * Returns both the analysis result and the executed value.
100
+ * If analysis fails, `value` is `undefined`.
101
+ *
102
+ * @param inputSchema - JSON Schema describing the available variables
103
+ * @param data - The context data for rendering
104
+ * @param options - Additional options
105
+ * @returns `{ analysis, value }`
106
+ */
107
+ analyzeAndExecute(inputSchema: JSONSchema7, data: Record<string, unknown>, options?: {
108
+ identifierSchemas?: Record<number, JSONSchema7>;
109
+ identifierData?: Record<number, Record<string, unknown>>;
110
+ }): {
111
+ analysis: AnalysisResult;
112
+ value: unknown;
113
+ };
114
+ /**
115
+ * Builds the execution context for `executeFromAst`.
116
+ *
117
+ * Uses lazy Handlebars compilation: the template is only compiled
118
+ * on the first call that needs it (not for single expressions).
119
+ */
120
+ private buildExecutorContext;
121
+ /**
122
+ * Lazily compiles the Handlebars template and caches it.
123
+ *
124
+ * Compilation happens only once — subsequent calls return the
125
+ * in-memory compiled template.
126
+ *
127
+ * Precondition: this method is only called from "template" mode.
128
+ */
129
+ private getOrCompileHbs;
130
+ }
@@ -0,0 +1,2 @@
1
+ function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}import{analyzeFromAst}from"./analyzer.js";import{TemplateAnalysisError}from"./errors.js";import{executeFromAst}from"./executor.js";import{inferPrimitiveSchema}from"./types.js";import{aggregateObjectAnalysis,aggregateObjectAnalysisAndExecution}from"./utils.js";export class CompiledTemplate{get ast(){return this.state.kind==="template"?this.state.ast:null}get template(){return this.state.kind==="template"?this.state.source:""}static fromTemplate(ast,source,options){return new CompiledTemplate({kind:"template",ast,source},options)}static fromLiteral(value,options){return new CompiledTemplate({kind:"literal",value},options)}static fromObject(children,options){return new CompiledTemplate({kind:"object",children},options)}analyze(inputSchema,identifierSchemas){switch(this.state.kind){case"object":{const{children}=this.state;return aggregateObjectAnalysis(Object.keys(children),key=>{const child=children[key];if(!child)throw new Error(`unreachable: missing child "${key}"`);return child.analyze(inputSchema,identifierSchemas)})}case"literal":return{valid:true,diagnostics:[],outputSchema:inferPrimitiveSchema(this.state.value)};case"template":return analyzeFromAst(this.state.ast,this.state.source,inputSchema,{identifierSchemas,helpers:this.options.helpers})}}validate(inputSchema,identifierSchemas){const analysis=this.analyze(inputSchema,identifierSchemas);return{valid:analysis.valid,diagnostics:analysis.diagnostics}}execute(data,options){switch(this.state.kind){case"object":{const{children}=this.state;const result={};for(const[key,child]of Object.entries(children)){result[key]=child.execute(data,options)}return result}case"literal":return this.state.value;case"template":{if(options?.schema){const analysis=this.analyze(options.schema,options.identifierSchemas);if(!analysis.valid){throw new TemplateAnalysisError(analysis.diagnostics)}}return executeFromAst(this.state.ast,this.state.source,data,this.buildExecutorContext(options))}}}analyzeAndExecute(inputSchema,data,options){switch(this.state.kind){case"object":{const{children}=this.state;return aggregateObjectAnalysisAndExecution(Object.keys(children),key=>children[key].analyzeAndExecute(inputSchema,data,options))}case"literal":return{analysis:{valid:true,diagnostics:[],outputSchema:inferPrimitiveSchema(this.state.value)},value:this.state.value};case"template":{const analysis=this.analyze(inputSchema,options?.identifierSchemas);if(!analysis.valid){return{analysis,value:undefined}}const value=executeFromAst(this.state.ast,this.state.source,data,this.buildExecutorContext({identifierData:options?.identifierData}));return{analysis,value}}}}buildExecutorContext(options){return{identifierData:options?.identifierData,compiledTemplate:this.getOrCompileHbs(),hbs:this.options.hbs,compilationCache:this.options.compilationCache}}getOrCompileHbs(){if(!this.hbsCompiled){this.hbsCompiled=this.options.hbs.compile(this.template,{noEscape:true,strict:false})}return this.hbsCompiled}constructor(state,options){_define_property(this,"state",void 0);_define_property(this,"options",void 0);_define_property(this,"hbsCompiled",null);this.state=state;this.options=options}}
2
+ //# sourceMappingURL=compiled-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/compiled-template.ts"],"sourcesContent":["import type Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { analyzeFromAst } from \"./analyzer.ts\";\nimport { TemplateAnalysisError } from \"./errors.ts\";\nimport { type ExecutorContext, executeFromAst } from \"./executor.ts\";\nimport type {\n\tAnalysisResult,\n\tExecuteOptions,\n\tHelperDefinition,\n\tValidationResult,\n} from \"./types.ts\";\nimport { inferPrimitiveSchema } from \"./types.ts\";\nimport {\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n\ttype LRUCache,\n} from \"./utils\";\n\n// ─── CompiledTemplate ────────────────────────────────────────────────────────\n// Pre-parsed template ready to be executed or analyzed without re-parsing.\n//\n// The compile-once / execute-many pattern avoids the cost of Handlebars\n// parsing on every call. The AST is parsed once at compile time, and the\n// Handlebars template is lazily compiled on the first `execute()`.\n//\n// Usage:\n// const tpl = engine.compile(\"Hello {{name}}\");\n// tpl.execute({ name: \"Alice\" }); // no re-parsing\n// tpl.execute({ name: \"Bob\" }); // no re-parsing or recompilation\n// tpl.analyze(schema); // no re-parsing\n//\n// ─── Internal State (TemplateState) ──────────────────────────────────────────\n// CompiledTemplate operates in 3 exclusive modes, modeled by a discriminated\n// union `TemplateState`:\n//\n// - `\"template\"` — parsed Handlebars template (AST + source string)\n// - `\"literal\"` — primitive passthrough value (number, boolean, null)\n// - `\"object\"` — object where each property is a child CompiledTemplate\n//\n// This design eliminates optional fields and `!` assertions in favor of\n// natural TypeScript narrowing via `switch (this.state.kind)`.\n//\n// ─── Advantages Over the Direct API ──────────────────────────────────────────\n// - **Performance**: parsing and compilation happen only once\n// - **Simplified API**: no need to re-pass the template string on each call\n// - **Consistency**: the same AST is used for both analysis and execution\n\n// ─── Internal Types ──────────────────────────────────────────────────────────\n\n/** Internal options passed by Typebars during compilation */\nexport interface CompiledTemplateOptions {\n\t/** Custom helpers registered on the engine */\n\thelpers: Map<string, HelperDefinition>;\n\t/** Isolated Handlebars environment (with registered helpers) */\n\thbs: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache: LRUCache<string, HandlebarsTemplateDelegate>;\n}\n\n/** Discriminated internal state of the CompiledTemplate */\ntype TemplateState =\n\t| {\n\t\t\treadonly kind: \"template\";\n\t\t\treadonly ast: hbs.AST.Program;\n\t\t\treadonly source: string;\n\t }\n\t| { readonly kind: \"literal\"; readonly value: number | boolean | null }\n\t| {\n\t\t\treadonly kind: \"object\";\n\t\t\treadonly children: Record<string, CompiledTemplate>;\n\t };\n\n// ─── Public Class ────────────────────────────────────────────────────────────\n\nexport class CompiledTemplate {\n\t/** Discriminated internal state */\n\tprivate readonly state: TemplateState;\n\n\t/** Options inherited from the parent Typebars instance */\n\tprivate readonly options: CompiledTemplateOptions;\n\n\t/** Compiled Handlebars template (lazy — created on the first `execute()` that needs it) */\n\tprivate hbsCompiled: HandlebarsTemplateDelegate | null = null;\n\n\t// ─── Public Accessors (backward-compatible) ──────────────────────────\n\n\t/** The pre-parsed Handlebars AST — `null` in literal or object mode */\n\tget ast(): hbs.AST.Program | null {\n\t\treturn this.state.kind === \"template\" ? this.state.ast : null;\n\t}\n\n\t/** The original template source — empty string in literal or object mode */\n\tget template(): string {\n\t\treturn this.state.kind === \"template\" ? this.state.source : \"\";\n\t}\n\n\t// ─── Construction ────────────────────────────────────────────────────\n\n\tprivate constructor(state: TemplateState, options: CompiledTemplateOptions) {\n\t\tthis.state = state;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate for a parsed Handlebars template.\n\t *\n\t * @param ast - The pre-parsed Handlebars AST\n\t * @param source - The original template source\n\t * @param options - Options inherited from Typebars\n\t */\n\tstatic fromTemplate(\n\t\tast: hbs.AST.Program,\n\t\tsource: string,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"template\", ast, source }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in passthrough mode for a literal value\n\t * (number, boolean, null). No parsing or compilation is performed.\n\t *\n\t * @param value - The primitive value\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that always returns `value`\n\t */\n\tstatic fromLiteral(\n\t\tvalue: number | boolean | null,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"literal\", value }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in object mode, where each property is a\n\t * child CompiledTemplate. All operations are recursively delegated\n\t * to the children.\n\t *\n\t * @param children - The compiled child templates `{ [key]: CompiledTemplate }`\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that delegates to children\n\t */\n\tstatic fromObject(\n\t\tchildren: Record<string, CompiledTemplate>,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"object\", children }, options);\n\t}\n\n\t// ─── Static Analysis ─────────────────────────────────────────────────\n\n\t/**\n\t * Statically analyzes this template against a JSON Schema v7.\n\t *\n\t * Returns an `AnalysisResult` containing:\n\t * - `valid` — `true` if no errors\n\t * - `diagnostics` — list of diagnostics (errors + warnings)\n\t * - `outputSchema` — JSON Schema describing the return type\n\t *\n\t * Since the AST is pre-parsed, this method never re-parses the template.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param identifierSchemas - (optional) Schemas by identifier `{ [id]: JSONSchema7 }`\n\t */\n\tanalyze(\n\t\tinputSchema: JSONSchema7,\n\t\tidentifierSchemas?: Record<number, JSONSchema7>,\n\t): AnalysisResult {\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\treturn aggregateObjectAnalysis(Object.keys(children), (key) => {\n\t\t\t\t\tconst child = children[key];\n\t\t\t\t\tif (!child) throw new Error(`unreachable: missing child \"${key}\"`);\n\t\t\t\t\treturn child.analyze(inputSchema, identifierSchemas);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tvalid: true,\n\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t};\n\n\t\t\tcase \"template\":\n\t\t\t\treturn analyzeFromAst(this.state.ast, this.state.source, inputSchema, {\n\t\t\t\t\tidentifierSchemas,\n\t\t\t\t\thelpers: this.options.helpers,\n\t\t\t\t});\n\t\t}\n\t}\n\n\t// ─── Validation ──────────────────────────────────────────────────────\n\n\t/**\n\t * Validates the template against a schema without returning the output type.\n\t *\n\t * This is an API shortcut for `analyze()` that only returns `valid` and\n\t * `diagnostics`, without `outputSchema`. The full analysis (including type\n\t * inference) is executed internally — this method provides no performance\n\t * gain, only a simplified API.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param identifierSchemas - (optional) Schemas by identifier\n\t */\n\tvalidate(\n\t\tinputSchema: JSONSchema7,\n\t\tidentifierSchemas?: Record<number, JSONSchema7>,\n\t): ValidationResult {\n\t\tconst analysis = this.analyze(inputSchema, identifierSchemas);\n\t\treturn {\n\t\t\tvalid: analysis.valid,\n\t\t\tdiagnostics: analysis.diagnostics,\n\t\t};\n\t}\n\n\t// ─── Execution ───────────────────────────────────────────────────────\n\n\t/**\n\t * Executes this template with the provided data.\n\t *\n\t * The return type depends on the template structure:\n\t * - Single expression `{{expr}}` → raw value (number, boolean, object…)\n\t * - Mixed template or with blocks → `string`\n\t * - Primitive literal → the value as-is\n\t * - Object template → object with resolved values\n\t *\n\t * If a `schema` is provided in options, static analysis is performed\n\t * before execution. A `TemplateAnalysisError` is thrown on errors.\n\t *\n\t * @param data - The context data for rendering\n\t * @param options - Execution options (schema, identifierData, etc.)\n\t * @returns The execution result\n\t */\n\texecute(data: Record<string, unknown>, options?: ExecuteOptions): unknown {\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst result: Record<string, unknown> = {};\n\t\t\t\tfor (const [key, child] of Object.entries(children)) {\n\t\t\t\t\tresult[key] = child.execute(data, options);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn this.state.value;\n\n\t\t\tcase \"template\": {\n\t\t\t\t// Pre-execution static validation if a schema is provided\n\t\t\t\tif (options?.schema) {\n\t\t\t\t\tconst analysis = this.analyze(\n\t\t\t\t\t\toptions.schema,\n\t\t\t\t\t\toptions.identifierSchemas,\n\t\t\t\t\t);\n\t\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\t\tthrow new TemplateAnalysisError(analysis.diagnostics);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn executeFromAst(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext(options),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Combined Shortcuts ──────────────────────────────────────────────\n\n\t/**\n\t * Analyzes and executes the template in a single call.\n\t *\n\t * Returns both the analysis result and the executed value.\n\t * If analysis fails, `value` is `undefined`.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param data - The context data for rendering\n\t * @param options - Additional options\n\t * @returns `{ analysis, value }`\n\t */\n\tanalyzeAndExecute(\n\t\tinputSchema: JSONSchema7,\n\t\tdata: Record<string, unknown>,\n\t\toptions?: {\n\t\t\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t\t\tidentifierData?: Record<number, Record<string, unknown>>;\n\t\t},\n\t): { analysis: AnalysisResult; value: unknown } {\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\treturn aggregateObjectAnalysisAndExecution(\n\t\t\t\t\tObject.keys(children),\n\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: key comes from Object.keys(children), access is guaranteed\n\t\t\t\t\t(key) => children[key]!.analyzeAndExecute(inputSchema, data, options),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tanalysis: {\n\t\t\t\t\t\tvalid: true,\n\t\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t\t},\n\t\t\t\t\tvalue: this.state.value,\n\t\t\t\t};\n\n\t\t\tcase \"template\": {\n\t\t\t\tconst analysis = this.analyze(inputSchema, options?.identifierSchemas);\n\n\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\treturn { analysis, value: undefined };\n\t\t\t\t}\n\n\t\t\t\tconst value = executeFromAst(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext({\n\t\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\treturn { analysis, value };\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Internals ───────────────────────────────────────────────────────\n\n\t/**\n\t * Builds the execution context for `executeFromAst`.\n\t *\n\t * Uses lazy Handlebars compilation: the template is only compiled\n\t * on the first call that needs it (not for single expressions).\n\t */\n\tprivate buildExecutorContext(options?: ExecuteOptions): ExecutorContext {\n\t\treturn {\n\t\t\tidentifierData: options?.identifierData,\n\t\t\tcompiledTemplate: this.getOrCompileHbs(),\n\t\t\thbs: this.options.hbs,\n\t\t\tcompilationCache: this.options.compilationCache,\n\t\t};\n\t}\n\n\t/**\n\t * Lazily compiles the Handlebars template and caches it.\n\t *\n\t * Compilation happens only once — subsequent calls return the\n\t * in-memory compiled template.\n\t *\n\t * Precondition: this method is only called from \"template\" mode.\n\t */\n\tprivate getOrCompileHbs(): HandlebarsTemplateDelegate {\n\t\tif (!this.hbsCompiled) {\n\t\t\t// In \"template\" mode, `this.template` returns the source string\n\t\t\tthis.hbsCompiled = this.options.hbs.compile(this.template, {\n\t\t\t\tnoEscape: true,\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t}\n\t\treturn this.hbsCompiled;\n\t}\n}\n"],"names":["analyzeFromAst","TemplateAnalysisError","executeFromAst","inferPrimitiveSchema","aggregateObjectAnalysis","aggregateObjectAnalysisAndExecution","CompiledTemplate","ast","state","kind","template","source","fromTemplate","options","fromLiteral","value","fromObject","children","analyze","inputSchema","identifierSchemas","Object","keys","key","child","Error","valid","diagnostics","outputSchema","helpers","validate","analysis","execute","data","result","entries","schema","buildExecutorContext","analyzeAndExecute","undefined","identifierData","compiledTemplate","getOrCompileHbs","hbs","compilationCache","hbsCompiled","compile","noEscape","strict"],"mappings":"oLAEA,OAASA,cAAc,KAAQ,eAAgB,AAC/C,QAASC,qBAAqB,KAAQ,aAAc,AACpD,QAA+BC,cAAc,KAAQ,eAAgB,AAOrE,QAASC,oBAAoB,KAAQ,YAAa,AAClD,QACCC,uBAAuB,CACvBC,mCAAmC,KAE7B,SAAU,AA0DjB,QAAO,MAAMC,iBAaZ,IAAIC,KAA8B,CACjC,OA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,KACb,CAAA,IAAI,CAACK,OAAO,CAAGA,OAChB,CA2QD"}
@@ -0,0 +1,105 @@
1
+ import type { TemplateDiagnostic } from "./types.js";
2
+ export declare class TemplateError extends Error {
3
+ constructor(message: string);
4
+ /**
5
+ * Serializes the error into a JSON-compatible object, suitable for sending
6
+ * to a frontend or a structured logging system.
7
+ */
8
+ toJSON(): Record<string, unknown>;
9
+ }
10
+ export declare class TemplateParseError extends TemplateError {
11
+ /** Approximate position of the error in the source */
12
+ readonly loc?: {
13
+ line: number;
14
+ column: number;
15
+ } | undefined;
16
+ /** Fragment of the template source around the error */
17
+ readonly source?: string | undefined;
18
+ constructor(message: string,
19
+ /** Approximate position of the error in the source */
20
+ loc?: {
21
+ line: number;
22
+ column: number;
23
+ } | undefined,
24
+ /** Fragment of the template source around the error */
25
+ source?: string | undefined);
26
+ toJSON(): Record<string, unknown>;
27
+ }
28
+ export declare class TemplateAnalysisError extends TemplateError {
29
+ /** Full list of diagnostics (errors + warnings) */
30
+ readonly diagnostics: TemplateDiagnostic[];
31
+ /** Only diagnostics with "error" severity */
32
+ readonly errors: TemplateDiagnostic[];
33
+ /** Only diagnostics with "warning" severity */
34
+ readonly warnings: TemplateDiagnostic[];
35
+ /** Total number of errors */
36
+ readonly errorCount: number;
37
+ /** Total number of warnings */
38
+ readonly warningCount: number;
39
+ constructor(diagnostics: TemplateDiagnostic[]);
40
+ /**
41
+ * Serializes the analysis error into a JSON-compatible object.
42
+ *
43
+ * Designed for direct use in API responses:
44
+ * ```
45
+ * res.status(400).json(error.toJSON());
46
+ * ```
47
+ *
48
+ * Returned structure:
49
+ * ```
50
+ * {
51
+ * name: "TemplateAnalysisError",
52
+ * message: "Static analysis failed with 2 error(s): ...",
53
+ * errorCount: 2,
54
+ * warningCount: 0,
55
+ * diagnostics: [
56
+ * {
57
+ * severity: "error",
58
+ * code: "UNKNOWN_PROPERTY",
59
+ * message: "Property \"foo\" does not exist...",
60
+ * loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 7 } },
61
+ * source: "{{foo}}",
62
+ * details: { path: "foo", availableProperties: ["name", "age"] }
63
+ * }
64
+ * ]
65
+ * }
66
+ * ```
67
+ */
68
+ toJSON(): Record<string, unknown>;
69
+ }
70
+ export declare class TemplateRuntimeError extends TemplateError {
71
+ constructor(message: string);
72
+ }
73
+ export declare class UnsupportedSchemaError extends TemplateError {
74
+ /** The unsupported keyword(s) detected (e.g. `"if/then/else"`) */
75
+ readonly keyword: string;
76
+ /** JSON pointer path to the location in the schema (e.g. `"/properties/user"`) */
77
+ readonly schemaPath: string;
78
+ constructor(
79
+ /** The unsupported keyword(s) detected (e.g. `"if/then/else"`) */
80
+ keyword: string,
81
+ /** JSON pointer path to the location in the schema (e.g. `"/properties/user"`) */
82
+ schemaPath: string);
83
+ toJSON(): Record<string, unknown>;
84
+ }
85
+ /**
86
+ * Creates a structured diagnostic message for a missing property.
87
+ * Used by the analyzer to produce enriched error messages with suggestions.
88
+ */
89
+ export declare function createPropertyNotFoundMessage(path: string, availableProperties: string[]): string;
90
+ /**
91
+ * Creates a message for a type mismatch on a block helper.
92
+ */
93
+ export declare function createTypeMismatchMessage(helperName: string, expected: string, actual: string): string;
94
+ /**
95
+ * Creates a message for a missing argument on a block helper.
96
+ */
97
+ export declare function createMissingArgumentMessage(helperName: string): string;
98
+ /**
99
+ * Creates a message for an unknown block helper.
100
+ */
101
+ export declare function createUnknownHelperMessage(helperName: string): string;
102
+ /**
103
+ * Creates a message for an expression that cannot be statically analyzed.
104
+ */
105
+ export declare function createUnanalyzableMessage(nodeType: string): string;
@@ -0,0 +1,3 @@
1
+ function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}export class TemplateError extends Error{toJSON(){return{name:this.name,message:this.message}}constructor(message){super(message);this.name="TemplateError"}}export class TemplateParseError extends TemplateError{toJSON(){return{name:this.name,message:this.message,loc:this.loc,source:this.source}}constructor(message,loc,source){super(`Parse error: ${message}`),_define_property(this,"loc",void 0),_define_property(this,"source",void 0),this.loc=loc,this.source=source;this.name="TemplateParseError"}}export class TemplateAnalysisError extends TemplateError{toJSON(){return{name:this.name,message:this.message,errorCount:this.errorCount,warningCount:this.warningCount,diagnostics:this.diagnostics}}constructor(diagnostics){const errors=diagnostics.filter(d=>d.severity==="error");const warnings=diagnostics.filter(d=>d.severity==="warning");const summary=errors.map(d=>formatDiagnosticLine(d)).join("\n");super(`Static analysis failed with ${errors.length} error(s):
2
+ ${summary}`),_define_property(this,"diagnostics",void 0),_define_property(this,"errors",void 0),_define_property(this,"warnings",void 0),_define_property(this,"errorCount",void 0),_define_property(this,"warningCount",void 0);this.name="TemplateAnalysisError";this.diagnostics=diagnostics;this.errors=errors;this.warnings=warnings;this.errorCount=errors.length;this.warningCount=warnings.length}}export class TemplateRuntimeError extends TemplateError{constructor(message){super(`Runtime error: ${message}`);this.name="TemplateRuntimeError"}}export class UnsupportedSchemaError extends TemplateError{toJSON(){return{name:this.name,message:this.message,keyword:this.keyword,schemaPath:this.schemaPath}}constructor(keyword,schemaPath){super(`Unsupported JSON Schema feature: "${keyword}" at "${schemaPath}". `+"Conditional schemas (if/then/else) cannot be resolved during static analysis "+"because they depend on runtime data. Consider using oneOf/anyOf combinators instead."),_define_property(this,"keyword",void 0),_define_property(this,"schemaPath",void 0),this.keyword=keyword,this.schemaPath=schemaPath;this.name="UnsupportedSchemaError"}}function formatDiagnosticLine(diag){const parts=[` • [${diag.code}] ${diag.message}`];if(diag.loc){parts.push(`(at ${diag.loc.start.line}:${diag.loc.start.column})`)}return parts.join(" ")}export function createPropertyNotFoundMessage(path,availableProperties){const base=`Property "${path}" does not exist in the context schema`;if(availableProperties.length===0)return base;return`${base}. Available properties: ${availableProperties.join(", ")}`}export function createTypeMismatchMessage(helperName,expected,actual){return`"{{#${helperName}}}" expects ${expected}, but resolved schema has type "${actual}"`}export function createMissingArgumentMessage(helperName){return`"{{#${helperName}}}" requires an argument`}export function createUnknownHelperMessage(helperName){return`Unknown block helper "{{#${helperName}}}" — cannot analyze statically`}export function createUnanalyzableMessage(nodeType){return`Expression of type "${nodeType}" cannot be statically analyzed`}
3
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import type { TemplateDiagnostic } from \"./types.ts\";\n\n// ─── Base Class ──────────────────────────────────────────────────────────────\n// All template engine errors extend this class, enabling targeted catch blocks:\n// `catch (e) { if (e instanceof TemplateError) … }`\n// Subclasses:\n// - `TemplateParseError` — invalid template syntax\n// - `TemplateAnalysisError` — static analysis failures (diagnostics)\n// - `TemplateRuntimeError` — execution failures\n// - `UnsupportedSchemaError` — schema uses unsupported JSON Schema features\n\nexport class TemplateError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"TemplateError\";\n\t}\n\n\t/**\n\t * Serializes the error into a JSON-compatible object, suitable for sending\n\t * to a frontend or a structured logging system.\n\t */\n\ttoJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t};\n\t}\n}\n\n// ─── Parse Error ─────────────────────────────────────────────────────────────\n// Thrown when Handlebars fails to parse the template (invalid syntax).\n\nexport class TemplateParseError extends TemplateError {\n\tconstructor(\n\t\tmessage: string,\n\t\t/** Approximate position of the error in the source */\n\t\tpublic readonly loc?: { line: number; column: number },\n\t\t/** Fragment of the template source around the error */\n\t\tpublic readonly source?: string,\n\t) {\n\t\tsuper(`Parse error: ${message}`);\n\t\tthis.name = \"TemplateParseError\";\n\t}\n\n\toverride toJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tloc: this.loc,\n\t\t\tsource: this.source,\n\t\t};\n\t}\n}\n\n// ─── Static Analysis Error ───────────────────────────────────────────────────\n// Thrown in strict mode when the analysis produces at least one error.\n// Contains the full list of diagnostics for detailed inspection.\n\nexport class TemplateAnalysisError extends TemplateError {\n\t/** Full list of diagnostics (errors + warnings) */\n\tpublic readonly diagnostics: TemplateDiagnostic[];\n\n\t/** Only diagnostics with \"error\" severity */\n\tpublic readonly errors: TemplateDiagnostic[];\n\n\t/** Only diagnostics with \"warning\" severity */\n\tpublic readonly warnings: TemplateDiagnostic[];\n\n\t/** Total number of errors */\n\tpublic readonly errorCount: number;\n\n\t/** Total number of warnings */\n\tpublic readonly warningCount: number;\n\n\tconstructor(diagnostics: TemplateDiagnostic[]) {\n\t\tconst errors = diagnostics.filter((d) => d.severity === \"error\");\n\t\tconst warnings = diagnostics.filter((d) => d.severity === \"warning\");\n\n\t\tconst summary = errors.map((d) => formatDiagnosticLine(d)).join(\"\\n\");\n\t\tsuper(`Static analysis failed with ${errors.length} error(s):\\n${summary}`);\n\n\t\tthis.name = \"TemplateAnalysisError\";\n\t\tthis.diagnostics = diagnostics;\n\t\tthis.errors = errors;\n\t\tthis.warnings = warnings;\n\t\tthis.errorCount = errors.length;\n\t\tthis.warningCount = warnings.length;\n\t}\n\n\t/**\n\t * Serializes the analysis error into a JSON-compatible object.\n\t *\n\t * Designed for direct use in API responses:\n\t * ```\n\t * res.status(400).json(error.toJSON());\n\t * ```\n\t *\n\t * Returned structure:\n\t * ```\n\t * {\n\t * name: \"TemplateAnalysisError\",\n\t * message: \"Static analysis failed with 2 error(s): ...\",\n\t * errorCount: 2,\n\t * warningCount: 0,\n\t * diagnostics: [\n\t * {\n\t * severity: \"error\",\n\t * code: \"UNKNOWN_PROPERTY\",\n\t * message: \"Property \\\"foo\\\" does not exist...\",\n\t * loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 7 } },\n\t * source: \"{{foo}}\",\n\t * details: { path: \"foo\", availableProperties: [\"name\", \"age\"] }\n\t * }\n\t * ]\n\t * }\n\t * ```\n\t */\n\toverride toJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\terrorCount: this.errorCount,\n\t\t\twarningCount: this.warningCount,\n\t\t\tdiagnostics: this.diagnostics,\n\t\t};\n\t}\n}\n\n// ─── Runtime Error ───────────────────────────────────────────────────────────\n// Thrown when template execution fails (accessing a non-existent property\n// in strict mode, unexpected type, etc.).\n\nexport class TemplateRuntimeError extends TemplateError {\n\tconstructor(message: string) {\n\t\tsuper(`Runtime error: ${message}`);\n\t\tthis.name = \"TemplateRuntimeError\";\n\t}\n}\n\n// ─── Unsupported Schema Error ────────────────────────────────────────────────\n// Thrown when the provided JSON Schema uses features that cannot be handled\n// by static analysis (e.g. `if/then/else` conditional schemas).\n//\n// These features are data-dependent and fundamentally non-resolvable without\n// runtime values. Rather than silently ignoring them (which would produce\n// incorrect analysis results), we fail fast with a clear error message.\n\nexport class UnsupportedSchemaError extends TemplateError {\n\tconstructor(\n\t\t/** The unsupported keyword(s) detected (e.g. `\"if/then/else\"`) */\n\t\tpublic readonly keyword: string,\n\t\t/** JSON pointer path to the location in the schema (e.g. `\"/properties/user\"`) */\n\t\tpublic readonly schemaPath: string,\n\t) {\n\t\tsuper(\n\t\t\t`Unsupported JSON Schema feature: \"${keyword}\" at \"${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);\n\t\tthis.name = \"UnsupportedSchemaError\";\n\t}\n\n\toverride toJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tkeyword: this.keyword,\n\t\t\tschemaPath: this.schemaPath,\n\t\t};\n\t}\n}\n\n// ─── Internal Utilities ──────────────────────────────────────────────────────\n\n/**\n * Formats a single diagnostic line for the summary message\n * of a `TemplateAnalysisError`.\n *\n * Produces a human-readable format:\n * ` • [UNKNOWN_PROPERTY] Property \"foo\" does not exist (at 1:0)`\n */\nfunction formatDiagnosticLine(diag: TemplateDiagnostic): string {\n\tconst parts: string[] = [` • [${diag.code}] ${diag.message}`];\n\n\tif (diag.loc) {\n\t\tparts.push(`(at ${diag.loc.start.line}:${diag.loc.start.column})`);\n\t}\n\n\treturn parts.join(\" \");\n}\n\n// ─── Common Error Factories ──────────────────────────────────────────────────\n// These functions simplify the creation of typed errors across the codebase.\n\n/**\n * Creates a structured diagnostic message for a missing property.\n * Used by the analyzer to produce enriched error messages with suggestions.\n */\nexport function createPropertyNotFoundMessage(\n\tpath: string,\n\tavailableProperties: string[],\n): string {\n\tconst base = `Property \"${path}\" does not exist in the context schema`;\n\tif (availableProperties.length === 0) return base;\n\treturn `${base}. Available properties: ${availableProperties.join(\", \")}`;\n}\n\n/**\n * Creates a message for a type mismatch on a block helper.\n */\nexport function createTypeMismatchMessage(\n\thelperName: string,\n\texpected: string,\n\tactual: string,\n): string {\n\treturn `\"{{#${helperName}}}\" expects ${expected}, but resolved schema has type \"${actual}\"`;\n}\n\n/**\n * Creates a message for a missing argument on a block helper.\n */\nexport function createMissingArgumentMessage(helperName: string): string {\n\treturn `\"{{#${helperName}}}\" requires an argument`;\n}\n\n/**\n * Creates a message for an unknown block helper.\n */\nexport function createUnknownHelperMessage(helperName: string): string {\n\treturn `Unknown block helper \"{{#${helperName}}}\" — cannot analyze statically`;\n}\n\n/**\n * Creates a message for an expression that cannot be statically analyzed.\n */\nexport function createUnanalyzableMessage(nodeType: string): string {\n\treturn `Expression of type \"${nodeType}\" cannot be statically analyzed`;\n}\n"],"names":["TemplateError","Error","toJSON","name","message","TemplateParseError","loc","source","TemplateAnalysisError","errorCount","warningCount","diagnostics","errors","filter","d","severity","warnings","summary","map","formatDiagnosticLine","join","length","TemplateRuntimeError","UnsupportedSchemaError","keyword","schemaPath","diag","parts","code","push","start","line","column","createPropertyNotFoundMessage","path","availableProperties","base","createTypeMismatchMessage","helperName","expected","actual","createMissingArgumentMessage","createUnknownHelperMessage","createUnanalyzableMessage","nodeType"],"mappings":"oLAWA,OAAO,MAAMA,sBAAsBC,MAUlCC,QAAkC,CACjC,MAAO,CACNC,KAA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L,MAAMP,IAAI,CAAC,IACnB,CASA,OAAO,SAASa,8BACfC,IAAY,CACZC,mBAA6B,EAE7B,MAAMC,KAAO,CAAC,UAAU,EAAEF,KAAK,sCAAsC,CAAC,CACtE,GAAIC,oBAAoBd,MAAM,GAAK,EAAG,OAAOe,KAC7C,MAAO,CAAC,EAAEA,KAAK,wBAAwB,EAAED,oBAAoBf,IAAI,CAAC,MAAM,CAAC,AAC1E,CAKA,OAAO,SAASiB,0BACfC,UAAkB,CAClBC,QAAgB,CAChBC,MAAc,EAEd,MAAO,CAAC,IAAI,EAAEF,WAAW,YAAY,EAAEC,SAAS,gCAAgC,EAAEC,OAAO,CAAC,CAAC,AAC5F,CAKA,OAAO,SAASC,6BAA6BH,UAAkB,EAC9D,MAAO,CAAC,IAAI,EAAEA,WAAW,wBAAwB,CAAC,AACnD,CAKA,OAAO,SAASI,2BAA2BJ,UAAkB,EAC5D,MAAO,CAAC,yBAAyB,EAAEA,WAAW,+BAA+B,CAAC,AAC/E,CAKA,OAAO,SAASK,0BAA0BC,QAAgB,EACzD,MAAO,CAAC,oBAAoB,EAAEA,SAAS,+BAA+B,CAAC,AACxE"}
@@ -0,0 +1,55 @@
1
+ import Handlebars from "handlebars";
2
+ import type { TemplateInput } from "./types.js";
3
+ import { LRUCache } from "./utils.js";
4
+ /** Optional context for execution (used by Typebars/CompiledTemplate) */
5
+ export interface ExecutorContext {
6
+ /** Data by identifier `{ [id]: { key: value } }` */
7
+ identifierData?: Record<number, Record<string, unknown>>;
8
+ /** Pre-compiled Handlebars template (for CompiledTemplate) */
9
+ compiledTemplate?: HandlebarsTemplateDelegate;
10
+ /** Isolated Handlebars environment (for custom helpers) */
11
+ hbs?: typeof Handlebars;
12
+ /** Compilation cache shared by the engine */
13
+ compilationCache?: LRUCache<string, HandlebarsTemplateDelegate>;
14
+ }
15
+ /**
16
+ * Executes a template with the provided data and returns the result.
17
+ *
18
+ * The return type depends on the template structure:
19
+ * - Single expression `{{expr}}` → raw value (any)
20
+ * - Single block → coerced value (number, boolean, null, or string)
21
+ * - Mixed template → `string`
22
+ *
23
+ * @param template - The template string
24
+ * @param data - The main context data
25
+ * @param identifierData - (optional) Data by identifier `{ [id]: { key: value } }`
26
+ */
27
+ export declare function execute(template: TemplateInput, data: Record<string, unknown>, identifierData?: Record<number, Record<string, unknown>>): unknown;
28
+ /**
29
+ * Executes a template from an already-parsed AST.
30
+ *
31
+ * This function is the core of execution. It is used by:
32
+ * - `execute()` (backward-compatible wrapper)
33
+ * - `CompiledTemplate.execute()` (with pre-parsed AST and cache)
34
+ * - `Typebars.execute()` (with cache and helpers)
35
+ *
36
+ * @param ast - The already-parsed Handlebars AST
37
+ * @param template - The template source (for Handlebars compilation if needed)
38
+ * @param data - The main context data
39
+ * @param ctx - Optional execution context
40
+ */
41
+ export declare function executeFromAst(ast: hbs.AST.Program, template: string, data: Record<string, unknown>, ctx?: ExecutorContext): unknown;
42
+ /**
43
+ * Navigates through a data object by following a path of segments.
44
+ *
45
+ * @param data - The data object
46
+ * @param segments - The path segments (e.g. `["user", "address", "city"]`)
47
+ * @returns The value at the end of the path, or `undefined` if an
48
+ * intermediate segment is null/undefined
49
+ */
50
+ export declare function resolveDataPath(data: unknown, segments: string[]): unknown;
51
+ /**
52
+ * Clears the global Handlebars compilation cache.
53
+ * Useful for tests or to free memory.
54
+ */
55
+ export declare function clearCompilationCache(): void;
@@ -0,0 +1,2 @@
1
+ import Handlebars from"handlebars";import{TemplateRuntimeError}from"./errors.js";import{canUseFastPath,coerceLiteral,extractExpressionIdentifier,extractPathSegments,getEffectivelySingleBlock,getEffectivelySingleExpression,isSingleExpression,isThisExpression,parse}from"./parser.js";import{isLiteralInput,isObjectInput}from"./types.js";import{LRUCache}from"./utils.js";const globalCompilationCache=new LRUCache(128);export function execute(template,data,identifierData){if(isObjectInput(template)){return executeObjectTemplate(template,data,identifierData)}if(isLiteralInput(template))return template;const ast=parse(template);return executeFromAst(ast,template,data,{identifierData})}function executeObjectTemplate(template,data,identifierData){const result={};for(const[key,value]of Object.entries(template)){result[key]=execute(value,data,identifierData)}return result}export function executeFromAst(ast,template,data,ctx){const identifierData=ctx?.identifierData;if(isSingleExpression(ast)){const stmt=ast.body[0];if(stmt.params.length===0&&!stmt.hash){return resolveExpression(stmt.path,data,identifierData)}}const singleExpr=getEffectivelySingleExpression(ast);if(singleExpr&&singleExpr.params.length===0&&!singleExpr.hash){return resolveExpression(singleExpr.path,data,identifierData)}if(singleExpr&&(singleExpr.params.length>0||singleExpr.hash)){const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceLiteral(raw)}if(canUseFastPath(ast)&&ast.body.length>1){return executeFastPath(ast,data,identifierData)}const singleBlock=getEffectivelySingleBlock(ast);if(singleBlock){const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceLiteral(raw)}const merged=mergeDataWithIdentifiers(data,identifierData);return renderWithHandlebars(template,merged,ctx)}function executeFastPath(ast,data,identifierData){let result="";for(const stmt of ast.body){if(stmt.type==="ContentStatement"){result+=stmt.value}else if(stmt.type==="MustacheStatement"){const value=resolveExpression(stmt.path,data,identifierData);if(value!=null){result+=String(value)}}}return result}function resolveExpression(expr,data,identifierData){if(isThisExpression(expr)){return data}if(expr.type==="StringLiteral")return expr.value;if(expr.type==="NumberLiteral")return expr.value;if(expr.type==="BooleanLiteral")return expr.value;if(expr.type==="NullLiteral")return null;if(expr.type==="UndefinedLiteral")return undefined;const segments=extractPathSegments(expr);if(segments.length===0){throw new TemplateRuntimeError(`Cannot resolve expression of type "${expr.type}"`)}const{cleanSegments,identifier}=extractExpressionIdentifier(segments);if(identifier!==null&&identifierData){const source=identifierData[identifier];if(source){return resolveDataPath(source,cleanSegments)}return undefined}if(identifier!==null&&!identifierData){return undefined}return resolveDataPath(data,cleanSegments)}export function resolveDataPath(data,segments){let current=data;for(const segment of segments){if(current===null||current===undefined){return undefined}if(typeof current!=="object"){return undefined}current=current[segment]}return current}function mergeDataWithIdentifiers(data,identifierData){if(!identifierData)return data;const merged={...data};for(const[id,idData]of Object.entries(identifierData)){for(const[key,value]of Object.entries(idData)){merged[`${key}:${id}`]=value}}return merged}function renderWithHandlebars(template,data,ctx){try{if(ctx?.compiledTemplate){return ctx.compiledTemplate(data)}const cache=ctx?.compilationCache??globalCompilationCache;const hbs=ctx?.hbs??Handlebars;let compiled=cache.get(template);if(!compiled){compiled=hbs.compile(template,{noEscape:true,strict:false});cache.set(template,compiled)}return compiled(data)}catch(error){const message=error instanceof Error?error.message:String(error);throw new TemplateRuntimeError(message)}}export function clearCompilationCache(){globalCompilationCache.clear()}
2
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/executor.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport { TemplateRuntimeError } from \"./errors.ts\";\nimport {\n\tcanUseFastPath,\n\tcoerceLiteral,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisSingleExpression,\n\tisThisExpression,\n\tparse,\n} from \"./parser.ts\";\nimport type { TemplateInput, TemplateInputObject } from \"./types.ts\";\nimport { isLiteralInput, isObjectInput } from \"./types.ts\";\nimport { LRUCache } from \"./utils.ts\";\n\n// ─── Template Executor ───────────────────────────────────────────────────────\n// Executes a Handlebars template with real data.\n//\n// Four execution modes (from fastest to most general):\n//\n// 1. **Single expression** (`{{value}}` or ` {{value}} `) → returns the raw\n// value without converting to string. This preserves the original type\n// (number, boolean, object, array, null).\n//\n// 2. **Fast-path** (text + simple expressions, no blocks or helpers) →\n// direct concatenation without going through Handlebars.compile(). Up to\n// 10-100x faster for simple templates like `Hello {{name}}`.\n//\n// 3. **Single block** (`{{#if x}}10{{else}}20{{/if}}` possibly surrounded\n// by whitespace) → rendered via Handlebars then intelligently coerced\n// (detecting number, boolean, null literals).\n//\n// 4. **Mixed template** (text + multiple blocks, helpers, …) →\n// delegates to Handlebars which always produces a string.\n//\n// ─── Caching ─────────────────────────────────────────────────────────────────\n// Handlebars-compiled templates are cached in an LRU cache to avoid costly\n// recompilation on repeated calls.\n//\n// Two cache levels:\n// - **Global cache** (module-level) for standalone `execute()` calls\n// - **Instance cache** for `Typebars` (passed via `ExecutorContext`)\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows resolving a variable from a specific data\n// source, identified by an integer N. The optional `identifierData` parameter\n// provides a mapping `{ [id]: { key: value, ... } }`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Optional context for execution (used by Typebars/CompiledTemplate) */\nexport interface ExecutorContext {\n\t/** Data by identifier `{ [id]: { key: value } }` */\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\t/** Pre-compiled Handlebars template (for CompiledTemplate) */\n\tcompiledTemplate?: HandlebarsTemplateDelegate;\n\t/** Isolated Handlebars environment (for custom helpers) */\n\thbs?: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache?: LRUCache<string, HandlebarsTemplateDelegate>;\n}\n\n// ─── Global Compilation Cache ────────────────────────────────────────────────\n// Used by the standalone `execute()` function and `renderWithHandlebars()`.\n// `Typebars` instances use their own cache.\nconst globalCompilationCache = new LRUCache<string, HandlebarsTemplateDelegate>(\n\t128,\n);\n\n// ─── Public API (backward-compatible) ────────────────────────────────────────\n\n/**\n * Executes a template with the provided data and returns the result.\n *\n * The return type depends on the template structure:\n * - Single expression `{{expr}}` → raw value (any)\n * - Single block → coerced value (number, boolean, null, or string)\n * - Mixed template → `string`\n *\n * @param template - The template string\n * @param data - The main context data\n * @param identifierData - (optional) Data by identifier `{ [id]: { key: value } }`\n */\nexport function execute(\n\ttemplate: TemplateInput,\n\tdata: Record<string, unknown>,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): unknown {\n\tif (isObjectInput(template)) {\n\t\treturn executeObjectTemplate(template, data, identifierData);\n\t}\n\tif (isLiteralInput(template)) return template;\n\tconst ast = parse(template);\n\treturn executeFromAst(ast, template, data, { identifierData });\n}\n\n/**\n * Executes an object template recursively (standalone version).\n * Each property is executed individually and the result is an object\n * with the same structure but resolved values.\n */\nfunction executeObjectTemplate(\n\ttemplate: TemplateInputObject,\n\tdata: Record<string, unknown>,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(template)) {\n\t\tresult[key] = execute(value, data, identifierData);\n\t}\n\treturn result;\n}\n\n// ─── Internal API (for Typebars / CompiledTemplate) ──────────────────────\n\n/**\n * Executes a template from an already-parsed AST.\n *\n * This function is the core of execution. It is used by:\n * - `execute()` (backward-compatible wrapper)\n * - `CompiledTemplate.execute()` (with pre-parsed AST and cache)\n * - `Typebars.execute()` (with cache and helpers)\n *\n * @param ast - The already-parsed Handlebars AST\n * @param template - The template source (for Handlebars compilation if needed)\n * @param data - The main context data\n * @param ctx - Optional execution context\n */\nexport function executeFromAst(\n\tast: hbs.AST.Program,\n\ttemplate: string,\n\tdata: Record<string, unknown>,\n\tctx?: ExecutorContext,\n): unknown {\n\tconst identifierData = ctx?.identifierData;\n\n\t// ── Case 1: strict single expression `{{expr}}` ──────────────────────\n\t// Exclude helper calls (params > 0 or hash) because they must go\n\t// through Handlebars for correct execution.\n\tif (isSingleExpression(ast)) {\n\t\tconst stmt = ast.body[0] as hbs.AST.MustacheStatement;\n\t\tif (stmt.params.length === 0 && !stmt.hash) {\n\t\t\treturn resolveExpression(stmt.path, data, identifierData);\n\t\t}\n\t}\n\n\t// ── Case 1b: single expression with surrounding whitespace ` {{expr}} `\n\tconst singleExpr = getEffectivelySingleExpression(ast);\n\tif (singleExpr && singleExpr.params.length === 0 && !singleExpr.hash) {\n\t\treturn resolveExpression(singleExpr.path, data, identifierData);\n\t}\n\n\t// ── Case 1c: single expression with helper (params > 0) ──────────────\n\t// E.g. `{{ divide accountIds.length 10 }}` or `{{ math a \"+\" b }}`\n\t// The helper returns a typed value but Handlebars converts it to a\n\t// string. We render via Handlebars then coerce the result to recover\n\t// the original type (number, boolean, null).\n\tif (singleExpr && (singleExpr.params.length > 0 || singleExpr.hash)) {\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceLiteral(raw);\n\t}\n\n\t// ── Case 2: fast-path for simple templates (text + expressions) ──────\n\t// If the template only contains text and simple expressions (no blocks,\n\t// no helpers with parameters), we can do direct concatenation without\n\t// going through Handlebars.compile().\n\tif (canUseFastPath(ast) && ast.body.length > 1) {\n\t\treturn executeFastPath(ast, data, identifierData);\n\t}\n\n\t// ── Case 3: single block (possibly surrounded by whitespace) ─────────\n\t// Render via Handlebars then attempt to coerce the result to the\n\t// detected literal type (number, boolean, null).\n\tconst singleBlock = getEffectivelySingleBlock(ast);\n\tif (singleBlock) {\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceLiteral(raw);\n\t}\n\n\t// ── Case 4: mixed template → string ──────────────────────────────────\n\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\treturn renderWithHandlebars(template, merged, ctx);\n}\n\n// ─── Fast-Path Execution ─────────────────────────────────────────────────────\n// For templates consisting only of text and simple expressions (no blocks,\n// no helpers), we bypass Handlebars and do direct concatenation.\n// This is significantly faster.\n\n/**\n * Executes a template via the fast-path (direct concatenation).\n *\n * Precondition: `canUseFastPath(ast)` must return `true`.\n *\n * @param ast - The template AST (only ContentStatement and simple MustacheStatement)\n * @param data - The context data\n * @param identifierData - Data by identifier (optional)\n * @returns The resulting string\n */\nfunction executeFastPath(\n\tast: hbs.AST.Program,\n\tdata: Record<string, unknown>,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): string {\n\tlet result = \"\";\n\n\tfor (const stmt of ast.body) {\n\t\tif (stmt.type === \"ContentStatement\") {\n\t\t\tresult += (stmt as hbs.AST.ContentStatement).value;\n\t\t} else if (stmt.type === \"MustacheStatement\") {\n\t\t\tconst value = resolveExpression(\n\t\t\t\t(stmt as hbs.AST.MustacheStatement).path,\n\t\t\t\tdata,\n\t\t\t\tidentifierData,\n\t\t\t);\n\t\t\t// Handlebars converts values to strings for rendering.\n\t\t\t// We replicate this behavior: null/undefined → \"\", otherwise String(value).\n\t\t\tif (value != null) {\n\t\t\t\tresult += String(value);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n// ─── Direct Expression Resolution ────────────────────────────────────────────\n// Used for single-expression templates and the fast-path, to return the raw\n// value without going through the Handlebars engine.\n\n/**\n * Resolves an AST expression by following the path through the data.\n *\n * If the expression contains an identifier (e.g. `meetingId:1`), resolution\n * is performed in `identifierData[1]` instead of `data`.\n *\n * @param expr - The AST expression to resolve\n * @param data - The main data context\n * @param identifierData - Data by identifier (optional)\n * @returns The raw value pointed to by the expression\n */\nfunction resolveExpression(\n\texpr: hbs.AST.Expression,\n\tdata: Record<string, unknown>,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): unknown {\n\t// this / . → return the entire context\n\tif (isThisExpression(expr)) {\n\t\treturn data;\n\t}\n\n\t// Literals\n\tif (expr.type === \"StringLiteral\")\n\t\treturn (expr as hbs.AST.StringLiteral).value;\n\tif (expr.type === \"NumberLiteral\")\n\t\treturn (expr as hbs.AST.NumberLiteral).value;\n\tif (expr.type === \"BooleanLiteral\")\n\t\treturn (expr as hbs.AST.BooleanLiteral).value;\n\tif (expr.type === \"NullLiteral\") return null;\n\tif (expr.type === \"UndefinedLiteral\") return undefined;\n\n\t// PathExpression — navigate through segments in the data object\n\tconst segments = extractPathSegments(expr);\n\tif (segments.length === 0) {\n\t\tthrow new TemplateRuntimeError(\n\t\t\t`Cannot resolve expression of type \"${expr.type}\"`,\n\t\t);\n\t}\n\n\t// Extract the potential identifier from the last segment\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\tif (identifier !== null && identifierData) {\n\t\tconst source = identifierData[identifier];\n\t\tif (source) {\n\t\t\treturn resolveDataPath(source, cleanSegments);\n\t\t}\n\t\t// Source does not exist → undefined (like a missing key)\n\t\treturn undefined;\n\t}\n\n\tif (identifier !== null && !identifierData) {\n\t\t// Template uses an identifier but no identifierData was provided\n\t\treturn undefined;\n\t}\n\n\treturn resolveDataPath(data, cleanSegments);\n}\n\n/**\n * Navigates through a data object by following a path of segments.\n *\n * @param data - The data object\n * @param segments - The path segments (e.g. `[\"user\", \"address\", \"city\"]`)\n * @returns The value at the end of the path, or `undefined` if an\n * intermediate segment is null/undefined\n */\nexport function resolveDataPath(data: unknown, segments: string[]): unknown {\n\tlet current: unknown = data;\n\n\tfor (const segment of segments) {\n\t\tif (current === null || current === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcurrent = (current as Record<string, unknown>)[segment];\n\t}\n\n\treturn current;\n}\n\n// ─── Data Merging ────────────────────────────────────────────────────────────\n// For Handlebars rendering (mixed templates / blocks), we cannot intercept\n// resolution on a per-expression basis. Instead, we merge identifier data\n// into the main object using the format `\"key:N\"`.\n//\n// Handlebars parses `{{meetingId:1}}` as a PathExpression with a single\n// segment `\"meetingId:1\"`, so it looks up the key `\"meetingId:1\"` in the\n// data object — which matches our flattened format exactly.\n\n/**\n * Merges the main data with identifier data.\n *\n * @param data - Main data\n * @param identifierData - Data by identifier\n * @returns A merged object where identifier data appears as `\"key:N\"` keys\n *\n * @example\n * ```\n * mergeDataWithIdentifiers(\n * { name: \"Alice\" },\n * { 1: { meetingId: \"val1\" }, 2: { meetingId: \"val2\" } }\n * )\n * // → { name: \"Alice\", \"meetingId:1\": \"val1\", \"meetingId:2\": \"val2\" }\n * ```\n */\nfunction mergeDataWithIdentifiers(\n\tdata: Record<string, unknown>,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): Record<string, unknown> {\n\tif (!identifierData) return data;\n\n\tconst merged: Record<string, unknown> = { ...data };\n\n\tfor (const [id, idData] of Object.entries(identifierData)) {\n\t\tfor (const [key, value] of Object.entries(idData)) {\n\t\t\tmerged[`${key}:${id}`] = value;\n\t\t}\n\t}\n\n\treturn merged;\n}\n\n// ─── Handlebars Rendering ────────────────────────────────────────────────────\n// For complex templates (blocks, helpers), we delegate to Handlebars.\n// Compilation is cached to avoid costly recompilations.\n\n/**\n * Compiles and executes a template via Handlebars.\n *\n * Uses a compilation cache (LRU) to avoid recompiling the same template\n * on repeated calls. The cache is either:\n * - The global cache (for the standalone `execute()` function)\n * - The instance cache provided via `ExecutorContext` (for `Typebars`)\n *\n * @param template - The template string\n * @param data - The context data\n * @param ctx - Optional execution context (cache, Handlebars env)\n * @returns Always a string\n */\nfunction renderWithHandlebars(\n\ttemplate: string,\n\tdata: Record<string, unknown>,\n\tctx?: ExecutorContext,\n): string {\n\ttry {\n\t\t// 1. Use the pre-compiled template if available (CompiledTemplate)\n\t\tif (ctx?.compiledTemplate) {\n\t\t\treturn ctx.compiledTemplate(data);\n\t\t}\n\n\t\t// 2. Look up in the cache (instance or global)\n\t\tconst cache = ctx?.compilationCache ?? globalCompilationCache;\n\t\tconst hbs = ctx?.hbs ?? Handlebars;\n\n\t\tlet compiled = cache.get(template);\n\t\tif (!compiled) {\n\t\t\tcompiled = hbs.compile(template, {\n\t\t\t\t// Disable HTML-escaping by default — this engine is not\n\t\t\t\t// HTML-specific, we want raw values.\n\t\t\t\tnoEscape: true,\n\t\t\t\t// Strict mode: throws if a path does not exist in the data.\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t\tcache.set(template, compiled);\n\t\t}\n\n\t\treturn compiled(data);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new TemplateRuntimeError(message);\n\t}\n}\n\n/**\n * Clears the global Handlebars compilation cache.\n * Useful for tests or to free memory.\n */\nexport function clearCompilationCache(): void {\n\tglobalCompilationCache.clear();\n}\n"],"names":["Handlebars","TemplateRuntimeError","canUseFastPath","coerceLiteral","extractExpressionIdentifier","extractPathSegments","getEffectivelySingleBlock","getEffectivelySingleExpression","isSingleExpression","isThisExpression","parse","isLiteralInput","isObjectInput","LRUCache","globalCompilationCache","execute","template","data","identifierData","executeObjectTemplate","ast","executeFromAst","result","key","value","Object","entries","ctx","stmt","body","params","length","hash","resolveExpression","path","singleExpr","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","executeFastPath","singleBlock","type","String","expr","undefined","segments","cleanSegments","identifier","source","resolveDataPath","current","segment","id","idData","compiledTemplate","cache","compilationCache","hbs","compiled","get","compile","noEscape","strict","set","error","message","Error","clearCompilationCache","clear"],"mappings":"AAAA,OAAOA,eAAgB,YAAa,AACpC,QAASC,oBAAoB,KAAQ,aAAc,AACnD,QACCC,cAAc,CACdC,aAAa,CACbC,2BAA2B,CAC3BC,mBAAmB,CACnBC,yBAAyB,CACzBC,8BAA8B,CAC9BC,kBAAkB,CAClBC,gBAAgB,CAChBC,KAAK,KACC,aAAc,AAErB,QAASC,cAAc,CAAEC,aAAa,KAAQ,YAAa,AAC3D,QAASC,QAAQ,KAAQ,YAAa,CAoDtC,MAAMC,uBAAyB,IAAID,SAClC,IAiBD,QAAO,SAASE,QACfC,QAAuB,CACvBC,IAA6B,CAC7BC,cAAwD,EAExD,GAAIN,cAAcI,UAAW,CAC5B,OAAOG,sBAAsBH,SAAUC,KAAMC,eAC9C,CACA,GAAIP,eAAeK,UAAW,OAAOA,SACrC,MAAMI,IAAMV,MAAMM,UAClB,OAAOK,eAAeD,IAAKJ,SAAUC,KAAM,CAAEC,cAAe,EAC7D,CAOA,SAASC,sBACRH,QAA6B,CAC7BC,IAA6B,CAC7BC,cAAwD,EAExD,MAAMI,OAAkC,CAAC,EACzC,IAAK,KAAM,CAACC,IAAKC,MAAM,GAAIC,OAAOC,OAAO,CAACV,UAAW,CACpDM,MAAM,CAACC,IAAI,CAAGR,QAAQS,MAAOP,KAAMC,eACpC,CACA,OAAOI,MACR,CAiBA,OAAO,SA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