typebars 1.0.4 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/{analyzer.d.ts → cjs/analyzer.d.ts} +1 -1
- package/dist/cjs/analyzer.js +2 -0
- package/dist/cjs/analyzer.js.map +1 -0
- package/dist/{compiled-template.d.ts → cjs/compiled-template.d.ts} +2 -2
- package/dist/cjs/compiled-template.js +2 -0
- package/dist/cjs/compiled-template.js.map +1 -0
- package/dist/{errors.d.ts → cjs/errors.d.ts} +1 -1
- package/dist/cjs/errors.js +3 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/{executor.d.ts → cjs/executor.d.ts} +2 -2
- package/dist/cjs/executor.js +2 -0
- package/dist/cjs/executor.js.map +1 -0
- package/dist/{helpers → cjs/helpers}/helper-factory.d.ts +1 -1
- package/dist/cjs/helpers/helper-factory.js +2 -0
- package/dist/cjs/helpers/helper-factory.js.map +1 -0
- package/dist/cjs/helpers/index.d.ts +4 -0
- package/dist/cjs/helpers/index.js +2 -0
- package/dist/cjs/helpers/index.js.map +1 -0
- package/dist/{helpers → cjs/helpers}/logical-helpers.d.ts +2 -2
- package/dist/cjs/helpers/logical-helpers.js +2 -0
- package/dist/cjs/helpers/logical-helpers.js.map +1 -0
- package/dist/{helpers → cjs/helpers}/math-helpers.d.ts +2 -2
- package/dist/cjs/helpers/math-helpers.js +2 -0
- package/dist/cjs/helpers/math-helpers.js.map +1 -0
- package/dist/cjs/helpers/utils.js +2 -0
- package/dist/cjs/helpers/utils.js.map +1 -0
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +2 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/parser.js +2 -0
- package/dist/cjs/parser.js.map +1 -0
- package/dist/cjs/schema-resolver.js +2 -0
- package/dist/cjs/schema-resolver.js.map +1 -0
- package/dist/{typebars.d.ts → cjs/typebars.d.ts} +2 -2
- package/dist/cjs/typebars.js +2 -0
- package/dist/cjs/typebars.js.map +1 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/{utils.d.ts → cjs/utils.d.ts} +1 -1
- package/dist/cjs/utils.js +2 -0
- package/dist/cjs/utils.js.map +1 -0
- package/dist/esm/analyzer.d.ts +59 -0
- package/dist/esm/analyzer.js +2 -0
- package/dist/esm/analyzer.js.map +1 -0
- package/dist/esm/compiled-template.d.ts +130 -0
- package/dist/esm/compiled-template.js +2 -0
- package/dist/esm/compiled-template.js.map +1 -0
- package/dist/esm/errors.d.ts +105 -0
- package/dist/esm/errors.js +3 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/executor.d.ts +55 -0
- package/dist/esm/executor.js +2 -0
- package/dist/esm/executor.js.map +1 -0
- package/dist/esm/helpers/helper-factory.d.ts +56 -0
- package/dist/esm/helpers/helper-factory.js +2 -0
- package/dist/esm/helpers/helper-factory.js.map +1 -0
- package/dist/esm/helpers/index.d.ts +4 -0
- package/dist/esm/helpers/index.js +2 -0
- package/dist/esm/helpers/index.js.map +1 -0
- package/dist/esm/helpers/logical-helpers.d.ts +15 -0
- package/dist/esm/helpers/logical-helpers.js +2 -0
- package/dist/esm/helpers/logical-helpers.js.map +1 -0
- package/dist/esm/helpers/math-helpers.d.ts +13 -0
- package/dist/esm/helpers/math-helpers.js +2 -0
- package/dist/esm/helpers/math-helpers.js.map +1 -0
- package/dist/esm/helpers/utils.d.ts +19 -0
- package/dist/esm/helpers/utils.js +2 -0
- package/dist/esm/helpers/utils.js.map +1 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/parser.d.ts +146 -0
- package/dist/esm/parser.js +2 -0
- package/dist/esm/parser.js.map +1 -0
- package/dist/esm/schema-resolver.d.ts +88 -0
- package/dist/esm/schema-resolver.js +2 -0
- package/dist/esm/schema-resolver.js.map +1 -0
- package/dist/esm/typebars.d.ts +130 -0
- package/dist/esm/typebars.js +2 -0
- package/dist/esm/typebars.js.map +1 -0
- package/dist/esm/types.d.ts +334 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/utils.d.ts +113 -0
- package/dist/esm/utils.js +2 -0
- package/dist/esm/utils.js.map +1 -0
- package/package.json +30 -9
- package/dist/analyzer.js +0 -2
- package/dist/analyzer.js.map +0 -1
- package/dist/compiled-template.js +0 -2
- package/dist/compiled-template.js.map +0 -1
- package/dist/errors.js +0 -2
- package/dist/errors.js.map +0 -1
- package/dist/executor.js +0 -2
- package/dist/executor.js.map +0 -1
- package/dist/helpers/helper-factory.js +0 -2
- package/dist/helpers/helper-factory.js.map +0 -1
- package/dist/helpers/index.d.ts +0 -4
- package/dist/helpers/index.js +0 -2
- package/dist/helpers/index.js.map +0 -1
- package/dist/helpers/logical-helpers.js +0 -2
- package/dist/helpers/logical-helpers.js.map +0 -1
- package/dist/helpers/math-helpers.js +0 -2
- package/dist/helpers/math-helpers.js.map +0 -1
- package/dist/helpers/utils.js +0 -2
- package/dist/helpers/utils.js.map +0 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -2
- package/dist/index.js.map +0 -1
- package/dist/parser.js +0 -2
- package/dist/parser.js.map +0 -1
- package/dist/schema-resolver.js +0 -2
- package/dist/schema-resolver.js.map +0 -1
- package/dist/typebars.js +0 -2
- package/dist/typebars.js.map +0 -1
- package/dist/types.js +0 -2
- package/dist/types.js.map +0 -1
- package/dist/utils.js +0 -2
- package/dist/utils.js.map +0 -1
- /package/dist/{helpers → cjs/helpers}/utils.d.ts +0 -0
- /package/dist/{parser.d.ts → cjs/parser.d.ts} +0 -0
- /package/dist/{schema-resolver.d.ts → cjs/schema-resolver.d.ts} +0 -0
- /package/dist/{types.d.ts → cjs/types.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
**Type-safe Handlebars template engine with static analysis powered by JSON Schema.**
|
|
4
4
|
|
|
5
5
|
Typebars wraps Handlebars with a static analysis layer that validates your templates against a JSON Schema **before execution**. Given an input schema describing your data, Typebars detects unknown properties, type mismatches, and missing arguments at analysis time — and infers the exact JSON Schema of the template's output.
|
|
6
|
-
|
|
7
6
|
```ts
|
|
8
7
|
import { Typebars } from "typebars";
|
|
9
8
|
|
|
@@ -1579,4 +1578,4 @@ Returned by `engine.compile()`. Has the same methods but without re-parsing:
|
|
|
1579
1578
|
|
|
1580
1579
|
## License
|
|
1581
1580
|
|
|
1582
|
-
MIT
|
|
1581
|
+
MIT
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { JSONSchema7 } from "json-schema";
|
|
2
|
-
import type { AnalysisResult, HelperDefinition, TemplateDiagnostic, TemplateInput } from "./types";
|
|
2
|
+
import type { AnalysisResult, HelperDefinition, TemplateDiagnostic, TemplateInput } from "./types.js";
|
|
3
3
|
/** Context passed recursively during AST traversal */
|
|
4
4
|
interface AnalysisContext {
|
|
5
5
|
/** Root schema (for resolving $refs) */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get analyze(){return analyze},get analyzeFromAst(){return analyzeFromAst},get inferBlockType(){return inferBlockType}});const _errors=require("./errors.js");const _parser=require("./parser.js");const _schemaresolver=require("./schema-resolver.js");const _typests=require("./types.js");const _utils=require("./utils.js");function analyze(template,inputSchema,identifierSchemas){if((0,_typests.isObjectInput)(template)){return analyzeObjectTemplate(template,inputSchema,identifierSchemas)}if((0,_typests.isLiteralInput)(template)){return{valid:true,diagnostics:[],outputSchema:(0,_typests.inferPrimitiveSchema)(template)}}const ast=(0,_parser.parse)(template);return analyzeFromAst(ast,template,inputSchema,{identifierSchemas})}function analyzeObjectTemplate(template,inputSchema,identifierSchemas){return(0,_utils.aggregateObjectAnalysis)(Object.keys(template),key=>analyze(template[key],inputSchema,identifierSchemas))}function analyzeFromAst(ast,template,inputSchema,options){(0,_schemaresolver.assertNoConditionalSchema)(inputSchema);if(options?.identifierSchemas){for(const[id,idSchema]of Object.entries(options.identifierSchemas)){(0,_schemaresolver.assertNoConditionalSchema)(idSchema,`/identifierSchemas/${id}`)}}const ctx={root:inputSchema,current:inputSchema,diagnostics:[],template,identifierSchemas:options?.identifierSchemas,helpers:options?.helpers};const outputSchema=inferProgramType(ast,ctx);const hasErrors=ctx.diagnostics.some(d=>d.severity==="error");return{valid:!hasErrors,diagnostics:ctx.diagnostics,outputSchema:(0,_schemaresolver.simplifySchema)(outputSchema)}}function processStatement(stmt,ctx){switch(stmt.type){case"ContentStatement":case"CommentStatement":return undefined;case"MustacheStatement":return processMustache(stmt,ctx);case"BlockStatement":return inferBlockType(stmt,ctx);default:addDiagnostic(ctx,"UNANALYZABLE","warning",`Unsupported AST node type: "${stmt.type}"`,stmt);return undefined}}function processMustache(stmt,ctx){if(stmt.path.type==="SubExpression"){addDiagnostic(ctx,"UNANALYZABLE","warning","Sub-expressions are not statically analyzable",stmt);return{}}if(stmt.params.length>0||stmt.hash){const helperName=getExpressionName(stmt.path);const helper=ctx.helpers?.get(helperName);if(helper){const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(stmt.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${stmt.params.length}`,stmt,{helperName,expected:`${requiredCount} argument(s)`,actual:`${stmt.params.length} argument(s)`})}}for(let i=0;i<stmt.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(stmt.params[i],ctx,stmt);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,stmt,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown inline helper "${helperName}" — cannot analyze statically`,stmt,{helperName});return{type:"string"}}return resolveExpressionWithDiagnostics(stmt.path,ctx,stmt)??{}}function isParamTypeCompatible(resolved,expected){if(!expected.type||!resolved.type)return true;const expectedTypes=Array.isArray(expected.type)?expected.type:[expected.type];const resolvedTypes=Array.isArray(resolved.type)?resolved.type:[resolved.type];return resolvedTypes.some(rt=>expectedTypes.some(et=>rt===et||et==="number"&&rt==="integer"||et==="integer"&&rt==="number"))}function inferProgramType(program,ctx){const effective=(0,_parser.getEffectiveBody)(program);if(effective.length===0){return{type:"string"}}const singleExpr=(0,_parser.getEffectivelySingleExpression)(program);if(singleExpr){return processMustache(singleExpr,ctx)}const singleBlock=(0,_parser.getEffectivelySingleBlock)(program);if(singleBlock){return inferBlockType(singleBlock,ctx)}const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){const text=effective.map(s=>s.value).join("").trim();if(text==="")return{type:"string"};const literalType=(0,_parser.detectLiteralType)(text);if(literalType)return{type:literalType}}const allBlocks=effective.every(s=>s.type==="BlockStatement");if(allBlocks){const types=[];for(const stmt of effective){const t=inferBlockType(stmt,ctx);if(t)types.push(t)}if(types.length===1)return types[0];if(types.length>1)return(0,_schemaresolver.simplifySchema)({oneOf:types});return{type:"string"}}for(const stmt of program.body){processStatement(stmt,ctx)}return{type:"string"}}function inferBlockType(stmt,ctx){const helperName=getBlockHelperName(stmt);switch(helperName){case"if":case"unless":{const arg=getBlockArgument(stmt);if(arg){resolveExpressionWithDiagnostics(arg,ctx,stmt)}else{addDiagnostic(ctx,"MISSING_ARGUMENT","error",(0,_errors.createMissingArgumentMessage)(helperName),stmt,{helperName})}const thenType=inferProgramType(stmt.program,ctx);if(stmt.inverse){const elseType=inferProgramType(stmt.inverse,ctx);if((0,_utils.deepEqual)(thenType,elseType))return thenType;return(0,_schemaresolver.simplifySchema)({oneOf:[thenType,elseType]})}return thenType}case"each":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",(0,_errors.createMissingArgumentMessage)("each"),stmt,{helperName:"each"});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const collectionSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);if(!collectionSchema){const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const itemSchema=(0,_schemaresolver.resolveArrayItems)(collectionSchema,ctx.root);if(!itemSchema){addDiagnostic(ctx,"TYPE_MISMATCH","error",(0,_errors.createTypeMismatchMessage)("each","an array",schemaTypeLabel(collectionSchema)),stmt,{helperName:"each",expected:"array",actual:schemaTypeLabel(collectionSchema)});const saved=ctx.current;ctx.current={};inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}const saved=ctx.current;ctx.current=itemSchema;inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}case"with":{const arg=getBlockArgument(stmt);if(!arg){addDiagnostic(ctx,"MISSING_ARGUMENT","error",(0,_errors.createMissingArgumentMessage)("with"),stmt,{helperName:"with"});const saved=ctx.current;ctx.current={};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}const innerSchema=resolveExpressionWithDiagnostics(arg,ctx,stmt);const saved=ctx.current;ctx.current=innerSchema??{};const result=inferProgramType(stmt.program,ctx);ctx.current=saved;if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return result}default:{const helper=ctx.helpers?.get(helperName);if(helper){for(const param of stmt.params){resolveExpressionWithDiagnostics(param,ctx,stmt)}inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return helper.returnType??{type:"string"}}addDiagnostic(ctx,"UNKNOWN_HELPER","warning",(0,_errors.createUnknownHelperMessage)(helperName),stmt,{helperName});inferProgramType(stmt.program,ctx);if(stmt.inverse)inferProgramType(stmt.inverse,ctx);return{type:"string"}}}}function resolveExpressionWithDiagnostics(expr,ctx,parentNode){if((0,_parser.isThisExpression)(expr)){return ctx.current}if(expr.type==="SubExpression"){return resolveSubExpression(expr,ctx,parentNode)}const segments=(0,_parser.extractPathSegments)(expr);if(segments.length===0){if(expr.type==="StringLiteral")return{type:"string"};if(expr.type==="NumberLiteral")return{type:"number"};if(expr.type==="BooleanLiteral")return{type:"boolean"};if(expr.type==="NullLiteral")return{type:"null"};if(expr.type==="UndefinedLiteral")return{};addDiagnostic(ctx,"UNANALYZABLE","warning",(0,_errors.createUnanalyzableMessage)(expr.type),parentNode??expr);return undefined}const{cleanSegments,identifier}=(0,_parser.extractExpressionIdentifier)(segments);if(identifier!==null){return resolveWithIdentifier(cleanSegments,identifier,ctx,parentNode??expr)}const resolved=(0,_schemaresolver.resolveSchemaPath)(ctx.current,cleanSegments);if(resolved===undefined){const fullPath=cleanSegments.join(".");const availableProperties=(0,_utils.getSchemaPropertyNames)(ctx.current);addDiagnostic(ctx,"UNKNOWN_PROPERTY","error",(0,_errors.createPropertyNotFoundMessage)(fullPath,availableProperties),parentNode??expr,{path:fullPath,availableProperties});return undefined}return resolved}function resolveWithIdentifier(cleanSegments,identifier,ctx,node){const fullPath=cleanSegments.join(".");if(!ctx.identifierSchemas){addDiagnostic(ctx,"MISSING_IDENTIFIER_SCHEMAS","error",`Property "${fullPath}:${identifier}" uses an identifier but no identifier schemas were provided`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const idSchema=ctx.identifierSchemas[identifier];if(!idSchema){addDiagnostic(ctx,"UNKNOWN_IDENTIFIER","error",`Property "${fullPath}:${identifier}" references identifier ${identifier} but no schema exists for this identifier`,node,{path:`${fullPath}:${identifier}`,identifier});return undefined}const resolved=(0,_schemaresolver.resolveSchemaPath)(idSchema,cleanSegments);if(resolved===undefined){const availableProperties=(0,_utils.getSchemaPropertyNames)(idSchema);addDiagnostic(ctx,"IDENTIFIER_PROPERTY_NOT_FOUND","error",`Property "${fullPath}" does not exist in the schema for identifier ${identifier}`,node,{path:fullPath,identifier,availableProperties});return undefined}return resolved}function resolveSubExpression(expr,ctx,parentNode){const helperName=getExpressionName(expr.path);const helper=ctx.helpers?.get(helperName);if(!helper){addDiagnostic(ctx,"UNKNOWN_HELPER","warning",`Unknown sub-expression helper "${helperName}" — cannot analyze statically`,parentNode??expr,{helperName});return{type:"string"}}const helperParams=helper.params;if(helperParams){const requiredCount=helperParams.filter(p=>!p.optional).length;if(expr.params.length<requiredCount){addDiagnostic(ctx,"MISSING_ARGUMENT","error",`Helper "${helperName}" expects at least ${requiredCount} argument(s), but got ${expr.params.length}`,parentNode??expr,{helperName,expected:`${requiredCount} argument(s)`,actual:`${expr.params.length} argument(s)`})}}for(let i=0;i<expr.params.length;i++){const resolvedSchema=resolveExpressionWithDiagnostics(expr.params[i],ctx,parentNode??expr);const helperParam=helperParams?.[i];if(resolvedSchema&&helperParam?.type){const expectedType=helperParam.type;if(!isParamTypeCompatible(resolvedSchema,expectedType)){const paramName=helperParam.name;addDiagnostic(ctx,"TYPE_MISMATCH","error",`Helper "${helperName}" parameter "${paramName}" expects ${schemaTypeLabel(expectedType)}, but got ${schemaTypeLabel(resolvedSchema)}`,parentNode??expr,{helperName,expected:schemaTypeLabel(expectedType),actual:schemaTypeLabel(resolvedSchema)})}}}return helper.returnType??{type:"string"}}function getBlockArgument(stmt){return stmt.params[0]}function getBlockHelperName(stmt){if(stmt.path.type==="PathExpression"){return stmt.path.original}return""}function getExpressionName(expr){if(expr.type==="PathExpression"){return expr.original}return""}function addDiagnostic(ctx,code,severity,message,node,details){const diagnostic={severity,code,message};if(node&&"loc"in node&&node.loc){diagnostic.loc={start:{line:node.loc.start.line,column:node.loc.start.column},end:{line:node.loc.end.line,column:node.loc.end.column}};diagnostic.source=(0,_utils.extractSourceSnippet)(ctx.template,diagnostic.loc)}if(details){diagnostic.details=details}ctx.diagnostics.push(diagnostic)}function schemaTypeLabel(schema){if(schema.type){return Array.isArray(schema.type)?schema.type.join(" | "):schema.type}if(schema.oneOf)return"oneOf(...)";if(schema.anyOf)return"anyOf(...)";if(schema.allOf)return"allOf(...)";if(schema.enum)return"enum";return"unknown"}
|
|
2
|
+
//# sourceMappingURL=analyzer.js.map
|
|
@@ -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":["analyze","analyzeFromAst","inferBlockType","template","inputSchema","identifierSchemas","isObjectInput","analyzeObjectTemplate","isLiteralInput","valid","diagnostics","outputSchema","inferPrimitiveSchema","ast","parse","aggregateObjectAnalysis","Object","keys","key","options","assertNoConditionalSchema","id","idSchema","entries","ctx","root","current","helpers","inferProgramType","hasErrors","some","d","severity","simplifySchema","processStatement","stmt","type","undefined","processMustache","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","getEffectiveBody","singleExpr","getEffectivelySingleExpression","singleBlock","getEffectivelySingleBlock","allContent","every","s","text","map","value","join","trim","literalType","detectLiteralType","allBlocks","types","t","push","oneOf","body","getBlockHelperName","arg","getBlockArgument","createMissingArgumentMessage","thenType","inverse","elseType","deepEqual","saved","collectionSchema","itemSchema","resolveArrayItems","createTypeMismatchMessage","result","innerSchema","param","createUnknownHelperMessage","expr","parentNode","isThisExpression","resolveSubExpression","segments","extractPathSegments","createUnanalyzableMessage","cleanSegments","identifier","extractExpressionIdentifier","resolveWithIdentifier","resolveSchemaPath","fullPath","availableProperties","getSchemaPropertyNames","createPropertyNotFoundMessage","node","original","code","message","details","diagnostic","loc","start","line","column","end","source","extractSourceSnippet","schema","anyOf","allOf","enum"],"mappings":"mPAsGgBA,iBAAAA,aA8CAC,wBAAAA,oBAs0BPC,wBAAAA,wCAn9BF,kCAUA,0CAMA,4CAcA,mCAMA,WA2DA,SAASF,QACfG,QAAuB,CACvBC,WAAwB,CACxBC,iBAA+C,EAE/C,GAAIC,GAAAA,sBAAa,EAACH,UAAW,CAC5B,OAAOI,sBAAsBJ,SAAUC,YAAaC,kBACrD,CACA,GAAIG,GAAAA,uBAAc,EAACL,UAAW,CAC7B,MAAO,CACNM,MAAO,KACPC,YAAa,EAAE,CACfC,aAAcC,GAAAA,6BAAoB,EAACT,SACpC,CACD,CACA,MAAMU,IAAMC,GAAAA,aAAK,EAACX,UAClB,OAAOF,eAAeY,IAAKV,SAAUC,YAAa,CAAEC,iBAAkB,EACvE,CAOA,SAASE,sBACRJ,QAA6B,CAC7BC,WAAwB,CACxBC,i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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,CAAGC,GAAAA,2BAAoB,EAACpH,IAAIrB,QAAQ,CAAEkI,WAAWC,GAAG,CACtE,CAEA,GAAIF,QAAS,CACZC,WAAWD,OAAO,CAAGA,OACtB,CAEA5G,IAAId,WAAW,CAACkF,IAAI,CAACyC,WACtB,CAKA,SAAStE,gBAAgB8E,MAAmB,EAC3C,GAAIA,OAAOzG,IAAI,CAAE,CAChB,OAAO+B,MAAMC,OAAO,CAACyE,OAAOzG,IAAI,EAAIyG,OAAOzG,IAAI,CAACiD,IAAI,CAAC,OAASwD,OAAOzG,IAAI,AAC1E,CACA,GAAIyG,OAAOhD,KAAK,CAAE,MAAO,aACzB,GAAIgD,OAAOC,KAAK,CAAE,MAAO,aACzB,GAAID,OAAOE,KAAK,CAAE,MAAO,aACzB,GAAIF,OAAOG,IAAI,CAAE,MAAO,OACxB,MAAO,SACR"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type Handlebars from "handlebars";
|
|
2
2
|
import type { JSONSchema7 } from "json-schema";
|
|
3
|
-
import type { AnalysisResult, ExecuteOptions, HelperDefinition, ValidationResult } from "./types";
|
|
4
|
-
import { type LRUCache } from "./utils";
|
|
3
|
+
import type { AnalysisResult, ExecuteOptions, HelperDefinition, ValidationResult } from "./types.js";
|
|
4
|
+
import { type LRUCache } from "./utils.js";
|
|
5
5
|
/** Internal options passed by Typebars during compilation */
|
|
6
6
|
export interface CompiledTemplateOptions {
|
|
7
7
|
/** Custom helpers registered on the engine */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"CompiledTemplate",{enumerable:true,get:function(){return CompiledTemplate}});const _analyzerts=require("./analyzer.js");const _errorsts=require("./errors.js");const _executorts=require("./executor.js");const _typests=require("./types.js");const _utils=require("./utils.js");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}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(0,_utils.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:(0,_typests.inferPrimitiveSchema)(this.state.value)};case"template":return(0,_analyzerts.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 _errorsts.TemplateAnalysisError(analysis.diagnostics)}}return(0,_executorts.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(0,_utils.aggregateObjectAnalysisAndExecution)(Object.keys(children),key=>children[key].analyzeAndExecute(inputSchema,data,options))}case"literal":return{analysis:{valid:true,diagnostics:[],outputSchema:(0,_typests.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=(0,_executorts.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":["CompiledTemplate","ast","state","kind","template","source","fromTemplate","options","fromLiteral","value","fromObject","children","analyze","inputSchema","identifierSchemas","aggregateObjectAnalysis","Object","keys","key","child","Error","valid","diagnostics","outputSchema","inferPrimitiveSchema","analyzeFromAst","helpers","validate","analysis","execute","data","result","entries","schema","TemplateAnalysisError","executeFromAst","buildExecutorContext","analyzeAndExecute","aggregateObjectAnalysisAndExecution","undefined","identifierData","compiledTemplate","getOrCompileHbs","hbs","compilationCache","hbsCompiled","compile","noEscape","strict"],"mappings":"oGA0EaA,0DAAAA,8CAxEkB,yCACO,yCACe,wCAOhB,mCAK9B,+LA0DA,MAAMA,iBAaZ,IAAIC,KAA8B,CACjC,OAAO,IAAI,CAACC,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACD,GAAG,CAAG,IAC1D,CAGA,IAAIG,UAAmB,CACtB,OAAO,IAAI,CAACF,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACG,MAAM,CAAG,EAC7D,CAgBA,OAAOC,aACNL,GAAoB,CACpB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function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get TemplateAnalysisError(){return TemplateAnalysisError},get TemplateError(){return TemplateError},get TemplateParseError(){return TemplateParseError},get TemplateRuntimeError(){return TemplateRuntimeError},get UnsupportedSchemaError(){return UnsupportedSchemaError},get createMissingArgumentMessage(){return createMissingArgumentMessage},get createPropertyNotFoundMessage(){return createPropertyNotFoundMessage},get createTypeMismatchMessage(){return createTypeMismatchMessage},get createUnanalyzableMessage(){return createUnanalyzableMessage},get createUnknownHelperMessage(){return createUnknownHelperMessage}});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}class TemplateError extends Error{toJSON(){return{name:this.name,message:this.message}}constructor(message){super(message);this.name="TemplateError"}}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"}}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}}class TemplateRuntimeError extends TemplateError{constructor(message){super(`Runtime error: ${message}`);this.name="TemplateRuntimeError"}}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(" ")}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(", ")}`}function createTypeMismatchMessage(helperName,expected,actual){return`"{{#${helperName}}}" expects ${expected}, but resolved schema has type "${actual}"`}function createMissingArgumentMessage(helperName){return`"{{#${helperName}}}" requires an argument`}function createUnknownHelperMessage(helperName){return`Unknown block helper "{{#${helperName}}}" — cannot analyze statically`}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":["TemplateAnalysisError","TemplateError","TemplateParseError","TemplateRuntimeError","UnsupportedSchemaError","createMissingArgumentMessage","createPropertyNotFoundMessage","createTypeMismatchMessage","createUnanalyzableMessage","createUnknownHelperMessage","Error","toJSON","name","message","loc","source","errorCount","warningCount","diagnostics","errors","filter","d","severity","warnings","summary","map","formatDiagnosticLine","join","length","keyword","schemaPath","diag","parts","code","push","start","line","column","path","availableProperties","base","helperName","expected","actual","nodeType"],"mappings":"mPA0DaA,+BAAAA,2BA/CAC,uBAAAA,mBAqBAC,4BAAAA,wBAoGAC,8BAAAA,0BAeAC,gCAAAA,4BA0EGC,sCAAAA,kCAvBAC,uCAAAA,mCAYAC,mCAAAA,+BAyBAC,mCAAAA,+BAPAC,oCAAAA,kNAzNT,MAAMR,sBAAsBS,MAUlCC,QAAkC,CACjC,MAAO,CACNC,KAAM,IAAI,CAACA,IAAI,CACfC,QAAS,IAAI,CAACA,OAAO,AACtB,CACD,CAdA,YAAYA,OAAe,CAAE,CAC5B,KAAK,CAACA,QACN,CAAA,IAAI,CAACD,IAAI,CAAG,eACb,CAYD,CAKO,MAAMV,2BAA2BD,cAYvC,AAASU,QAAkC,CAC1C,MAAO,CACNC,KAAM,IAAI,CAACA,IAAI,CACfC,QAAS,IAAI,CAACA,OAAO,CACrBC,IAAK,IAAI,CAACA,GAAG,CACbC,OAAQ,IAAI,CAACA,MAAM,AACpB,CACD,CAlBA,YACCF,OAAe,CAEf,AAAgBC,GAAsC,CAEtD,AAAgBC,MAAe,CAC9B,CACD,KAAK,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EAC9D,MAAO,CAAC,IAAI,EAAEA,WAAW,wBAAwB,CAAC,AACnD,CAKO,SAAShC,2BAA2BgC,UAAkB,EAC5D,MAAO,CAAC,yBAAyB,EAAEA,WAAW,+BAA+B,CAAC,AAC/E,CAKO,SAASjC,0BAA0BoC,QAAgB,EACzD,MAAO,CAAC,oBAAoB,EAAEA,SAAS,+BAA+B,CAAC,AACxE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import Handlebars from "handlebars";
|
|
2
|
-
import type { TemplateInput } from "./types";
|
|
3
|
-
import { LRUCache } from "./utils";
|
|
2
|
+
import type { TemplateInput } from "./types.js";
|
|
3
|
+
import { LRUCache } from "./utils.js";
|
|
4
4
|
/** Optional context for execution (used by Typebars/CompiledTemplate) */
|
|
5
5
|
export interface ExecutorContext {
|
|
6
6
|
/** Data by identifier `{ [id]: { key: value } }` */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get clearCompilationCache(){return clearCompilationCache},get execute(){return execute},get executeFromAst(){return executeFromAst},get resolveDataPath(){return resolveDataPath}});const _handlebars=/*#__PURE__*/_interop_require_default(require("handlebars"));const _errorsts=require("./errors.js");const _parserts=require("./parser.js");const _typests=require("./types.js");const _utilsts=require("./utils.js");function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const globalCompilationCache=new _utilsts.LRUCache(128);function execute(template,data,identifierData){if((0,_typests.isObjectInput)(template)){return executeObjectTemplate(template,data,identifierData)}if((0,_typests.isLiteralInput)(template))return template;const ast=(0,_parserts.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}function executeFromAst(ast,template,data,ctx){const identifierData=ctx?.identifierData;if((0,_parserts.isSingleExpression)(ast)){const stmt=ast.body[0];if(stmt.params.length===0&&!stmt.hash){return resolveExpression(stmt.path,data,identifierData)}}const singleExpr=(0,_parserts.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(0,_parserts.coerceLiteral)(raw)}if((0,_parserts.canUseFastPath)(ast)&&ast.body.length>1){return executeFastPath(ast,data,identifierData)}const singleBlock=(0,_parserts.getEffectivelySingleBlock)(ast);if(singleBlock){const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return(0,_parserts.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((0,_parserts.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=(0,_parserts.extractPathSegments)(expr);if(segments.length===0){throw new _errorsts.TemplateRuntimeError(`Cannot resolve expression of type "${expr.type}"`)}const{cleanSegments,identifier}=(0,_parserts.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)}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.default;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 _errorsts.TemplateRuntimeError(message)}}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":["clearCompilationCache","execute","executeFromAst","resolveDataPath","globalCompilationCache","LRUCache","template","data","identifierData","isObjectInput","executeObjectTemplate","isLiteralInput","ast","parse","result","key","value","Object","entries","ctx","isSingleExpression","stmt","body","params","length","hash","resolveExpression","path","singleExpr","getEffectivelySingleExpression","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceLiteral","canUseFastPath","executeFastPath","singleBlock","getEffectivelySingleBlock","type","String","expr","isThisExpression","undefined","segments","extractPathSegments","TemplateRuntimeError","cleanSegments","identifier","extractExpressionIdentifier","source","current","segment","id","idData","compiledTemplate","cache","compilationCache","hbs","Handlebars","compiled","get","compile","noEscape","strict","set","error","message","Error","clear"],"mappings":"mPAgagBA,+BAAAA,2BA3UAC,iBAAAA,aA6CAC,wBAAAA,oBA2KAC,yBAAAA,mFA7SO,uCACc,uCAW9B,sCAEuC,qCACrB,kGAoDzB,MAAMC,uBAAyB,IAAIC,iBAAQ,CAC1C,KAiBM,SAASJ,QACfK,QAAuB,CACvBC,IAA6B,CAC7BC,cAAwD,EAExD,GAAIC,GAAAA,sBAAa,EAACH,UAAW,CAC5B,OAAOI,sBAAsBJ,SAAUC,KAAMC,eAC9C,CACA,GAAIG,GAAAA,uBAAc,EAACL,UAAW,OAAOA,SACrC,MAAMM,IAAMC,GAAAA,eAAK,EAACP,UAClB,OAAOJ,eAAeU,IAAKN,SAAUC,KAAM,CAAEC,cAAe,EAC7D,CAOA,SAASE,sBACRJ,QAA6B,CAC7BC,IAA6B,CAC7BC,cAAwD,EAExD,MAAMM,OAAkC,CAAC,EACzC,IAAK,KAAM,CAACC,IAAKC,MAAM,GAAIC,OAAOC,OAAO,CAACZ,UAAW,CACpDQ,MAAM,CAACC,IAAI,CAAGd,QAAQe,MAAOT,KAAMC,eACpC,CACA,OAAOM,MACR,CAiBO,SAASZ,eACfU,GAAoB,CACpBN,QAAgB,CAChBC,IAA6B,CAC7BY,GAAqB,EAErB,MAAMX,eAAiBW,KAAKX,eAK5B,GAAIY,GAAAA,4BAAkB,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../types";
|
|
1
|
+
import type { HelperDefinition } from "../types.js";
|
|
2
2
|
/** Minimal registration interface — avoids tight coupling with Typebars */
|
|
3
3
|
export interface HelperRegistry {
|
|
4
4
|
registerHelper(name: string, definition: HelperDefinition): unknown;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"HelperFactory",{enumerable:true,get:function(){return HelperFactory}});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}class HelperFactory{getDefinitions(){if(!this._definitions){this._definitions=new Map;this.buildDefinitions(this._definitions)}return this._definitions}getHelperNames(){if(!this._helperNames){this._helperNames=[...this.getDefinitions().keys()]}return this._helperNames}isHelper(name){if(!this._helperNamesSet){this._helperNamesSet=new Set(this.getHelperNames())}return this._helperNamesSet.has(name)}register(registry){for(const[name,def]of this.getDefinitions()){registry.registerHelper(name,def)}}unregister(registry){for(const name of this.getHelperNames()){registry.unregisterHelper(name)}}constructor(){_define_property(this,"_definitions",null);_define_property(this,"_helperNames",null);_define_property(this,"_helperNamesSet",null)}}
|
|
2
|
+
//# sourceMappingURL=helper-factory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/helper-factory.ts"],"sourcesContent":["import type { HelperDefinition } from \"../types.ts\";\n\n// ─── HelperFactory ───────────────────────────────────────────────────────────\n// Abstract base class that enforces a consistent pattern for creating,\n// registering, and managing groups of related helpers.\n//\n// Every helper factory (MathHelpers, LogicalHelpers, …) must extend this class\n// and implement the `buildDefinitions()` method to populate its helpers.\n//\n// The base class provides:\n// - Lazy-cached definitions, helper names, and name set\n// - `register()` / `unregister()` for any `HelperRegistry`\n// - `getHelperNames()` / `isHelper()` for introspection\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Minimal registration interface — avoids tight coupling with Typebars */\nexport interface HelperRegistry {\n\tregisterHelper(name: string, definition: HelperDefinition): unknown;\n\tunregisterHelper(name: string): unknown;\n}\n\n// ─── Abstract Base Class ─────────────────────────────────────────────────────\n\nexport abstract class HelperFactory {\n\t// ── Lazy caches (populated on first access) ──────────────────────────\n\tprivate _definitions: Map<string, HelperDefinition> | null = null;\n\tprivate _helperNames: readonly string[] | null = null;\n\tprivate _helperNamesSet: ReadonlySet<string> | null = null;\n\n\t// ── Abstract method — must be implemented by each factory ────────────\n\n\t/**\n\t * Populates the `defs` map with all helper definitions.\n\t *\n\t * Subclasses implement this method to register their helpers:\n\t * ```\n\t * protected buildDefinitions(defs: Map<string, HelperDefinition>): void {\n\t * defs.set(\"myHelper\", {\n\t * fn: (a: unknown) => String(a).toUpperCase(),\n\t * params: [{ name: \"a\", type: { type: \"string\" } }],\n\t * returnType: { type: \"string\" },\n\t * description: \"Converts to uppercase\",\n\t * });\n\t * }\n\t * ```\n\t *\n\t * @param defs - The map to populate with `[name, HelperDefinition]` entries\n\t */\n\tprotected abstract buildDefinitions(\n\t\tdefs: Map<string, HelperDefinition>,\n\t): void;\n\n\t// ── Public API ───────────────────────────────────────────────────────\n\n\t/**\n\t * Returns all definitions as a `Map<name, HelperDefinition>`.\n\t * The map is lazily built and cached on first access.\n\t */\n\tgetDefinitions(): Map<string, HelperDefinition> {\n\t\tif (!this._definitions) {\n\t\t\tthis._definitions = new Map();\n\t\t\tthis.buildDefinitions(this._definitions);\n\t\t}\n\t\treturn this._definitions;\n\t}\n\n\t/**\n\t * Returns the list of all helper names provided by this factory.\n\t */\n\tgetHelperNames(): readonly string[] {\n\t\tif (!this._helperNames) {\n\t\t\tthis._helperNames = [...this.getDefinitions().keys()];\n\t\t}\n\t\treturn this._helperNames;\n\t}\n\n\t/**\n\t * Checks whether a helper name belongs to this factory.\n\t *\n\t * @param name - The helper name to check\n\t */\n\tisHelper(name: string): boolean {\n\t\tif (!this._helperNamesSet) {\n\t\t\tthis._helperNamesSet = new Set(this.getHelperNames());\n\t\t}\n\t\treturn this._helperNamesSet.has(name);\n\t}\n\n\t/**\n\t * Registers all helpers from this factory on the given registry.\n\t *\n\t * @param registry - The engine or target registry\n\t */\n\tregister(registry: HelperRegistry): void {\n\t\tfor (const [name, def] of this.getDefinitions()) {\n\t\t\tregistry.registerHelper(name, def);\n\t\t}\n\t}\n\n\t/**\n\t * Removes all helpers from this factory from the given registry.\n\t *\n\t * @param registry - The engine or target registry\n\t */\n\tunregister(registry: HelperRegistry): void {\n\t\tfor (const name of this.getHelperNames()) {\n\t\t\tregistry.unregisterHelper(name);\n\t\t}\n\t}\n}\n"],"names":["HelperFactory","getDefinitions","_definitions","Map","buildDefinitions","getHelperNames","_helperNames","keys","isHelper","name","_helperNamesSet","Set","has","register","registry","def","registerHelper","unregister","unregisterHelper"],"mappings":"oGAwBsBA,uDAAAA,qMAAf,MAAeA,cAmCrBC,gBAAgD,CAC/C,GAAI,CAAC,IAAI,CAACC,YAAY,CAAE,CACvB,IAAI,CAACA,YAAY,CAAG,IAAIC,IACxB,IAAI,CAACC,gBAAgB,CAAC,IAAI,CAACF,YAAY,CACxC,CACA,OAAO,IAAI,CAACA,YAAY,AACzB,CAKAG,gBAAoC,CACnC,GAAI,CAAC,IAAI,CAACC,YAAY,CAAE,CACvB,IAAI,CAACA,YAAY,CAAG,IAAI,IAAI,CAACL,cAAc,GAAGM,IAAI,GAAG,AACtD,CACA,OAAO,IAAI,CAACD,YAAY,AACzB,CAOAE,SAASC,IAAY,CAAW,CAC/B,GAAI,CAAC,IAAI,CAACC,eAAe,CAAE,CAC1B,IAAI,CAACA,eAAe,CAAG,IAAIC,IAAI,IAAI,CAACN,cAAc,GACnD,CACA,OAAO,IAAI,CAACK,eAAe,CAACE,GAAG,CAACH,KACjC,CAOAI,SAASC,QAAwB,CAAQ,CACxC,IAAK,KAAM,CAACL,KAAMM,IAAI,GAAI,IAAI,CAACd,cAAc,GAAI,CAChDa,SAASE,cAAc,CAACP,KAAMM,IAC/B,CACD,CAOAE,WAAWH,QAAwB,CAAQ,CAC1C,IAAK,MAAML,QAAQ,IAAI,CAACJ,cAAc,GAAI,CACzCS,SAASI,gBAAgB,CAACT,KAC3B,CACD,eAnFA,sBAAQP,eAAqD,MAC7D,sBAAQI,eAAyC,MACjD,sBAAQI,kBAA8C,MAkFvD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get HelperFactory(){return _helperfactory.HelperFactory},get LogicalHelpers(){return _logicalhelpers.LogicalHelpers},get MathHelpers(){return _mathhelpers.MathHelpers},get toNumber(){return _utils.toNumber}});const _helperfactory=require("./helper-factory.js");const _logicalhelpers=require("./logical-helpers.js");const _mathhelpers=require("./math-helpers.js");const _utils=require("./utils.js");
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/index.ts"],"sourcesContent":["export { HelperFactory, type HelperRegistry } from \"./helper-factory\";\nexport { LogicalHelpers } from \"./logical-helpers\";\nexport { MathHelpers } from \"./math-helpers\";\nexport { toNumber } from \"./utils\";\n"],"names":["HelperFactory","LogicalHelpers","MathHelpers","toNumber"],"mappings":"mPAASA,uBAAAA,4BAAa,MACbC,wBAAAA,8BAAc,MACdC,qBAAAA,wBAAW,MACXC,kBAAAA,eAAQ,iCAHkC,kDACpB,gDACH,uCACH"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { HelperDefinition } from "../types";
|
|
2
|
-
import { HelperFactory } from "./helper-factory";
|
|
1
|
+
import type { HelperDefinition } from "../types.js";
|
|
2
|
+
import { HelperFactory } from "./helper-factory.js";
|
|
3
3
|
export declare class LogicalHelpers extends HelperFactory {
|
|
4
4
|
protected buildDefinitions(defs: Map<string, HelperDefinition>): void;
|
|
5
5
|
/** Registers eq, ne / neq */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"LogicalHelpers",{enumerable:true,get:function(){return LogicalHelpers}});const _helperfactoryts=require("./helper-factory.js");const _utilsts=require("./utils.js");const SUPPORTED_OPERATORS=new Set(["==","===","!=","!==","<","<=",">",">="]);function applyOperator(a,op,b){switch(op){case"==":return a==b;case"===":return a===b;case"!=":return a!=b;case"!==":return a!==b;case"<":return(0,_utilsts.toNumber)(a)<(0,_utilsts.toNumber)(b);case"<=":return(0,_utilsts.toNumber)(a)<=(0,_utilsts.toNumber)(b);case">":return(0,_utilsts.toNumber)(a)>(0,_utilsts.toNumber)(b);case">=":return(0,_utilsts.toNumber)(a)>=(0,_utilsts.toNumber)(b)}}function isHandlebarsOptions(value){return value!==null&&typeof value==="object"&&"hash"in value&&"name"in value}class LogicalHelpers extends _helperfactoryts.HelperFactory{buildDefinitions(defs){this.registerEquality(defs);this.registerComparison(defs);this.registerLogicalOperators(defs);this.registerCollectionHelpers(defs);this.registerGenericCompare(defs)}registerEquality(defs){defs.set("eq",{fn:(a,b)=>a===b,params:[{name:"a",description:"Left value"},{name:"b",description:"Right value"}],returnType:{type:"boolean"},description:"Returns true if a is strictly equal to b: {{#if (eq a b)}}"});const neDef={fn:(a,b)=>a!==b,params:[{name:"a",description:"Left value"},{name:"b",description:"Right value"}],returnType:{type:"boolean"},description:"Returns true if a is not strictly equal to b: {{#if (ne a b)}}"};defs.set("ne",neDef);defs.set("neq",neDef)}registerComparison(defs){defs.set("lt",{fn:(a,b)=>(0,_utilsts.toNumber)(a)<(0,_utilsts.toNumber)(b),params:[{name:"a",type:{type:"number"},description:"Left operand"},{name:"b",type:{type:"number"},description:"Right operand"}],returnType:{type:"boolean"},description:"Returns true if a < b: {{#if (lt a b)}}"});const lteDef={fn:(a,b)=>(0,_utilsts.toNumber)(a)<=(0,_utilsts.toNumber)(b),params:[{name:"a",type:{type:"number"},description:"Left operand"},{name:"b",type:{type:"number"},description:"Right operand"}],returnType:{type:"boolean"},description:"Returns true if a <= b: {{#if (lte a b)}}"};defs.set("lte",lteDef);defs.set("le",lteDef);defs.set("gt",{fn:(a,b)=>(0,_utilsts.toNumber)(a)>(0,_utilsts.toNumber)(b),params:[{name:"a",type:{type:"number"},description:"Left operand"},{name:"b",type:{type:"number"},description:"Right operand"}],returnType:{type:"boolean"},description:"Returns true if a > b: {{#if (gt a b)}}"});const gteDef={fn:(a,b)=>(0,_utilsts.toNumber)(a)>=(0,_utilsts.toNumber)(b),params:[{name:"a",type:{type:"number"},description:"Left operand"},{name:"b",type:{type:"number"},description:"Right operand"}],returnType:{type:"boolean"},description:"Returns true if a >= b: {{#if (gte a b)}}"};defs.set("gte",gteDef);defs.set("ge",gteDef)}registerLogicalOperators(defs){defs.set("not",{fn:value=>!value,params:[{name:"value",description:"Value to negate"}],returnType:{type:"boolean"},description:"Returns true if the value is falsy: {{#if (not active)}}"});defs.set("and",{fn:(a,b)=>!!a&&!!b,params:[{name:"a",description:"First condition"},{name:"b",description:"Second condition"}],returnType:{type:"boolean"},description:"Returns true if both values are truthy: {{#if (and a b)}}"});defs.set("or",{fn:(a,b)=>!!a||!!b,params:[{name:"a",description:"First condition"},{name:"b",description:"Second condition"}],returnType:{type:"boolean"},description:"Returns true if at least one value is truthy: {{#if (or a b)}}"})}registerCollectionHelpers(defs){defs.set("contains",{fn:(haystack,needle)=>{if(typeof haystack==="string"){return haystack.includes(String(needle))}if(Array.isArray(haystack)){return haystack.includes(needle)}return false},params:[{name:"haystack",description:"String or array to search in"},{name:"needle",description:"Value to search for"}],returnType:{type:"boolean"},description:'Checks if a string contains a substring or an array contains an element: {{#if (contains name "ali")}}'});defs.set("in",{fn:(...args)=>{if(args.length<2)return false;const value=args[0];const candidates=args.slice(1).filter(a=>!isHandlebarsOptions(a));return candidates.some(c=>c===value)},params:[{name:"value",description:"Value to look for"},{name:"candidates",description:'One or more candidate values (variadic): {{#if (in status "active" "pending")}}'}],returnType:{type:"boolean"},description:'Checks if a value is one of the provided options: {{#if (in status "active" "pending" "draft")}}'})}registerGenericCompare(defs){defs.set("compare",{fn:(a,operator,b)=>{const op=String(operator);if(!SUPPORTED_OPERATORS.has(op)){throw new Error(`[compare helper] Unknown operator "${op}". `+`Supported: ${[...SUPPORTED_OPERATORS].join(", ")} `)}return applyOperator(a,op,b)},params:[{name:"a",description:"Left operand"},{name:"operator",type:{type:"string",enum:["==","===","!=","!==","<","<=",">",">="]},description:'Comparison operator: "==", "===", "!=", "!==", "<", "<=", ">", ">="'},{name:"b",description:"Right operand"}],returnType:{type:"boolean"},description:'Generic comparison helper with operator as parameter: {{#if (compare a "<" b)}}. '+"Supported operators: ==, ===, !=, !==, <, <=, >, >="})}}
|
|
2
|
+
//# sourceMappingURL=logical-helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/logical-helpers.ts"],"sourcesContent":["import type { HelperDefinition } from \"../types.ts\";\nimport { HelperFactory } from \"./helper-factory.ts\";\nimport { toNumber } from \"./utils.ts\";\n\n// ─── LogicalHelpers ──────────────────────────────────────────────────────────\n// Aggregates all logical / comparison helpers for the template engine.\n//\n// Provides two kinds of helpers:\n//\n// 1. **Named helpers** — one helper per operation (`eq`, `lt`, `not`, …)\n// Usage: `{{#if (eq status \"active\")}}`, `{{#if (lt price 100)}}`\n//\n// 2. **Generic `compare` helper** — single helper with the operator as a param\n// Usage: `{{#if (compare a \"<\" b)}}`, `{{#if (compare name \"==\" \"Alice\")}}`\n//\n// ─── Registration ────────────────────────────────────────────────────────────\n// LogicalHelpers are automatically pre-registered by the `Typebars` constructor.\n// They can also be registered manually on any object implementing\n// `HelperRegistry`:\n//\n// const factory = new LogicalHelpers();\n// factory.register(engine); // registers all helpers\n// factory.unregister(engine); // removes all helpers\n//\n// ─── Supported operators (generic `compare` helper) ──────────────────────────\n// == Loose equality\n// === Strict equality\n// != Loose inequality\n// !== Strict inequality\n// < Less than\n// <= Less than or equal\n// > Greater than\n// >= Greater than or equal\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Operators supported by the generic `compare` helper */\ntype CompareOperator = \"==\" | \"===\" | \"!=\" | \"!==\" | \"<\" | \"<=\" | \">\" | \">=\";\n\nconst SUPPORTED_OPERATORS = new Set<string>([\n\t\"==\",\n\t\"===\",\n\t\"!=\",\n\t\"!==\",\n\t\"<\",\n\t\"<=\",\n\t\">\",\n\t\">=\",\n]);\n\n// ─── Internal utilities ─────────────────────────────────────────────────────\n\n/**\n * Applies a comparison operator to two operands.\n */\nfunction applyOperator(a: unknown, op: CompareOperator, b: unknown): boolean {\n\tswitch (op) {\n\t\tcase \"==\":\n\t\t\t// biome-ignore lint/suspicious/noDoubleEquals: intentional loose equality\n\t\t\treturn a == b;\n\t\tcase \"===\":\n\t\t\treturn a === b;\n\t\tcase \"!=\":\n\t\t\t// biome-ignore lint/suspicious/noDoubleEquals: intentional loose inequality\n\t\t\treturn a != b;\n\t\tcase \"!==\":\n\t\t\treturn a !== b;\n\t\tcase \"<\":\n\t\t\treturn toNumber(a) < toNumber(b);\n\t\tcase \"<=\":\n\t\t\treturn toNumber(a) <= toNumber(b);\n\t\tcase \">\":\n\t\t\treturn toNumber(a) > toNumber(b);\n\t\tcase \">=\":\n\t\t\treturn toNumber(a) >= toNumber(b);\n\t}\n}\n\n/**\n * Checks whether a value is a Handlebars options object.\n * Handlebars always passes an options object as the last argument to helpers.\n */\nfunction isHandlebarsOptions(value: unknown): boolean {\n\treturn (\n\t\tvalue !== null &&\n\t\ttypeof value === \"object\" &&\n\t\t\"hash\" in (value as Record<string, unknown>) &&\n\t\t\"name\" in (value as Record<string, unknown>)\n\t);\n}\n\n// ─── Main class ─────────────────────────────────────────────────────────────\n\nexport class LogicalHelpers extends HelperFactory {\n\t// ─── buildDefinitions (required by HelperFactory) ──────────────────\n\n\tprotected buildDefinitions(defs: Map<string, HelperDefinition>): void {\n\t\tthis.registerEquality(defs);\n\t\tthis.registerComparison(defs);\n\t\tthis.registerLogicalOperators(defs);\n\t\tthis.registerCollectionHelpers(defs);\n\t\tthis.registerGenericCompare(defs);\n\t}\n\n\t// ── Equality helpers ─────────────────────────────────────────────\n\n\t/** Registers eq, ne / neq */\n\tprivate registerEquality(defs: Map<string, HelperDefinition>): void {\n\t\t// eq — Strict equality: {{#if (eq a b)}}\n\t\tdefs.set(\"eq\", {\n\t\t\tfn: (a: unknown, b: unknown) => a === b,\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", description: \"Left value\" },\n\t\t\t\t{ name: \"b\", description: \"Right value\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if a is strictly equal to b: {{#if (eq a b)}}\",\n\t\t});\n\n\t\t// ne / neq — Strict inequality: {{#if (ne a b)}}\n\t\tconst neDef: HelperDefinition = {\n\t\t\tfn: (a: unknown, b: unknown) => a !== b,\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", description: \"Left value\" },\n\t\t\t\t{ name: \"b\", description: \"Right value\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription:\n\t\t\t\t\"Returns true if a is not strictly equal to b: {{#if (ne a b)}}\",\n\t\t};\n\t\tdefs.set(\"ne\", neDef);\n\t\tdefs.set(\"neq\", neDef);\n\t}\n\n\t// ── Comparison helpers ───────────────────────────────────────────\n\n\t/** Registers lt, lte / le, gt, gte / ge */\n\tprivate registerComparison(defs: Map<string, HelperDefinition>): void {\n\t\t// lt — Less than: {{#if (lt a b)}}\n\t\tdefs.set(\"lt\", {\n\t\t\tfn: (a: unknown, b: unknown) => toNumber(a) < toNumber(b),\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", type: { type: \"number\" }, description: \"Left operand\" },\n\t\t\t\t{ name: \"b\", type: { type: \"number\" }, description: \"Right operand\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if a < b: {{#if (lt a b)}}\",\n\t\t});\n\n\t\t// lte / le — Less than or equal: {{#if (lte a b)}}\n\t\tconst lteDef: HelperDefinition = {\n\t\t\tfn: (a: unknown, b: unknown) => toNumber(a) <= toNumber(b),\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", type: { type: \"number\" }, description: \"Left operand\" },\n\t\t\t\t{ name: \"b\", type: { type: \"number\" }, description: \"Right operand\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if a <= b: {{#if (lte a b)}}\",\n\t\t};\n\t\tdefs.set(\"lte\", lteDef);\n\t\tdefs.set(\"le\", lteDef);\n\n\t\t// gt — Greater than: {{#if (gt a b)}}\n\t\tdefs.set(\"gt\", {\n\t\t\tfn: (a: unknown, b: unknown) => toNumber(a) > toNumber(b),\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", type: { type: \"number\" }, description: \"Left operand\" },\n\t\t\t\t{ name: \"b\", type: { type: \"number\" }, description: \"Right operand\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if a > b: {{#if (gt a b)}}\",\n\t\t});\n\n\t\t// gte / ge — Greater than or equal: {{#if (gte a b)}}\n\t\tconst gteDef: HelperDefinition = {\n\t\t\tfn: (a: unknown, b: unknown) => toNumber(a) >= toNumber(b),\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", type: { type: \"number\" }, description: \"Left operand\" },\n\t\t\t\t{ name: \"b\", type: { type: \"number\" }, description: \"Right operand\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if a >= b: {{#if (gte a b)}}\",\n\t\t};\n\t\tdefs.set(\"gte\", gteDef);\n\t\tdefs.set(\"ge\", gteDef);\n\t}\n\n\t// ── Logical operators ────────────────────────────────────────────\n\n\t/** Registers not, and, or */\n\tprivate registerLogicalOperators(defs: Map<string, HelperDefinition>): void {\n\t\t// not — Logical negation: {{#if (not active)}}\n\t\tdefs.set(\"not\", {\n\t\t\tfn: (value: unknown) => !value,\n\t\t\tparams: [{ name: \"value\", description: \"Value to negate\" }],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if the value is falsy: {{#if (not active)}}\",\n\t\t});\n\n\t\t// and — Logical AND: {{#if (and a b)}}\n\t\tdefs.set(\"and\", {\n\t\t\tfn: (a: unknown, b: unknown) => !!a && !!b,\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", description: \"First condition\" },\n\t\t\t\t{ name: \"b\", description: \"Second condition\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription: \"Returns true if both values are truthy: {{#if (and a b)}}\",\n\t\t});\n\n\t\t// or — Logical OR: {{#if (or a b)}}\n\t\tdefs.set(\"or\", {\n\t\t\tfn: (a: unknown, b: unknown) => !!a || !!b,\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", description: \"First condition\" },\n\t\t\t\t{ name: \"b\", description: \"Second condition\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription:\n\t\t\t\t\"Returns true if at least one value is truthy: {{#if (or a b)}}\",\n\t\t});\n\t}\n\n\t// ── Collection / String helpers ──────────────────────────────────\n\n\t/** Registers contains, in */\n\tprivate registerCollectionHelpers(defs: Map<string, HelperDefinition>): void {\n\t\t// contains — Checks if a string contains a substring or an array contains an element\n\t\t// Usage: {{#if (contains name \"ali\")}} or {{#if (contains tags \"admin\")}}\n\t\tdefs.set(\"contains\", {\n\t\t\tfn: (haystack: unknown, needle: unknown) => {\n\t\t\t\tif (typeof haystack === \"string\") {\n\t\t\t\t\treturn haystack.includes(String(needle));\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(haystack)) {\n\t\t\t\t\treturn haystack.includes(needle);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"haystack\",\n\t\t\t\t\tdescription: \"String or array to search in\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"needle\",\n\t\t\t\t\tdescription: \"Value to search for\",\n\t\t\t\t},\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription:\n\t\t\t\t'Checks if a string contains a substring or an array contains an element: {{#if (contains name \"ali\")}}',\n\t\t});\n\n\t\t// in — Checks if a value is one of the provided options (variadic)\n\t\t// Usage: {{#if (in status \"active\" \"pending\" \"draft\")}}\n\t\tdefs.set(\"in\", {\n\t\t\tfn: (...args: unknown[]) => {\n\t\t\t\t// Handlebars always passes an options object as the last argument.\n\t\t\t\t// We need to exclude it from the candidate list.\n\t\t\t\tif (args.length < 2) return false;\n\n\t\t\t\tconst value = args[0];\n\t\t\t\t// Filter out the trailing Handlebars options object\n\t\t\t\tconst candidates = args.slice(1).filter((a) => !isHandlebarsOptions(a));\n\n\t\t\t\treturn candidates.some((c) => c === value);\n\t\t\t},\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"value\",\n\t\t\t\t\tdescription: \"Value to look for\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"candidates\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t'One or more candidate values (variadic): {{#if (in status \"active\" \"pending\")}}',\n\t\t\t\t},\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription:\n\t\t\t\t'Checks if a value is one of the provided options: {{#if (in status \"active\" \"pending\" \"draft\")}}',\n\t\t});\n\t}\n\n\t// ── Generic helper ───────────────────────────────────────────────\n\n\t/** Registers the generic `compare` helper with operator as a parameter */\n\tprivate registerGenericCompare(defs: Map<string, HelperDefinition>): void {\n\t\t// Usage: {{#if (compare a \"<\" b)}}, {{#if (compare name \"===\" \"Alice\")}}\n\t\tdefs.set(\"compare\", {\n\t\t\tfn: (a: unknown, operator: unknown, b: unknown) => {\n\t\t\t\tconst op = String(operator);\n\t\t\t\tif (!SUPPORTED_OPERATORS.has(op)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`[compare helper] Unknown operator \"${op}\". ` +\n\t\t\t\t\t\t\t`Supported: ${[...SUPPORTED_OPERATORS].join(\", \")} `,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn applyOperator(a, op as CompareOperator, b);\n\t\t\t},\n\t\t\tparams: [\n\t\t\t\t{ name: \"a\", description: \"Left operand\" },\n\t\t\t\t{\n\t\t\t\t\tname: \"operator\",\n\t\t\t\t\ttype: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tenum: [\"==\", \"===\", \"!=\", \"!==\", \"<\", \"<=\", \">\", \">=\"],\n\t\t\t\t\t},\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t'Comparison operator: \"==\", \"===\", \"!=\", \"!==\", \"<\", \"<=\", \">\", \">=\"',\n\t\t\t\t},\n\t\t\t\t{ name: \"b\", description: \"Right operand\" },\n\t\t\t],\n\t\t\treturnType: { type: \"boolean\" },\n\t\t\tdescription:\n\t\t\t\t'Generic comparison helper with operator as parameter: {{#if (compare a \"<\" b)}}. ' +\n\t\t\t\t\"Supported operators: ==, ===, !=, !==, <, <=, >, >=\",\n\t\t});\n\t}\n}\n"],"names":["LogicalHelpers","SUPPORTED_OPERATORS","Set","applyOperator","a","op","b","toNumber","isHandlebarsOptions","value","HelperFactory","buildDefinitions","defs","registerEquality","registerComparison","registerLogicalOperators","registerCollectionHelpers","registerGenericCompare","set","fn","params","name","description","returnType","type","neDef","lteDef","gteDef","haystack","needle","includes","String","Array","isArray","args","length","candidates","slice","filter","some","c","operator","has","Error","join","enum"],"mappings":"oGA6FaA,wDAAAA,iDA5FiB,8CACL,cAqCzB,MAAMC,oBAAsB,IAAIC,IAAY,CAC3C,KACA,MACA,KACA,MACA,IACA,KACA,IACA,KACA,EAOD,SAASC,cAAcC,CAAU,CAAEC,EAAmB,CAAEC,CAAU,EACjE,OAAQD,IACP,IAAK,KAEJ,OAAOD,GAAKE,CACb,KAAK,MACJ,OAAOF,IAAME,CACd,KAAK,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FACA,qDACF,EACD,CACD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { HelperDefinition } from "../types";
|
|
2
|
-
import { HelperFactory } from "./helper-factory";
|
|
1
|
+
import type { HelperDefinition } from "../types.js";
|
|
2
|
+
import { HelperFactory } from "./helper-factory.js";
|
|
3
3
|
export declare class MathHelpers extends HelperFactory {
|
|
4
4
|
protected buildDefinitions(defs: Map<string, HelperDefinition>): void;
|
|
5
5
|
/** Registers add, subtract/sub, multiply/mul, divide/div, modulo/mod, pow */
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"MathHelpers",{enumerable:true,get:function(){return MathHelpers}});const _helperfactoryts=require("./helper-factory.js");const _utilsts=require("./utils.js");const SUPPORTED_OPERATORS=new Set(["+","-","*","/","%","**"]);const num=value=>(0,_utilsts.toNumber)(value,0);function applyOperator(a,op,b){switch(op){case"+":return a+b;case"-":return a-b;case"*":return a*b;case"/":return b===0?Infinity:a/b;case"%":return b===0?NaN:a%b;case"**":return a**b}}class MathHelpers extends _helperfactoryts.HelperFactory{buildDefinitions(defs){this.registerBinaryOperators(defs);this.registerUnaryFunctions(defs);this.registerMinMax(defs);this.registerGenericMath(defs)}registerBinaryOperators(defs){const addDef={fn:(a,b)=>num(a)+num(b),params:[{name:"a",type:{type:"number"},description:"First operand"},{name:"b",type:{type:"number"},description:"Second operand"}],returnType:{type:"number"},description:"Adds two numbers: {{ add a b }}"};defs.set("add",addDef);const subtractDef={fn:(a,b)=>num(a)-num(b),params:[{name:"a",type:{type:"number"},description:"Value to subtract from"},{name:"b",type:{type:"number"},description:"Value to subtract"}],returnType:{type:"number"},description:"Subtracts b from a: {{ subtract a b }}"};defs.set("subtract",subtractDef);defs.set("sub",subtractDef);const multiplyDef={fn:(a,b)=>num(a)*num(b),params:[{name:"a",type:{type:"number"},description:"First factor"},{name:"b",type:{type:"number"},description:"Second factor"}],returnType:{type:"number"},description:"Multiplies two numbers: {{ multiply a b }}"};defs.set("multiply",multiplyDef);defs.set("mul",multiplyDef);const divideDef={fn:(a,b)=>{const divisor=num(b);return divisor===0?Infinity:num(a)/divisor},params:[{name:"a",type:{type:"number"},description:"Dividend"},{name:"b",type:{type:"number"},description:"Divisor"}],returnType:{type:"number"},description:"Divides a by b: {{ divide a b }}. Returns Infinity if b is 0."};defs.set("divide",divideDef);defs.set("div",divideDef);const moduloDef={fn:(a,b)=>{const divisor=num(b);return divisor===0?NaN:num(a)%divisor},params:[{name:"a",type:{type:"number"},description:"Dividend"},{name:"b",type:{type:"number"},description:"Divisor"}],returnType:{type:"number"},description:"Returns the remainder of a divided by b: {{ modulo a b }}"};defs.set("modulo",moduloDef);defs.set("mod",moduloDef);defs.set("pow",{fn:(base,exponent)=>num(base)**num(exponent),params:[{name:"base",type:{type:"number"},description:"The base"},{name:"exponent",type:{type:"number"},description:"The exponent"}],returnType:{type:"number"},description:"Raises base to the power of exponent: {{ pow base exponent }}"})}registerUnaryFunctions(defs){defs.set("abs",{fn:value=>Math.abs(num(value)),params:[{name:"value",type:{type:"number"},description:"The number"}],returnType:{type:"number"},description:"Returns the absolute value: {{ abs value }}"});defs.set("ceil",{fn:value=>Math.ceil(num(value)),params:[{name:"value",type:{type:"number"},description:"The number to round up"}],returnType:{type:"number"},description:"Rounds up to the nearest integer: {{ ceil value }}"});defs.set("floor",{fn:value=>Math.floor(num(value)),params:[{name:"value",type:{type:"number"},description:"The number to round down"}],returnType:{type:"number"},description:"Rounds down to the nearest integer: {{ floor value }}"});defs.set("round",{fn:(value,precision)=>{const n=num(value);if(precision===undefined||precision===null||typeof precision==="object"){return Math.round(n)}const p=num(precision);const factor=10**p;return Math.round(n*factor)/factor},params:[{name:"value",type:{type:"number"},description:"The number to round"},{name:"precision",type:{type:"number"},description:"Number of decimal places (default: 0)",optional:true}],returnType:{type:"number"},description:"Rounds to the nearest integer or to a given precision: {{ round value }} or {{ round value 2 }}"});defs.set("sqrt",{fn:value=>Math.sqrt(num(value)),params:[{name:"value",type:{type:"number"},description:"The number"}],returnType:{type:"number"},description:"Returns the square root: {{ sqrt value }}"})}registerMinMax(defs){defs.set("min",{fn:(a,b)=>Math.min(num(a),num(b)),params:[{name:"a",type:{type:"number"},description:"First number"},{name:"b",type:{type:"number"},description:"Second number"}],returnType:{type:"number"},description:"Returns the smaller of two numbers: {{ min a b }}"});defs.set("max",{fn:(a,b)=>Math.max(num(a),num(b)),params:[{name:"a",type:{type:"number"},description:"First number"},{name:"b",type:{type:"number"},description:"Second number"}],returnType:{type:"number"},description:"Returns the larger of two numbers: {{ max a b }}"})}registerGenericMath(defs){defs.set("math",{fn:(a,operator,b)=>{const op=String(operator);if(!SUPPORTED_OPERATORS.has(op)){throw new Error(`[math helper] Unknown operator "${op}". `+`Supported: ${[...SUPPORTED_OPERATORS].join(", ")} `)}return applyOperator(num(a),op,num(b))},params:[{name:"a",type:{type:"number"},description:"Left operand"},{name:"operator",type:{type:"string",enum:["+","-","*","/","%","**"]},description:'Arithmetic operator: "+", "-", "*", "/", "%", "**"'},{name:"b",type:{type:"number"},description:"Right operand"}],returnType:{type:"number"},description:'Generic math helper with operator as parameter: {{ math a "+" b }}, {{ math a "/" b }}. '+"Supported operators: +, -, *, /, %, **"})}}
|
|
2
|
+
//# sourceMappingURL=math-helpers.js.map
|