typebars 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/cjs/analyzer.js +1 -1
  2. package/dist/cjs/analyzer.js.map +1 -1
  3. package/dist/cjs/compiled-template.js +1 -1
  4. package/dist/cjs/compiled-template.js.map +1 -1
  5. package/dist/cjs/dispatch.d.ts +4 -0
  6. package/dist/cjs/dispatch.js +1 -1
  7. package/dist/cjs/dispatch.js.map +1 -1
  8. package/dist/cjs/executor.d.ts +3 -1
  9. package/dist/cjs/executor.js +1 -1
  10. package/dist/cjs/executor.js.map +1 -1
  11. package/dist/cjs/helpers/collection-helpers.d.ts +9 -0
  12. package/dist/cjs/helpers/collection-helpers.js +2 -0
  13. package/dist/cjs/helpers/collection-helpers.js.map +1 -0
  14. package/dist/cjs/helpers/index.d.ts +1 -0
  15. package/dist/cjs/helpers/index.js +1 -1
  16. package/dist/cjs/helpers/index.js.map +1 -1
  17. package/dist/cjs/schema-resolver.js +1 -1
  18. package/dist/cjs/schema-resolver.js.map +1 -1
  19. package/dist/cjs/typebars.js +1 -1
  20. package/dist/cjs/typebars.js.map +1 -1
  21. package/dist/cjs/types.d.ts +18 -0
  22. package/dist/cjs/types.js.map +1 -1
  23. package/dist/esm/analyzer.js +1 -1
  24. package/dist/esm/analyzer.js.map +1 -1
  25. package/dist/esm/compiled-template.js +1 -1
  26. package/dist/esm/compiled-template.js.map +1 -1
  27. package/dist/esm/dispatch.d.ts +4 -0
  28. package/dist/esm/dispatch.js +1 -1
  29. package/dist/esm/dispatch.js.map +1 -1
  30. package/dist/esm/executor.d.ts +3 -1
  31. package/dist/esm/executor.js +1 -1
  32. package/dist/esm/executor.js.map +1 -1
  33. package/dist/esm/helpers/collection-helpers.d.ts +9 -0
  34. package/dist/esm/helpers/collection-helpers.js +2 -0
  35. package/dist/esm/helpers/collection-helpers.js.map +1 -0
  36. package/dist/esm/helpers/index.d.ts +1 -0
  37. package/dist/esm/helpers/index.js +1 -1
  38. package/dist/esm/helpers/index.js.map +1 -1
  39. package/dist/esm/schema-resolver.js +1 -1
  40. package/dist/esm/schema-resolver.js.map +1 -1
  41. package/dist/esm/typebars.js +1 -1
  42. package/dist/esm/typebars.js.map +1 -1
  43. package/dist/esm/types.d.ts +18 -0
  44. package/dist/esm/types.js.map +1 -1
  45. package/package.json +1 -1
@@ -13,6 +13,8 @@ export interface DispatchAnalyzeOptions {
13
13
  export interface DispatchExecuteOptions {
14
14
  /** Explicit coercion schema for output type coercion */
15
15
  coerceSchema?: JSONSchema7;
16
+ /** When true, exclude entries containing Handlebars expressions */
17
+ excludeTemplateExpression?: boolean;
16
18
  }
17
19
  /**
18
20
  * Dispatches a `TemplateInput` for analysis, handling the array/object/literal
@@ -47,6 +49,8 @@ export interface DispatchAnalyzeAndExecuteOptions {
47
49
  identifierSchemas?: Record<number, JSONSchema7>;
48
50
  identifierData?: Record<number, Record<string, unknown>>;
49
51
  coerceSchema?: JSONSchema7;
52
+ /** When true, exclude entries containing Handlebars expressions */
53
+ excludeTemplateExpression?: boolean;
50
54
  }
51
55
  /**
52
56
  * Dispatches a `TemplateInput` for combined analysis and execution,
@@ -1,2 +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 dispatchAnalyze(){return dispatchAnalyze},get dispatchAnalyzeAndExecute(){return dispatchAnalyzeAndExecute},get dispatchExecute(){return dispatchExecute},get resolveChildCoerceSchema(){return resolveChildCoerceSchema},get shouldExcludeEntry(){return shouldExcludeEntry}});const _parserts=require("./parser.js");const _schemaresolverts=require("./schema-resolver.js");const _typests=require("./types.js");const _utilsts=require("./utils.js");function dispatchAnalyze(template,options,analyzeString,recurse){if((0,_typests.isArrayInput)(template)){const exclude=options?.excludeTemplateExpression===true;if(exclude){const kept=template.filter(item=>!shouldExcludeEntry(item));return(0,_utilsts.aggregateArrayAnalysis)(kept.length,index=>recurse(kept[index],options))}return(0,_utilsts.aggregateArrayAnalysis)(template.length,index=>recurse(template[index],options))}if((0,_typests.isObjectInput)(template)){return dispatchObjectAnalysis(template,options,recurse)}if((0,_typests.isLiteralInput)(template)){return{valid:true,diagnostics:[],outputSchema:(0,_typests.inferPrimitiveSchema)(template)}}return analyzeString(template,options?.coerceSchema)}function dispatchObjectAnalysis(template,options,recurse){const coerceSchema=options?.coerceSchema;const exclude=options?.excludeTemplateExpression===true;const keys=exclude?Object.keys(template).filter(key=>!shouldExcludeEntry(template[key])):Object.keys(template);return(0,_utilsts.aggregateObjectAnalysis)(keys,key=>{const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);return recurse(template[key],{identifierSchemas:options?.identifierSchemas,coerceSchema:childCoerceSchema,excludeTemplateExpression:options?.excludeTemplateExpression})})}function dispatchExecute(template,options,executeString,recurse){if((0,_typests.isArrayInput)(template)){const result=[];for(const element of template){result.push(recurse(element,options))}return result}if((0,_typests.isObjectInput)(template)){const coerceSchema=options?.coerceSchema;const result={};for(const[key,value]of Object.entries(template)){const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);result[key]=recurse(value,{...options,coerceSchema:childCoerceSchema})}return result}if((0,_typests.isLiteralInput)(template))return template;return executeString(template,options?.coerceSchema)}function dispatchAnalyzeAndExecute(template,options,processString,recurse){if((0,_typests.isArrayInput)(template)){return(0,_utilsts.aggregateArrayAnalysisAndExecution)(template.length,index=>recurse(template[index],options))}if((0,_typests.isObjectInput)(template)){const coerceSchema=options?.coerceSchema;return(0,_utilsts.aggregateObjectAnalysisAndExecution)(Object.keys(template),key=>{const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);return recurse(template[key],{identifierSchemas:options?.identifierSchemas,identifierData:options?.identifierData,coerceSchema:childCoerceSchema})})}if((0,_typests.isLiteralInput)(template)){return{analysis:{valid:true,diagnostics:[],outputSchema:(0,_typests.inferPrimitiveSchema)(template)},value:template}}return processString(template,options?.coerceSchema)}function resolveChildCoerceSchema(coerceSchema,key){return coerceSchema?(0,_schemaresolverts.resolveSchemaPath)(coerceSchema,[key]):undefined}function shouldExcludeEntry(input){return typeof input==="string"&&(0,_parserts.hasHandlebarsExpression)(input)}
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 dispatchAnalyze(){return dispatchAnalyze},get dispatchAnalyzeAndExecute(){return dispatchAnalyzeAndExecute},get dispatchExecute(){return dispatchExecute},get resolveChildCoerceSchema(){return resolveChildCoerceSchema},get shouldExcludeEntry(){return shouldExcludeEntry}});const _parserts=require("./parser.js");const _schemaresolverts=require("./schema-resolver.js");const _typests=require("./types.js");const _utilsts=require("./utils.js");function dispatchAnalyze(template,options,analyzeString,recurse){if((0,_typests.isArrayInput)(template)){const exclude=options?.excludeTemplateExpression===true;if(exclude){const kept=template.filter(item=>!shouldExcludeEntry(item));return(0,_utilsts.aggregateArrayAnalysis)(kept.length,index=>recurse(kept[index],options))}return(0,_utilsts.aggregateArrayAnalysis)(template.length,index=>recurse(template[index],options))}if((0,_typests.isObjectInput)(template)){return dispatchObjectAnalysis(template,options,recurse)}if((0,_typests.isLiteralInput)(template)){return{valid:true,diagnostics:[],outputSchema:(0,_typests.inferPrimitiveSchema)(template)}}return analyzeString(template,options?.coerceSchema)}function dispatchObjectAnalysis(template,options,recurse){const coerceSchema=options?.coerceSchema;const exclude=options?.excludeTemplateExpression===true;const keys=exclude?Object.keys(template).filter(key=>!shouldExcludeEntry(template[key])):Object.keys(template);return(0,_utilsts.aggregateObjectAnalysis)(keys,key=>{const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);return recurse(template[key],{identifierSchemas:options?.identifierSchemas,coerceSchema:childCoerceSchema,excludeTemplateExpression:options?.excludeTemplateExpression})})}function dispatchExecute(template,options,executeString,recurse){const exclude=options?.excludeTemplateExpression===true;if((0,_typests.isArrayInput)(template)){const elements=exclude?template.filter(item=>!shouldExcludeEntry(item)):template;const result=[];for(const element of elements){result.push(recurse(element,options))}return result}if((0,_typests.isObjectInput)(template)){const coerceSchema=options?.coerceSchema;const result={};const keys=exclude?Object.keys(template).filter(key=>!shouldExcludeEntry(template[key])):Object.keys(template);for(const key of keys){const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);result[key]=recurse(template[key],{...options,coerceSchema:childCoerceSchema})}return result}if((0,_typests.isLiteralInput)(template))return template;if(exclude&&shouldExcludeEntry(template)){return null}return executeString(template,options?.coerceSchema)}function dispatchAnalyzeAndExecute(template,options,processString,recurse){const exclude=options?.excludeTemplateExpression===true;if((0,_typests.isArrayInput)(template)){const elements=exclude?template.filter(item=>!shouldExcludeEntry(item)):template;return(0,_utilsts.aggregateArrayAnalysisAndExecution)(elements.length,index=>recurse(elements[index],options))}if((0,_typests.isObjectInput)(template)){const coerceSchema=options?.coerceSchema;const keys=exclude?Object.keys(template).filter(key=>!shouldExcludeEntry(template[key])):Object.keys(template);return(0,_utilsts.aggregateObjectAnalysisAndExecution)(keys,key=>{const childCoerceSchema=resolveChildCoerceSchema(coerceSchema,key);return recurse(template[key],{identifierSchemas:options?.identifierSchemas,identifierData:options?.identifierData,coerceSchema:childCoerceSchema,excludeTemplateExpression:options?.excludeTemplateExpression})})}if((0,_typests.isLiteralInput)(template)){return{analysis:{valid:true,diagnostics:[],outputSchema:(0,_typests.inferPrimitiveSchema)(template)},value:template}}if(exclude&&shouldExcludeEntry(template)){return{analysis:{valid:true,diagnostics:[],outputSchema:{type:"null"}},value:null}}return processString(template,options?.coerceSchema)}function resolveChildCoerceSchema(coerceSchema,key){return coerceSchema?(0,_schemaresolverts.resolveSchemaPath)(coerceSchema,[key]):undefined}function shouldExcludeEntry(input){return typeof input==="string"&&(0,_parserts.hasHandlebarsExpression)(input)}
2
2
  //# sourceMappingURL=dispatch.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/dispatch.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { hasHandlebarsExpression } from \"./parser.ts\";\nimport { resolveSchemaPath } from \"./schema-resolver.ts\";\nimport type { AnalysisResult, TemplateInput } from \"./types.ts\";\nimport {\n\tinferPrimitiveSchema,\n\tisArrayInput,\n\tisLiteralInput,\n\tisObjectInput,\n} from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n} from \"./utils.ts\";\n\n// ─── Template Input Dispatching ──────────────────────────────────────────────\n// Factorized dispatching for recursive processing of `TemplateInput` values.\n//\n// Every method in the engine (`analyze`, `execute`, `analyzeAndExecute`,\n// `compile`) follows the same recursive pattern:\n//\n// 1. If the input is an **array** → process each element recursively\n// 2. If the input is an **object** → process each property recursively\n// 3. If the input is a **literal** (number, boolean, null) → passthrough\n// 4. If the input is a **string** → delegate to a template-specific handler\n//\n// This module extracts the common dispatching logic into generic functions\n// that accept a callback for the string (template) case. This eliminates\n// the duplication across `Typebars`, `CompiledTemplate`, and `analyzer.ts`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Options controlling recursive dispatching behavior */\nexport interface DispatchAnalyzeOptions {\n\t/** Schemas by template identifier */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Explicit coercion schema for static literal output type */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/** Options controlling recursive execution dispatching */\nexport interface DispatchExecuteOptions {\n\t/** Explicit coercion schema for output type coercion */\n\tcoerceSchema?: JSONSchema7;\n}\n\n// ─── Analysis Dispatching ────────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for analysis, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to analyze\n * @param options - Dispatching options (coerceSchema, excludeTemplateExpression)\n * @param analyzeString - Callback for analyzing a string template.\n * Receives `(template, coerceSchema?)` and must return an `AnalysisResult`.\n * @param recurse - Callback for recursively analyzing a child `TemplateInput`.\n * Receives `(child, options?)` and must return an `AnalysisResult`.\n * This allows callers (like `Typebars`) to rebind `this` or inject\n * additional context on each recursive call.\n * @returns An `AnalysisResult`\n */\nexport function dispatchAnalyze(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeOptions | undefined,\n\tanalyzeString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => AnalysisResult,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\t\tif (exclude) {\n\t\t\tconst kept = template.filter(\n\t\t\t\t(item) => !shouldExcludeEntry(item as TemplateInput),\n\t\t\t);\n\t\t\treturn aggregateArrayAnalysis(kept.length, (index) =>\n\t\t\t\trecurse(kept[index] as TemplateInput, options),\n\t\t\t);\n\t\t}\n\t\treturn aggregateArrayAnalysis(template.length, (index) =>\n\t\t\trecurse(template[index] as TemplateInput, options),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\treturn dispatchObjectAnalysis(template, options, recurse);\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\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\n\t// ── String template ──────────────────────────────────────────────────\n\treturn analyzeString(template, options?.coerceSchema);\n}\n\n/**\n * Dispatches object analysis with `coerceSchema` propagation and\n * `excludeTemplateExpression` filtering.\n *\n * Extracted as a separate function because the object case is the most\n * complex (key filtering + per-key coerceSchema resolution).\n */\nfunction dispatchObjectAnalysis(\n\ttemplate: Record<string, TemplateInput>,\n\toptions: DispatchAnalyzeOptions | undefined,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\tconst coerceSchema = options?.coerceSchema;\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\tconst keys = exclude\n\t\t? Object.keys(template).filter(\n\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t)\n\t\t: Object.keys(template);\n\n\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t});\n\t});\n}\n\n// ─── Execution Dispatching ───────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for execution, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to execute\n * @param options - Dispatching options (coerceSchema)\n * @param executeString - Callback for executing a string template.\n * Receives `(template, coerceSchema?)` and must return the result.\n * @param recurse - Callback for recursively executing a child `TemplateInput`.\n * Receives `(child, options?)` and must return the result.\n * @returns The execution result\n */\nexport function dispatchExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchExecuteOptions | undefined,\n\texecuteString: (template: string, coerceSchema?: JSONSchema7) => unknown,\n\trecurse: (child: TemplateInput, options?: DispatchExecuteOptions) => unknown,\n): unknown {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst result: unknown[] = [];\n\t\tfor (const element of template) {\n\t\t\tresult.push(recurse(element, options));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(template)) {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\tresult[key] = recurse(value, {\n\t\t\t\t...options,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) return template;\n\n\t// ── String template ──────────────────────────────────────────────────\n\treturn executeString(template, options?.coerceSchema);\n}\n\n// ─── Analyze-and-Execute Dispatching ─────────────────────────────────────────\n\n/** Options for combined analyze-and-execute dispatching */\nexport interface DispatchAnalyzeAndExecuteOptions {\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\tcoerceSchema?: JSONSchema7;\n}\n\n/**\n * Dispatches a `TemplateInput` for combined analysis and execution,\n * handling array/object/literal cases generically and delegating\n * the string case to a callback.\n *\n * @param template - The input to process\n * @param options - Options (identifierSchemas, identifierData, coerceSchema)\n * @param processString - Callback for analyzing and executing a string template.\n * Receives `(template, coerceSchema?)` and must return\n * `{ analysis, value }`.\n * @param recurse - Callback for recursively processing a child `TemplateInput`.\n * @returns `{ analysis, value }` where `value` is `undefined` if analysis fails\n */\nexport function dispatchAnalyzeAndExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeAndExecuteOptions | undefined,\n\tprocessString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => { analysis: AnalysisResult; value: unknown },\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeAndExecuteOptions,\n\t) => { analysis: AnalysisResult; value: unknown },\n): { analysis: AnalysisResult; value: unknown } {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\treturn aggregateArrayAnalysisAndExecution(template.length, (index) =>\n\t\t\trecurse(template[index] as TemplateInput, options),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\treturn aggregateObjectAnalysisAndExecution(Object.keys(template), (key) => {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t});\n\t\t});\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t\t},\n\t\t\tvalue: template,\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\treturn processString(template, options?.coerceSchema);\n}\n\n// ─── Internal Utilities ──────────────────────────────────────────────────────\n\n/**\n * Resolves the child `coerceSchema` for a given object key.\n *\n * When a `coerceSchema` is provided, navigates into its `properties`\n * to find the schema for the given key. This allows deeply nested\n * objects to propagate coercion at every level.\n *\n * @param coerceSchema - The parent coercion schema (may be `undefined`)\n * @param key - The object property key\n * @returns The child coercion schema, or `undefined`\n */\nexport function resolveChildCoerceSchema(\n\tcoerceSchema: JSONSchema7 | undefined,\n\tkey: string,\n): JSONSchema7 | undefined {\n\treturn coerceSchema ? resolveSchemaPath(coerceSchema, [key]) : undefined;\n}\n\n/**\n * Determines whether a `TemplateInput` value should be excluded when\n * `excludeTemplateExpression` is enabled.\n *\n * A value is excluded if it is a string containing at least one Handlebars\n * expression (`{{…}}`). Literals (number, boolean, null), plain strings\n * without expressions, objects, and arrays are never excluded at the\n * entry level — objects and arrays are recursively filtered by the\n * dispatching functions themselves.\n *\n * @param input - The template input to check\n * @returns `true` if the input should be excluded\n */\nexport function shouldExcludeEntry(input: TemplateInput): boolean {\n\treturn typeof input === \"string\" && hasHandlebarsExpression(input);\n}\n"],"names":["dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","resolveChildCoerceSchema","shouldExcludeEntry","template","options","analyzeString","recurse","isArrayInput","exclude","excludeTemplateExpression","kept","filter","item","aggregateArrayAnalysis","length","index","isObjectInput","dispatchObjectAnalysis","isLiteralInput","valid","diagnostics","outputSchema","inferPrimitiveSchema","coerceSchema","keys","Object","key","aggregateObjectAnalysis","childCoerceSchema","identifierSchemas","executeString","result","element","push","value","entries","processString","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","analysis","resolveSchemaPath","undefined","input","hasHandlebarsExpression"],"mappings":"mPAkEgBA,yBAAAA,qBAwJAC,mCAAAA,+BA1DAC,yBAAAA,qBAuHAC,kCAAAA,8BAoBAC,4BAAAA,8CA1SwB,+CACN,+CAO3B,qCAMA,cAmDA,SAASJ,gBACfK,QAAuB,CACvBC,OAA2C,CAC3CC,aAGmB,CACnBC,OAGmB,EAGnB,GAAIC,GAAAA,qBAAY,EAACJ,UAAW,CAC3B,MAAMK,QAAUJ,SAASK,4BAA8B,KACvD,GAAID,QAAS,CACZ,MAAME,KAAOP,SAASQ,MAAM,CAC3B,AAACC,MAAS,CAACV,mBAAmBU,OAE/B,MAAOC,GAAAA,+BAAsB,EAACH,KAAKI,MAAM,CAAE,AAACC,OAC3CT,QAAQI,IAAI,CAACK,MAAM,CAAmBX,SAExC,CACA,MAAOS,GAAAA,+BAAsB,EAACV,SAASW,MAAM,CAAE,AAACC,OAC/CT,QAAQH,QAAQ,CAACY,MAAM,CAAmBX,SAE5C,CAGA,GAAIY,GAAAA,sBAAa,EAACb,UAAW,CAC5B,OAAOc,uBAAuBd,SAAUC,QAASE,QAClD,CAGA,GAAIY,GAAAA,uBAAc,EAACf,UAAW,CAC7B,MAAO,CACNgB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAcC,GAAAA,6BAAoB,EAACnB,SACp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AASxB,0BACfI,QAAuB,CACvBC,OAAqD,CACrDgC,aAGiD,CACjD9B,OAGiD,EAGjD,GAAIC,GAAAA,qBAAY,EAACJ,UAAW,CAC3B,MAAOkC,GAAAA,2CAAkC,EAAClC,SAASW,MAAM,CAAE,AAACC,OAC3DT,QAAQH,QAAQ,CAACY,MAAM,CAAmBX,SAE5C,CAGA,GAAIY,GAAAA,sBAAa,EAACb,UAAW,CAC5B,MAAMoB,aAAenB,SAASmB,aAC9B,MAAOe,GAAAA,4CAAmC,EAACb,OAAOD,IAAI,CAACrB,UAAW,AAACuB,MAClE,MAAME,kBAAoB3B,yBAAyBsB,aAAcG,KACjE,OAAOpB,QAAQH,QAAQ,CAACuB,IAAI,CAAmB,CAC9CG,kBAAmBzB,SAASyB,kBAC5BU,eAAgBnC,SAASmC,eACzBhB,aAAcK,iBACf,EACD,EACD,CAGA,GAAIV,GAAAA,uBAAc,EAACf,UAAW,CAC7B,MAAO,CACNqC,SAAU,CACTrB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAcC,GAAAA,6BAAoB,EAACnB,SACpC,EACA+B,MAAO/B,QACR,CACD,CAGA,OAAOiC,cAAcjC,SAAUC,SAASmB,aACzC,CAeO,SAAStB,yBACfsB,YAAqC,CACrCG,GAAW,EAEX,OAAOH,aAAekB,GAAAA,mCAAiB,EAAClB,aAAc,CAACG,IAAI,EAAIgB,SAChE,CAeO,SAASxC,mBAAmByC,KAAoB,EACtD,OAAO,OAAOA,QAAU,UAAYC,GAAAA,iCAAuB,EAACD,MAC7D"}
1
+ {"version":3,"sources":["../../src/dispatch.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { hasHandlebarsExpression } from \"./parser.ts\";\nimport { resolveSchemaPath } from \"./schema-resolver.ts\";\nimport type { AnalysisResult, TemplateInput } from \"./types.ts\";\nimport {\n\tinferPrimitiveSchema,\n\tisArrayInput,\n\tisLiteralInput,\n\tisObjectInput,\n} from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n} from \"./utils.ts\";\n\n// ─── Template Input Dispatching ──────────────────────────────────────────────\n// Factorized dispatching for recursive processing of `TemplateInput` values.\n//\n// Every method in the engine (`analyze`, `execute`, `analyzeAndExecute`,\n// `compile`) follows the same recursive pattern:\n//\n// 1. If the input is an **array** → process each element recursively\n// 2. If the input is an **object** → process each property recursively\n// 3. If the input is a **literal** (number, boolean, null) → passthrough\n// 4. If the input is a **string** → delegate to a template-specific handler\n//\n// This module extracts the common dispatching logic into generic functions\n// that accept a callback for the string (template) case. This eliminates\n// the duplication across `Typebars`, `CompiledTemplate`, and `analyzer.ts`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Options controlling recursive dispatching behavior */\nexport interface DispatchAnalyzeOptions {\n\t/** Schemas by template identifier */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Explicit coercion schema for static literal output type */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/** Options controlling recursive execution dispatching */\nexport interface DispatchExecuteOptions {\n\t/** Explicit coercion schema for output type coercion */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Analysis Dispatching ────────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for analysis, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to analyze\n * @param options - Dispatching options (coerceSchema, excludeTemplateExpression)\n * @param analyzeString - Callback for analyzing a string template.\n * Receives `(template, coerceSchema?)` and must return an `AnalysisResult`.\n * @param recurse - Callback for recursively analyzing a child `TemplateInput`.\n * Receives `(child, options?)` and must return an `AnalysisResult`.\n * This allows callers (like `Typebars`) to rebind `this` or inject\n * additional context on each recursive call.\n * @returns An `AnalysisResult`\n */\nexport function dispatchAnalyze(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeOptions | undefined,\n\tanalyzeString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => AnalysisResult,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\t\tif (exclude) {\n\t\t\tconst kept = template.filter(\n\t\t\t\t(item) => !shouldExcludeEntry(item as TemplateInput),\n\t\t\t);\n\t\t\treturn aggregateArrayAnalysis(kept.length, (index) =>\n\t\t\t\trecurse(kept[index] as TemplateInput, options),\n\t\t\t);\n\t\t}\n\t\treturn aggregateArrayAnalysis(template.length, (index) =>\n\t\t\trecurse(template[index] as TemplateInput, options),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\treturn dispatchObjectAnalysis(template, options, recurse);\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\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\n\t// ── String template ──────────────────────────────────────────────────\n\treturn analyzeString(template, options?.coerceSchema);\n}\n\n/**\n * Dispatches object analysis with `coerceSchema` propagation and\n * `excludeTemplateExpression` filtering.\n *\n * Extracted as a separate function because the object case is the most\n * complex (key filtering + per-key coerceSchema resolution).\n */\nfunction dispatchObjectAnalysis(\n\ttemplate: Record<string, TemplateInput>,\n\toptions: DispatchAnalyzeOptions | undefined,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\tconst coerceSchema = options?.coerceSchema;\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\tconst keys = exclude\n\t\t? Object.keys(template).filter(\n\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t)\n\t\t: Object.keys(template);\n\n\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t});\n\t});\n}\n\n// ─── Execution Dispatching ───────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for execution, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to execute\n * @param options - Dispatching options (coerceSchema)\n * @param executeString - Callback for executing a string template.\n * Receives `(template, coerceSchema?)` and must return the result.\n * @param recurse - Callback for recursively executing a child `TemplateInput`.\n * Receives `(child, options?)` and must return the result.\n * @returns The execution result\n */\nexport function dispatchExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchExecuteOptions | undefined,\n\texecuteString: (template: string, coerceSchema?: JSONSchema7) => unknown,\n\trecurse: (child: TemplateInput, options?: DispatchExecuteOptions) => unknown,\n): unknown {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\tconst result: unknown[] = [];\n\t\tfor (const element of elements) {\n\t\t\tresult.push(recurse(element as TemplateInput, options));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst result: Record<string, unknown> = {};\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\tfor (const key of keys) {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\tresult[key] = recurse(template[key] as TemplateInput, {\n\t\t\t\t...options,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) return template;\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null (there is no parent to remove it from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn null;\n\t}\n\n\treturn executeString(template, options?.coerceSchema);\n}\n\n// ─── Analyze-and-Execute Dispatching ─────────────────────────────────────────\n\n/** Options for combined analyze-and-execute dispatching */\nexport interface DispatchAnalyzeAndExecuteOptions {\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/**\n * Dispatches a `TemplateInput` for combined analysis and execution,\n * handling array/object/literal cases generically and delegating\n * the string case to a callback.\n *\n * @param template - The input to process\n * @param options - Options (identifierSchemas, identifierData, coerceSchema)\n * @param processString - Callback for analyzing and executing a string template.\n * Receives `(template, coerceSchema?)` and must return\n * `{ analysis, value }`.\n * @param recurse - Callback for recursively processing a child `TemplateInput`.\n * @returns `{ analysis, value }` where `value` is `undefined` if analysis fails\n */\nexport function dispatchAnalyzeAndExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeAndExecuteOptions | undefined,\n\tprocessString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => { analysis: AnalysisResult; value: unknown },\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeAndExecuteOptions,\n\t) => { analysis: AnalysisResult; value: unknown },\n): { analysis: AnalysisResult; value: unknown } {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\treturn aggregateArrayAnalysisAndExecution(elements.length, (index) =>\n\t\t\trecurse(elements[index] as TemplateInput, options),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\treturn aggregateObjectAnalysisAndExecution(keys, (key) => {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t\t});\n\t\t});\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t\t},\n\t\t\tvalue: template,\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null with a valid analysis (no parent to remove from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: { type: \"null\" },\n\t\t\t},\n\t\t\tvalue: null,\n\t\t};\n\t}\n\n\treturn processString(template, options?.coerceSchema);\n}\n\n// ─── Internal Utilities ──────────────────────────────────────────────────────\n\n/**\n * Resolves the child `coerceSchema` for a given object key.\n *\n * When a `coerceSchema` is provided, navigates into its `properties`\n * to find the schema for the given key. This allows deeply nested\n * objects to propagate coercion at every level.\n *\n * @param coerceSchema - The parent coercion schema (may be `undefined`)\n * @param key - The object property key\n * @returns The child coercion schema, or `undefined`\n */\nexport function resolveChildCoerceSchema(\n\tcoerceSchema: JSONSchema7 | undefined,\n\tkey: string,\n): JSONSchema7 | undefined {\n\treturn coerceSchema ? resolveSchemaPath(coerceSchema, [key]) : undefined;\n}\n\n/**\n * Determines whether a `TemplateInput` value should be excluded when\n * `excludeTemplateExpression` is enabled.\n *\n * A value is excluded if it is a string containing at least one Handlebars\n * expression (`{{…}}`). Literals (number, boolean, null), plain strings\n * without expressions, objects, and arrays are never excluded at the\n * entry level — objects and arrays are recursively filtered by the\n * dispatching functions themselves.\n *\n * @param input - The template input to check\n * @returns `true` if the input should be excluded\n */\nexport function shouldExcludeEntry(input: TemplateInput): boolean {\n\treturn typeof input === \"string\" && hasHandlebarsExpression(input);\n}\n"],"names":["dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","resolveChildCoerceSchema","shouldExcludeEntry","template","options","analyzeString","recurse","isArrayInput","exclude","excludeTemplateExpression","kept","filter","item","aggregateArrayAnalysis","length","index","isObjectInput","dispatchObjectAnalysis","isLiteralInput","valid","diagnostics","outputSchema","inferPrimitiveSchema","coerceSchema","keys","Object","key","aggregateObjectAnalysis","childCoerceSchema","identifierSchemas","executeString","elements","result","element","push","processString","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","analysis","value","type","resolveSchemaPath","undefined","input","hasHandlebarsExpression"],"mappings":"mPAoEgBA,yBAAAA,qBA0KAC,mCAAAA,+BA5EAC,yBAAAA,qBAiKAC,kCAAAA,8BAoBAC,4BAAAA,8CAtVw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A,2CAAkC,EAACL,SAASjB,MAAM,CAAE,AAACC,OAC3DT,QAAQyB,QAAQ,CAAChB,MAAM,CAAmBX,SAE5C,CAGA,GAAIY,GAAAA,sBAAa,EAACb,UAAW,CAC5B,MAAMoB,aAAenB,SAASmB,aAC9B,MAAMC,KAAOhB,QACViB,OAAOD,IAAI,CAACrB,UAAUQ,MAAM,CAC5B,AAACe,KAAQ,CAACxB,mBAAmBC,QAAQ,CAACuB,IAAI,GAE1CD,OAAOD,IAAI,CAACrB,UACf,MAAOkC,GAAAA,4CAAmC,EAACb,KAAM,AAACE,MACjD,MAAME,kBAAoB3B,yBAAyBsB,aAAcG,KACjE,OAAOpB,QAAQH,QAAQ,CAACuB,IAAI,CAAmB,CAC9CG,kBAAmBzB,SAASyB,kBAC5BS,eAAgBlC,SAASkC,eACzBf,aAAcK,kBACdnB,0BAA2BL,SAASK,yBACrC,EACD,EACD,CAGA,GAAIS,GAAAA,uBAAc,EAACf,UAAW,CAC7B,MAAO,CACNoC,SAAU,CACTpB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAcC,GAAAA,6BAAoB,EAACnB,SACpC,EACAqC,MAAOrC,QACR,CACD,CAKA,GAAIK,SAAWN,mBAAmBC,UAAW,CAC5C,MAAO,CACNoC,SAAU,CACTpB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAc,CAAEoB,KAAM,MAAO,CAC9B,EACAD,MAAO,IACR,CACD,CAEA,OAAOL,cAAchC,SAAUC,SAASmB,aACzC,CAeO,SAAStB,yBACfsB,YAAqC,CACrCG,GAAW,EAEX,OAAOH,aAAemB,GAAAA,mCAAiB,EAACnB,aAAc,CAACG,IAAI,EAAIiB,SAChE,CAeO,SAASzC,mBAAmB0C,KAAoB,EACtD,OAAO,OAAOA,QAAU,UAAYC,GAAAA,iCAAuB,EAACD,MAC7D"}
@@ -1,6 +1,6 @@
1
1
  import Handlebars from "handlebars";
2
2
  import type { JSONSchema7 } from "json-schema";
3
- import type { TemplateInput } from "./types.js";
3
+ import type { HelperDefinition, TemplateInput } from "./types.js";
4
4
  import { LRUCache } from "./utils.js";
5
5
  /** Optional context for execution (used by Typebars/CompiledTemplate) */
6
6
  export interface ExecutorContext {
@@ -18,6 +18,8 @@ export interface ExecutorContext {
18
18
  * to match the declared type instead of using auto-detection.
19
19
  */
20
20
  coerceSchema?: JSONSchema7;
21
+ /** Registered helpers (for direct execution of special helpers like `collect`) */
22
+ helpers?: Map<string, HelperDefinition>;
21
23
  }
22
24
  /**
23
25
  * Executes a template with the provided data and returns the result.
@@ -1,2 +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 _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _parserts=require("./parser.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){return(0,_dispatchts.dispatchExecute)(template,undefined,tpl=>{const ast=(0,_parserts.parse)(tpl);return executeFromAst(ast,tpl,data,{identifierData})},child=>execute(child,data,identifierData))}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 coerceValue(raw,ctx?.coerceSchema)}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 coerceValue(raw,ctx?.coerceSchema)}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);const effective=(0,_parserts.getEffectiveBody)(ast);const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){return coerceValue(raw,ctx?.coerceSchema)}return raw}function coerceValue(raw,coerceSchema){if(coerceSchema){const targetType=coerceSchema.type;if(typeof targetType==="string"){if(targetType==="string")return raw;if(targetType==="number"||targetType==="integer")return Number(raw.trim());if(targetType==="boolean")return raw.trim()==="true";if(targetType==="null")return null}}return(0,_parserts.coerceLiteral)(raw)}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((0,_parserts.isRootPathTraversal)(cleanSegments)){return undefined}if((0,_parserts.isRootSegments)(cleanSegments)){if(identifier!==null&&identifierData){const source=identifierData[identifier];return source??undefined}if(identifier!==null){return undefined}return data}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){const base=data!==null&&typeof data==="object"&&!Array.isArray(data)?data:{};const merged={...base,[_parserts.ROOT_TOKEN]:data};if(!identifierData)return merged;for(const[id,idData]of Object.entries(identifierData)){merged[`${_parserts.ROOT_TOKEN}:${id}`]=idData;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()}
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 _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _collectionhelpersts=require("./helpers/collection-helpers.js");const _parserts=require("./parser.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){return(0,_dispatchts.dispatchExecute)(template,undefined,tpl=>{const ast=(0,_parserts.parse)(tpl);return executeFromAst(ast,tpl,data,{identifierData})},child=>execute(child,data,identifierData))}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,ctx?.helpers)}}const singleExpr=(0,_parserts.getEffectivelySingleExpression)(ast);if(singleExpr&&singleExpr.params.length===0&&!singleExpr.hash){return resolveExpression(singleExpr.path,data,identifierData,ctx?.helpers)}if(singleExpr&&(singleExpr.params.length>0||singleExpr.hash)){const directResult=tryDirectHelperExecution(singleExpr,data,ctx);if(directResult!==undefined){return directResult.value}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceValue(raw,ctx?.coerceSchema)}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 coerceValue(raw,ctx?.coerceSchema)}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);const effective=(0,_parserts.getEffectiveBody)(ast);const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){return coerceValue(raw,ctx?.coerceSchema)}return raw}function coerceValue(raw,coerceSchema){if(coerceSchema){const targetType=coerceSchema.type;if(typeof targetType==="string"){if(targetType==="string")return raw;if(targetType==="number"||targetType==="integer")return Number(raw.trim());if(targetType==="boolean")return raw.trim()==="true";if(targetType==="null")return null}}return(0,_parserts.coerceLiteral)(raw)}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,helpers){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;if(expr.type==="SubExpression"){const subExpr=expr;if(subExpr.path.type==="PathExpression"){const helperName=subExpr.path.original;const helper=helpers?.get(helperName);if(helper){const isCollect=helperName===_collectionhelpersts.CollectionHelpers.COLLECT_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<subExpr.params.length;i++){const param=subExpr.params[i];if(isCollect&&i===1&&param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,identifierData,helpers))}}return helper.fn(...resolvedArgs)}}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((0,_parserts.isRootPathTraversal)(cleanSegments)){return undefined}if((0,_parserts.isRootSegments)(cleanSegments)){if(identifier!==null&&identifierData){const source=identifierData[identifier];return source??undefined}if(identifier!==null){return undefined}return data}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){const base=data!==null&&typeof data==="object"&&!Array.isArray(data)?data:{};const merged={...base,[_parserts.ROOT_TOKEN]:data};if(!identifierData)return merged;for(const[id,idData]of Object.entries(identifierData)){merged[`${_parserts.ROOT_TOKEN}:${id}`]=idData;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()}const DIRECT_EXECUTION_HELPERS=new Set([_collectionhelpersts.CollectionHelpers.COLLECT_HELPER_NAME]);function tryDirectHelperExecution(stmt,data,ctx){if(stmt.path.type!=="PathExpression")return undefined;const helperName=stmt.path.original;if(!DIRECT_EXECUTION_HELPERS.has(helperName))return undefined;const helper=ctx?.helpers?.get(helperName);if(!helper)return undefined;const isCollect=helperName===_collectionhelpersts.CollectionHelpers.COLLECT_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<stmt.params.length;i++){const param=stmt.params[i];if(isCollect&&i===1){if(param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}const value=helper.fn(...resolvedArgs);return{value}}
2
2
  //# sourceMappingURL=executor.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/executor.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { dispatchExecute } from \"./dispatch.ts\";\nimport { TemplateRuntimeError } from \"./errors.ts\";\nimport {\n\tcanUseFastPath,\n\tcoerceLiteral,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisSingleExpression,\n\tisThisExpression,\n\tparse,\n\tROOT_TOKEN,\n} from \"./parser.ts\";\nimport type { TemplateInput } 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\t/**\n\t * Explicit coercion schema for the output value.\n\t * When set with a primitive type, the execution result will be coerced\n\t * to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\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: unknown,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): unknown {\n\treturn dispatchExecute(\n\t\ttemplate,\n\t\tundefined,\n\t\t// String handler — parse and execute the AST\n\t\t(tpl) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn executeFromAst(ast, tpl, data, { identifierData });\n\t\t},\n\t\t// Recursive handler — re-enter execute() for child elements\n\t\t(child) => execute(child, data, identifierData),\n\t);\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: 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 coerceValue(raw, ctx?.coerceSchema);\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 coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 4: mixed template ───────────────────────────────────────────\n\t// For purely static templates (only ContentStatements), coerce the\n\t// result to match the coerceSchema type or auto-detect the literal type.\n\t// For truly mixed templates (text + blocks + expressions), return string.\n\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\tconst raw = renderWithHandlebars(template, merged, ctx);\n\n\tconst effective = getEffectiveBody(ast);\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\treturn raw;\n}\n\n// ─── Value Coercion ──────────────────────────────────────────────────────────\n// Coerces a raw string from Handlebars rendering based on an optional\n// coerceSchema. When no schema is provided, falls back to auto-detection\n// via `coerceLiteral`.\n\n/**\n * Coerces a raw string value based on an optional coercion schema.\n *\n * - If `coerceSchema` declares a primitive type (`string`, `number`,\n * `integer`, `boolean`, `null`), the value is cast to that type.\n * - Otherwise, falls back to `coerceLiteral` (auto-detection).\n *\n * @param raw - The raw string from Handlebars rendering\n * @param coerceSchema - Optional schema declaring the desired output type\n * @returns The coerced value\n */\nfunction coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown {\n\tif (coerceSchema) {\n\t\tconst targetType = coerceSchema.type;\n\t\tif (typeof targetType === \"string\") {\n\t\t\tif (targetType === \"string\") return raw;\n\t\t\tif (targetType === \"number\" || targetType === \"integer\")\n\t\t\t\treturn Number(raw.trim());\n\t\t\tif (targetType === \"boolean\") return raw.trim() === \"true\";\n\t\t\tif (targetType === \"null\") return null;\n\t\t}\n\t}\n\t// No coerceSchema or non-primitive type → auto-detect\n\treturn coerceLiteral(raw);\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: 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: 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 BEFORE\n\t// checking for $root, so that both {{$root}} and {{$root:N}} are\n\t// handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// $root path traversal ($root.name) — not supported, return undefined\n\t// (the analyzer already rejects it with a diagnostic).\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\treturn undefined;\n\t}\n\n\t// $root → return the entire data context (or identifier data)\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null && identifierData) {\n\t\t\tconst source = identifierData[identifier];\n\t\t\treturn source ?? undefined;\n\t\t}\n\t\tif (identifier !== null) {\n\t\t\t// Template uses an identifier but no identifierData was provided\n\t\t\treturn undefined;\n\t\t}\n\t\treturn data;\n\t}\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: unknown,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): Record<string, unknown> {\n\t// Always include $root so that Handlebars can resolve {{$root}} in\n\t// mixed templates and block helpers (where we delegate to Handlebars\n\t// instead of resolving expressions ourselves).\n\t// When data is a primitive (e.g. number passed with {{$root}}), we\n\t// wrap it into an object so Handlebars can still function.\n\tconst base: Record<string, unknown> =\n\t\tdata !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t? (data as Record<string, unknown>)\n\t\t\t: {};\n\tconst merged: Record<string, unknown> = { ...base, [ROOT_TOKEN]: data };\n\n\tif (!identifierData) return merged;\n\n\tfor (const [id, idData] of Object.entries(identifierData)) {\n\t\t// Add `$root:N` so Handlebars can resolve {{$root:N}} in mixed/block\n\t\t// templates (where we delegate to Handlebars instead of resolving\n\t\t// expressions ourselves). The value is the entire identifier data object.\n\t\tmerged[`${ROOT_TOKEN}:${id}`] = idData;\n\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","dispatchExecute","undefined","tpl","ast","parse","child","ctx","isSingleExpression","stmt","body","params","length","hash","resolveExpression","path","singleExpr","getEffectivelySingleExpression","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","canUseFastPath","executeFastPath","singleBlock","getEffectivelySingleBlock","effective","getEffectiveBody","allContent","every","s","type","targetType","Number","trim","coerceLiteral","result","value","String","expr","isThisExpression","segments","extractPathSegments","TemplateRuntimeError","cleanSegments","identifier","extractExpressionIdentifier","isRootPathTraversal","isRootSegments","source","current","segment","base","Array","isArray","ROOT_TOKEN","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","Handlebars","compiled","get","compile","noEscape","strict","set","error","message","Error","clear"],"mappings":"mPA4egBA,+BAAAA,2BA5YAC,iBAAAA,aAiCAC,wBAAAA,oBA0OAC,yBAAAA,mFA3WO,yCAES,yCACK,uCAe9B,sCAEk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SACrB,CAEA,OAAOA,SAASrE,KACjB,CAAE,MAAO2E,MAAgB,CACxB,MAAMC,QAAUD,iBAAiBE,MAAQF,MAAMC,OAAO,CAAGnC,OAAOkC,MAChE,OAAM,IAAI7B,8BAAoB,CAAC8B,QAChC,CACD,CAMO,SAASnF,wBACfI,uBAAuBiF,KAAK,EAC7B"}
1
+ {"version":3,"sources":["../../src/executor.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { dispatchExecute } from \"./dispatch.ts\";\nimport { TemplateRuntimeError } from \"./errors.ts\";\nimport { CollectionHelpers } from \"./helpers/collection-helpers.ts\";\nimport {\n\tcanUseFastPath,\n\tcoerceLiteral,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisSingleExpression,\n\tisThisExpression,\n\tparse,\n\tROOT_TOKEN,\n} from \"./parser.ts\";\nimport type { HelperDefinition, TemplateInput } 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\t/**\n\t * Explicit coercion schema for the output value.\n\t * When set with a primitive type, the execution result will be coerced\n\t * to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/** Registered helpers (for direct execution of special helpers like `collect`) */\n\thelpers?: Map<string, HelperDefinition>;\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: unknown,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): unknown {\n\treturn dispatchExecute(\n\t\ttemplate,\n\t\tundefined,\n\t\t// String handler — parse and execute the AST\n\t\t(tpl) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn executeFromAst(ast, tpl, data, { identifierData });\n\t\t},\n\t\t// Recursive handler — re-enter execute() for child elements\n\t\t(child) => execute(child, data, identifierData),\n\t);\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: 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, ctx?.helpers);\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(\n\t\t\tsingleExpr.path,\n\t\t\tdata,\n\t\t\tidentifierData,\n\t\t\tctx?.helpers,\n\t\t);\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\t// ── Special case: helpers that return non-primitive values ────────\n\t\t// Some helpers (e.g. `collect`) return arrays or objects. Handlebars\n\t\t// would stringify these, so we resolve their arguments directly and\n\t\t// call the helper's fn to preserve the raw return value.\n\t\tconst directResult = tryDirectHelperExecution(singleExpr, data, ctx);\n\t\tif (directResult !== undefined) {\n\t\t\treturn directResult.value;\n\t\t}\n\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\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 coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 4: mixed template ───────────────────────────────────────────\n\t// For purely static templates (only ContentStatements), coerce the\n\t// result to match the coerceSchema type or auto-detect the literal type.\n\t// For truly mixed templates (text + blocks + expressions), return string.\n\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\tconst raw = renderWithHandlebars(template, merged, ctx);\n\n\tconst effective = getEffectiveBody(ast);\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\treturn raw;\n}\n\n// ─── Value Coercion ──────────────────────────────────────────────────────────\n// Coerces a raw string from Handlebars rendering based on an optional\n// coerceSchema. When no schema is provided, falls back to auto-detection\n// via `coerceLiteral`.\n\n/**\n * Coerces a raw string value based on an optional coercion schema.\n *\n * - If `coerceSchema` declares a primitive type (`string`, `number`,\n * `integer`, `boolean`, `null`), the value is cast to that type.\n * - Otherwise, falls back to `coerceLiteral` (auto-detection).\n *\n * @param raw - The raw string from Handlebars rendering\n * @param coerceSchema - Optional schema declaring the desired output type\n * @returns The coerced value\n */\nfunction coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown {\n\tif (coerceSchema) {\n\t\tconst targetType = coerceSchema.type;\n\t\tif (typeof targetType === \"string\") {\n\t\t\tif (targetType === \"string\") return raw;\n\t\t\tif (targetType === \"number\" || targetType === \"integer\")\n\t\t\t\treturn Number(raw.trim());\n\t\t\tif (targetType === \"boolean\") return raw.trim() === \"true\";\n\t\t\tif (targetType === \"null\") return null;\n\t\t}\n\t}\n\t// No coerceSchema or non-primitive type → auto-detect\n\treturn coerceLiteral(raw);\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: 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: unknown,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n\thelpers?: Map<string, HelperDefinition>,\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// ── SubExpression (nested helper call) ────────────────────────────────\n\t// E.g. `(collect users 'cartItems')` used as an argument to another helper.\n\t// Resolve all arguments recursively and call the helper's fn directly.\n\tif (expr.type === \"SubExpression\") {\n\t\tconst subExpr = expr as hbs.AST.SubExpression;\n\t\tif (subExpr.path.type === \"PathExpression\") {\n\t\t\tconst helperName = (subExpr.path as hbs.AST.PathExpression).original;\n\t\t\tconst helper = helpers?.get(helperName);\n\t\t\tif (helper) {\n\t\t\t\tconst isCollect = helperName === CollectionHelpers.COLLECT_HELPER_NAME;\n\t\t\t\tconst resolvedArgs: unknown[] = [];\n\t\t\t\tfor (let i = 0; i < subExpr.params.length; i++) {\n\t\t\t\t\tconst param = subExpr.params[i] as hbs.AST.Expression;\n\t\t\t\t\t// For `collect`, the second argument is a property name literal\n\t\t\t\t\tif (isCollect && i === 1 && param.type === \"StringLiteral\") {\n\t\t\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolvedArgs.push(\n\t\t\t\t\t\t\tresolveExpression(param, data, identifierData, helpers),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn helper.fn(...resolvedArgs);\n\t\t\t}\n\t\t}\n\t\t// Unknown sub-expression helper — return undefined\n\t\treturn undefined;\n\t}\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 BEFORE\n\t// checking for $root, so that both {{$root}} and {{$root:N}} are\n\t// handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// $root path traversal ($root.name) — not supported, return undefined\n\t// (the analyzer already rejects it with a diagnostic).\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\treturn undefined;\n\t}\n\n\t// $root → return the entire data context (or identifier data)\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null && identifierData) {\n\t\t\tconst source = identifierData[identifier];\n\t\t\treturn source ?? undefined;\n\t\t}\n\t\tif (identifier !== null) {\n\t\t\t// Template uses an identifier but no identifierData was provided\n\t\t\treturn undefined;\n\t\t}\n\t\treturn data;\n\t}\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: unknown,\n\tidentifierData?: Record<number, Record<string, unknown>>,\n): Record<string, unknown> {\n\t// Always include $root so that Handlebars can resolve {{$root}} in\n\t// mixed templates and block helpers (where we delegate to Handlebars\n\t// instead of resolving expressions ourselves).\n\t// When data is a primitive (e.g. number passed with {{$root}}), we\n\t// wrap it into an object so Handlebars can still function.\n\tconst base: Record<string, unknown> =\n\t\tdata !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t? (data as Record<string, unknown>)\n\t\t\t: {};\n\tconst merged: Record<string, unknown> = { ...base, [ROOT_TOKEN]: data };\n\n\tif (!identifierData) return merged;\n\n\tfor (const [id, idData] of Object.entries(identifierData)) {\n\t\t// Add `$root:N` so Handlebars can resolve {{$root:N}} in mixed/block\n\t\t// templates (where we delegate to Handlebars instead of resolving\n\t\t// expressions ourselves). The value is the entire identifier data object.\n\t\tmerged[`${ROOT_TOKEN}:${id}`] = idData;\n\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\n// ─── Direct Helper Execution ─────────────────────────────────────────────────\n// Some helpers (e.g. `collect`) return non-primitive values (arrays, objects)\n// that Handlebars would stringify. For these helpers, we resolve their\n// arguments directly and call the helper's `fn` to preserve the raw value.\n\n/** Set of helper names that must be executed directly (bypass Handlebars) */\nconst DIRECT_EXECUTION_HELPERS = new Set<string>([\n\tCollectionHelpers.COLLECT_HELPER_NAME,\n]);\n\n/**\n * Attempts to execute a helper directly (without Handlebars rendering).\n *\n * Returns `{ value }` if the helper was executed directly, or `undefined`\n * if the helper should go through the normal Handlebars rendering path.\n *\n * @param stmt - The MustacheStatement containing the helper call\n * @param data - The context data\n * @param ctx - Optional execution context (with helpers and identifierData)\n */\nfunction tryDirectHelperExecution(\n\tstmt: hbs.AST.MustacheStatement,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): { value: unknown } | undefined {\n\t// Get the helper name from the path\n\tif (stmt.path.type !== \"PathExpression\") return undefined;\n\tconst helperName = (stmt.path as hbs.AST.PathExpression).original;\n\n\t// Only intercept known direct-execution helpers\n\tif (!DIRECT_EXECUTION_HELPERS.has(helperName)) return undefined;\n\n\t// Look up the helper definition\n\tconst helper = ctx?.helpers?.get(helperName);\n\tif (!helper) return undefined;\n\n\t// Resolve each argument from the data context.\n\t// For the `collect` helper, the resolution strategy is:\n\t// - Arg 0 (collection): resolve as a data path (e.g. `users` → array)\n\t// - Arg 1 (property): must be a StringLiteral (e.g. `\"name\"`)\n\t// The analyzer enforces this — bare identifiers like `name` are\n\t// rejected at analysis time because Handlebars would resolve them\n\t// as a data path instead of a literal property name.\n\tconst isCollect = helperName === CollectionHelpers.COLLECT_HELPER_NAME;\n\n\tconst resolvedArgs: unknown[] = [];\n\tfor (let i = 0; i < stmt.params.length; i++) {\n\t\tconst param = stmt.params[i] as hbs.AST.Expression;\n\n\t\t// For `collect`, the second argument (index 1) is a property name —\n\t\t// it must be a StringLiteral (enforced by the analyzer).\n\t\tif (isCollect && i === 1) {\n\t\t\tif (param.type === \"StringLiteral\") {\n\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t} else {\n\t\t\t\t// Fallback: resolve normally (will likely be undefined at runtime)\n\t\t\t\tresolvedArgs.push(\n\t\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tresolvedArgs.push(\n\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Call the helper's fn directly with the resolved arguments\n\tconst value = helper.fn(...resolvedArgs);\n\treturn { value };\n}\n"],"names":["clearCompilationCache","execute","executeFromAst","resolveDataPath","globalCompilationCache","LRUCache","template","data","identifierData","dispatchExecute","undefined","tpl","ast","parse","child","ctx","isSingleExpression","stmt","body","params","length","hash","resolveExpression","path","helpers","singleExpr","getEffectivelySingleExpression","directResult","tryDirectHelperExecution","value","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","canUseFastPath","executeFastPath","singleBlock","getEffectivelySingleBlock","effective","getEffectiveBody","allContent","every","s","type","targetType","Number","trim","coerceLiteral","result","String","expr","isThisExpression","subExpr","helperName","original","helper","get","isCollect","CollectionHelpers","COLLECT_HELPER_NAME","resolvedArgs","i","param","push","fn","segments","extractPathSegments","TemplateRuntimeError","cleanSegments","identifier","extractExpressionIdentifier","isRootPathTraversal","isRootSegments","source","current","segment","base","Array","isArray","ROOT_TOKEN","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","Handlebars","compiled","compile","noEscape","strict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G,wBACfI,uBAAuBgG,KAAK,EAC7B,CAQA,MAAMC,yBAA2B,IAAIC,IAAY,CAChD1C,sCAAiB,CAACC,mBAAmB,CACrC,EAYD,SAASjC,yBACRX,IAA+B,CAC/BV,IAAa,CACbQ,GAAqB,EAGrB,GAAIE,KAAKM,IAAI,CAACsB,IAAI,GAAK,iBAAkB,OAAOnC,UAChD,MAAM6C,WAAa,AAACtC,KAAKM,IAAI,CAA4BiC,QAAQ,CAGjE,GAAI,CAAC6C,yBAAyBE,GAAG,CAAChD,YAAa,OAAO7C,UAGtD,MAAM+C,OAAS1C,KAAKS,SAASkC,IAAIH,YACjC,GAAI,CAACE,OAAQ,OAAO/C,UASpB,MAAMiD,UAAYJ,aAAeK,sCAAiB,CAACC,mBAAmB,CAEtE,MAAMC,aAA0B,EAAE,CAClC,IAAK,IAAIC,EAAI,EAAGA,EAAI9C,KAAKE,MAAM,CAACC,MAAM,CAAE2C,IAAK,CAC5C,MAAMC,MAAQ/C,KAAKE,MAAM,CAAC4C,EAAE,CAI5B,GAAIJ,WAAaI,IAAM,EAAG,CACzB,GAAIC,MAAMnB,IAAI,GAAK,gBAAiB,CACnCiB,aAAaG,IAAI,CAAC,AAACD,MAAgCnC,KAAK,CACzD,KAAO,CAENiC,aAAaG,IAAI,CAChB3C,kBAAkB0C,MAAOzD,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,KAAO,CACNsC,aAAaG,IAAI,CAChB3C,kBAAkB0C,MAAOzD,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,CAGA,MAAMK,MAAQ4B,OAAOS,EAAE,IAAIJ,cAC3B,MAAO,CAAEjC,KAAM,CAChB"}
@@ -0,0 +1,9 @@
1
+ import type { HelperDefinition } from "../types.js";
2
+ import { HelperFactory } from "./helper-factory.js";
3
+ export declare class CollectionHelpers extends HelperFactory {
4
+ /** The name used for special-case detection in the analyzer/executor */
5
+ static readonly COLLECT_HELPER_NAME = "collect";
6
+ protected buildDefinitions(defs: Map<string, HelperDefinition>): void;
7
+ /** Registers the `collect` helper */
8
+ private registerCollect;
9
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"CollectionHelpers",{enumerable:true,get:function(){return CollectionHelpers}});const _helperfactoryts=require("./helper-factory.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}function collectProperty(collection,property){if(!Array.isArray(collection)){return[]}const prop=String(property);const flattened=collection.flat(1);return flattened.map(item=>{if(item!==null&&item!==undefined&&typeof item==="object"){return item[prop]}return undefined})}class CollectionHelpers extends _helperfactoryts.HelperFactory{buildDefinitions(defs){this.registerCollect(defs)}registerCollect(defs){defs.set(CollectionHelpers.COLLECT_HELPER_NAME,{fn:(collection,property)=>collectProperty(collection,property),params:[{name:"collection",type:{type:"array"},description:"The array of objects to extract values from"},{name:"property",type:{type:"string"},description:"The property name to extract from each element"}],returnType:{type:"array"},description:'Extracts a property from each element of an array: {{ collect users "name" }} → ["Alice", "Bob", "Charlie"]'})}}_define_property(CollectionHelpers,"COLLECT_HELPER_NAME","collect");
2
+ //# sourceMappingURL=collection-helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/helpers/collection-helpers.ts"],"sourcesContent":["import type { HelperDefinition } from \"../types.ts\";\nimport { HelperFactory } from \"./helper-factory.ts\";\n\n// ─── CollectionHelpers ───────────────────────────────────────────────────────\n// Aggregates all collection-related helpers for the template engine.\n//\n// Provides helpers for working with arrays of objects:\n//\n// - **`collect`** — Extracts a specific property from each element of an\n// array, returning a new array of those values.\n// Usage: `{{ collect users \"name\" }}` → `[\"Alice\", \"Bob\", \"Charlie\"]`\n//\n// ─── Registration ────────────────────────────────────────────────────────────\n// CollectionHelpers are automatically pre-registered by the `Typebars`\n// constructor. They can also be registered manually on any object\n// implementing `HelperRegistry`:\n//\n// const factory = new CollectionHelpers();\n// factory.register(engine); // registers all helpers\n// factory.unregister(engine); // removes all helpers\n//\n// ─── Static Analysis ─────────────────────────────────────────────────────────\n// The `collect` helper has special static analysis handling in the analyzer:\n// - The first argument must resolve to an array of objects\n// - The second argument must be a quoted string literal (e.g. `\"name\"`, not `name`)\n// - The property must exist in the item schema of the array\n// - The inferred return type is `{ type: \"array\", items: <property schema> }`\n\n// ─── Internal utilities ─────────────────────────────────────────────────────\n\n/**\n * Extracts a property from each element of an array.\n *\n * @param collection - The array of objects\n * @param property - The property name to extract from each element\n * @returns A new array containing the extracted property values\n */\nfunction collectProperty(collection: unknown, property: unknown): unknown[] {\n\tif (!Array.isArray(collection)) {\n\t\treturn [];\n\t}\n\tconst prop = String(property);\n\t// Use flatMap semantics: if the collection contains nested arrays\n\t// (e.g. from a previous collect), flatten one level before extracting.\n\t// This enables chaining like `{{ collect (collect users 'cartItems') 'productId' }}`\n\t// where the inner collect returns an array of arrays.\n\tconst flattened = collection.flat(1);\n\treturn flattened.map((item: unknown) => {\n\t\tif (item !== null && item !== undefined && typeof item === \"object\") {\n\t\t\treturn (item as Record<string, unknown>)[prop];\n\t\t}\n\t\treturn undefined;\n\t});\n}\n\n// ─── Main class ─────────────────────────────────────────────────────────────\n\nexport class CollectionHelpers extends HelperFactory {\n\t/** The name used for special-case detection in the analyzer/executor */\n\tstatic readonly COLLECT_HELPER_NAME = \"collect\";\n\n\t// ─── buildDefinitions (required by HelperFactory) ──────────────────\n\n\tprotected buildDefinitions(defs: Map<string, HelperDefinition>): void {\n\t\tthis.registerCollect(defs);\n\t}\n\n\t// ── collect ──────────────────────────────────────────────────────────\n\n\t/** Registers the `collect` helper */\n\tprivate registerCollect(defs: Map<string, HelperDefinition>): void {\n\t\tdefs.set(CollectionHelpers.COLLECT_HELPER_NAME, {\n\t\t\tfn: (collection: unknown, property: unknown) =>\n\t\t\t\tcollectProperty(collection, property),\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"collection\",\n\t\t\t\t\ttype: { type: \"array\" },\n\t\t\t\t\tdescription: \"The array of objects to extract values from\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"property\",\n\t\t\t\t\ttype: { type: \"string\" },\n\t\t\t\t\tdescription: \"The property name to extract from each element\",\n\t\t\t\t},\n\t\t\t],\n\t\t\treturnType: { type: \"array\" },\n\t\t\tdescription:\n\t\t\t\t'Extracts a property from each element of an array: {{ collect users \"name\" }} → [\"Alice\", \"Bob\", \"Charlie\"]',\n\t\t});\n\t}\n}\n"],"names":["CollectionHelpers","collectProperty","collection","property","Array","isArray","prop","String","flattened","flat","map","item","undefined","HelperFactory","buildDefinitions","defs","registerCollect","set","COLLECT_HELPER_NAME","fn","params","name","type","description","returnType"],"mappings":"oGAyDaA,2DAAAA,oDAxDiB,2MAoC9B,SAASC,gBAAgBC,UAAmB,CAAEC,QAAiB,EAC9D,GAAI,CAACC,MAAMC,OAAO,CAACH,YAAa,CAC/B,MAAO,EAAE,AACV,CACA,MAAMI,KAAOC,OAAOJ,UAKpB,MAAMK,UAAYN,WAAWO,IAAI,CAAC,GAClC,OAAOD,UAAUE,GAAG,CAAC,AAACC,OACrB,GAAIA,OAAS,MAAQA,OAASC,WAAa,OAAOD,OAAS,SAAU,CACpE,OAAO,AAACA,IAAgC,CAACL,KAAK,AAC/C,CACA,OAAOM,SACR,EACD,CAIO,MAAMZ,0BAA0Ba,8BAAa,CAMnD,AAAUC,iBAAiBC,IAAmC,CAAQ,CACrE,IAAI,CAACC,eAAe,CAACD,KACtB,CAKA,AAAQC,gBAAgBD,IAAmC,CAAQ,CAClEA,KAAKE,GAAG,CAACjB,kBAAkBkB,mBAAmB,CAAE,CAC/CC,GAAI,CAACjB,WAAqBC,WACzBF,gBAAgBC,WAAYC,UAC7BiB,OAAQ,CACP,CACCC,KAAM,aACNC,KAAM,CAAEA,KAAM,OAAQ,EACtBC,YAAa,6CACd,EACA,CACCF,KAAM,WACNC,KAAM,CAAEA,KAAM,QAAS,EACvBC,YAAa,gDACd,EACA,CACDC,WAAY,CAAEF,KAAM,OAAQ,EAC5BC,YACC,6GACF,EACD,CACD,CAhCC,iBAFYvB,kBAEIkB,sBAAsB"}
@@ -1,3 +1,4 @@
1
+ export { CollectionHelpers } from "./collection-helpers.js";
1
2
  export { HelperFactory, type HelperRegistry } from "./helper-factory.js";
2
3
  export { LogicalHelpers } from "./logical-helpers.js";
3
4
  export { MathHelpers } from "./math-helpers.js";
@@ -1,2 +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");
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 CollectionHelpers(){return _collectionhelpers.CollectionHelpers},get HelperFactory(){return _helperfactory.HelperFactory},get LogicalHelpers(){return _logicalhelpers.LogicalHelpers},get MathHelpers(){return _mathhelpers.MathHelpers},get toNumber(){return _utils.toNumber}});const _collectionhelpers=require("./collection-helpers.js");const _helperfactory=require("./helper-factory.js");const _logicalhelpers=require("./logical-helpers.js");const _mathhelpers=require("./math-helpers.js");const _utils=require("./utils.js");
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +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
+ {"version":3,"sources":["../../../src/helpers/index.ts"],"sourcesContent":["export { CollectionHelpers } from \"./collection-helpers\";\nexport { HelperFactory, type HelperRegistry } from \"./helper-factory\";\nexport { LogicalHelpers } from \"./logical-helpers\";\nexport { MathHelpers } from \"./math-helpers\";\nexport { toNumber } from \"./utils\";\n"],"names":["CollectionHelpers","HelperFactory","LogicalHelpers","MathHelpers","toNumber"],"mappings":"mPAASA,2BAAAA,oCAAiB,MACjBC,uBAAAA,4BAAa,MACbC,wBAAAA,8BAAc,MACdC,qBAAAA,wBAAW,MACXC,kBAAAA,eAAQ,qCAJiB,qDACiB,kDACpB,gDACH,uCACH"}
@@ -1,2 +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 assertNoConditionalSchema(){return assertNoConditionalSchema},get resolveArrayItems(){return resolveArrayItems},get resolveRef(){return resolveRef},get resolveSchemaPath(){return resolveSchemaPath},get simplifySchema(){return simplifySchema}});const _errorsts=require("./errors.js");const _utilsts=require("./utils.js");function assertNoConditionalSchema(schema,path="",visited=new Set){if(visited.has(schema))return;visited.add(schema);if(schema.if!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.then!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.else!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.properties){for(const[key,prop]of Object.entries(schema.properties)){if(prop&&typeof prop!=="boolean"){assertNoConditionalSchema(prop,`${path}/properties/${key}`,visited)}}}if(schema.additionalProperties&&typeof schema.additionalProperties==="object"){assertNoConditionalSchema(schema.additionalProperties,`${path}/additionalProperties`,visited)}if(schema.items){if(Array.isArray(schema.items)){for(let i=0;i<schema.items.length;i++){const item=schema.items[i];if(item&&typeof item!=="boolean"){assertNoConditionalSchema(item,`${path}/items/${i}`,visited)}}}else if(typeof schema.items!=="boolean"){assertNoConditionalSchema(schema.items,`${path}/items`,visited)}}for(const keyword of["allOf","anyOf","oneOf"]){const branches=schema[keyword];if(branches){for(let i=0;i<branches.length;i++){const branch=branches[i];if(branch&&typeof branch!=="boolean"){assertNoConditionalSchema(branch,`${path}/${keyword}/${i}`,visited)}}}}if(schema.not&&typeof schema.not!=="boolean"){assertNoConditionalSchema(schema.not,`${path}/not`,visited)}for(const defsKey of["definitions","$defs"]){const defs=schema[defsKey];if(defs){for(const[name,def]of Object.entries(defs)){if(def&&typeof def!=="boolean"){assertNoConditionalSchema(def,`${path}/${defsKey}/${name}`,visited)}}}}}function resolveRef(schema,root){if(!schema.$ref)return schema;const ref=schema.$ref;const match=ref.match(/^#\/(definitions|\$defs)\/(.+)$/);if(!match){throw new Error(`Unsupported $ref format: "${ref}". Only internal #/definitions/ references are supported.`)}const defsKey=match[1];const name=match[2]??"";const defs=defsKey==="definitions"?root.definitions:root.$defs;if(!defs||!(name in defs)){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}const def=defs[name];if(!def||typeof def==="boolean"){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}return resolveRef(def,root)}function resolveSegment(schema,segment,root){const resolved=resolveRef(schema,root);if(resolved.properties&&segment in resolved.properties){const prop=resolved.properties[segment];if(prop&&typeof prop!=="boolean")return resolveRef(prop,root);if(prop===true)return{}}if(resolved.additionalProperties!==undefined&&resolved.additionalProperties!==false){if(resolved.additionalProperties===true){return{}}return resolveRef(resolved.additionalProperties,root)}const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(isArray&&segment==="length"){return{type:"integer"}}const combinatorResult=resolveInCombinators(resolved,segment,root);if(combinatorResult)return combinatorResult;return undefined}function resolveInCombinators(schema,segment,root){if(schema.allOf){const matches=schema.allOf.filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{allOf:matches}}for(const key of["anyOf","oneOf"]){if(!schema[key])continue;const matches=schema[key].filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{[key]:matches}}return undefined}function resolveSchemaPath(schema,path){if(path.length===0)return resolveRef(schema,schema);let current=resolveRef(schema,schema);const root=schema;for(const segment of path){const next=resolveSegment(current,segment,root);if(next===undefined)return undefined;current=next}return current}function resolveArrayItems(schema,root){const resolved=resolveRef(schema,root);const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(!isArray&&resolved.items===undefined){return undefined}if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const schemas=resolved.items.filter(item=>typeof item!=="boolean").map(item=>resolveRef(item,root));if(schemas.length===0)return{};return{oneOf:schemas}}return resolveRef(resolved.items,root)}function simplifySchema(schema){for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length===1){const first=arr[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}}if(schema.allOf&&schema.allOf.length===1){const first=schema.allOf[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length>1){const unique=[];for(const entry of arr){if(typeof entry==="boolean")continue;const isDuplicate=unique.some(existing=>(0,_utilsts.deepEqual)(existing,entry));if(!isDuplicate){unique.push(simplifySchema(entry))}}if(unique.length===1)return unique[0];return{...schema,[key]:unique}}}return schema}
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 assertNoConditionalSchema(){return assertNoConditionalSchema},get resolveArrayItems(){return resolveArrayItems},get resolveRef(){return resolveRef},get resolveSchemaPath(){return resolveSchemaPath},get simplifySchema(){return simplifySchema}});const _errorsts=require("./errors.js");const _utilsts=require("./utils.js");function assertNoConditionalSchema(schema,path="",visited=new Set){if(visited.has(schema))return;visited.add(schema);if(schema.if!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.then!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.else!==undefined){throw new _errorsts.UnsupportedSchemaError("if/then/else",path||"/")}if(schema.properties){for(const[key,prop]of Object.entries(schema.properties)){if(prop&&typeof prop!=="boolean"){assertNoConditionalSchema(prop,`${path}/properties/${key}`,visited)}}}if(schema.additionalProperties&&typeof schema.additionalProperties==="object"){assertNoConditionalSchema(schema.additionalProperties,`${path}/additionalProperties`,visited)}if(schema.items){if(Array.isArray(schema.items)){for(let i=0;i<schema.items.length;i++){const item=schema.items[i];if(item&&typeof item!=="boolean"){assertNoConditionalSchema(item,`${path}/items/${i}`,visited)}}}else if(typeof schema.items!=="boolean"){assertNoConditionalSchema(schema.items,`${path}/items`,visited)}}for(const keyword of["allOf","anyOf","oneOf"]){const branches=schema[keyword];if(branches){for(let i=0;i<branches.length;i++){const branch=branches[i];if(branch&&typeof branch!=="boolean"){assertNoConditionalSchema(branch,`${path}/${keyword}/${i}`,visited)}}}}if(schema.not&&typeof schema.not!=="boolean"){assertNoConditionalSchema(schema.not,`${path}/not`,visited)}for(const defsKey of["definitions","$defs"]){const defs=schema[defsKey];if(defs){for(const[name,def]of Object.entries(defs)){if(def&&typeof def!=="boolean"){assertNoConditionalSchema(def,`${path}/${defsKey}/${name}`,visited)}}}}}function resolveRef(schema,root){if(!schema.$ref)return schema;const ref=schema.$ref;const match=ref.match(/^#\/(definitions|\$defs)\/(.+)$/);if(!match){throw new Error(`Unsupported $ref format: "${ref}". Only internal #/definitions/ references are supported.`)}const defsKey=match[1];const name=match[2]??"";const defs=defsKey==="definitions"?root.definitions:root.$defs;if(!defs||!(name in defs)){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}const def=defs[name];if(!def||typeof def==="boolean"){throw new Error(`Cannot resolve $ref "${ref}": definition "${name}" not found.`)}return resolveRef(def,root)}function resolveSegment(schema,segment,root){const resolved=resolveRef(schema,root);if(resolved.properties&&segment in resolved.properties){const prop=resolved.properties[segment];if(prop&&typeof prop!=="boolean")return resolveRef(prop,root);if(prop===true)return{}}if(resolved.additionalProperties!==undefined&&resolved.additionalProperties!==false){if(resolved.additionalProperties===true){return{}}return resolveRef(resolved.additionalProperties,root)}const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(isArray&&segment==="length"){return{type:"integer"}}if(isArray&&/^\d+$/.test(segment)){if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const idx=Number.parseInt(segment,10);const item=resolved.items[idx];if(item!==undefined&&typeof item!=="boolean"){return resolveRef(item,root)}if(item!==undefined&&typeof item==="boolean"){return{}}if(resolved.additionalItems===false){return undefined}if(resolved.additionalItems!==undefined&&resolved.additionalItems!==true&&typeof resolved.additionalItems==="object"){return resolveRef(resolved.additionalItems,root)}return{}}return resolveRef(resolved.items,root)}const combinatorResult=resolveInCombinators(resolved,segment,root);if(combinatorResult)return combinatorResult;return undefined}function resolveInCombinators(schema,segment,root){if(schema.allOf){const matches=schema.allOf.filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{allOf:matches}}for(const key of["anyOf","oneOf"]){if(!schema[key])continue;const matches=schema[key].filter(b=>typeof b!=="boolean").map(branch=>resolveSegment(branch,segment,root)).filter(s=>s!==undefined);if(matches.length===1)return matches[0];if(matches.length>1)return{[key]:matches}}return undefined}function resolveSchemaPath(schema,path){if(path.length===0)return resolveRef(schema,schema);let current=resolveRef(schema,schema);const root=schema;for(const segment of path){const next=resolveSegment(current,segment,root);if(next===undefined)return undefined;current=next}return current}function resolveArrayItems(schema,root){const resolved=resolveRef(schema,root);const schemaType=resolved.type;const isArray=schemaType==="array"||Array.isArray(schemaType)&&schemaType.includes("array");if(!isArray&&resolved.items===undefined){return undefined}if(resolved.items===undefined){return{}}if(typeof resolved.items==="boolean"){return{}}if(Array.isArray(resolved.items)){const schemas=resolved.items.filter(item=>typeof item!=="boolean").map(item=>resolveRef(item,root));if(schemas.length===0)return{};return{oneOf:schemas}}return resolveRef(resolved.items,root)}function simplifySchema(schema){for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length===1){const first=arr[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}}if(schema.allOf&&schema.allOf.length===1){const first=schema.allOf[0];if(first!==undefined&&typeof first!=="boolean")return simplifySchema(first)}for(const key of["oneOf","anyOf"]){const arr=schema[key];if(arr&&arr.length>1){const unique=[];for(const entry of arr){if(typeof entry==="boolean")continue;const isDuplicate=unique.some(existing=>(0,_utilsts.deepEqual)(existing,entry));if(!isDuplicate){unique.push(simplifySchema(entry))}}if(unique.length===1)return unique[0];return{...schema,[key]:unique}}}return schema}
2
2
  //# sourceMappingURL=schema-resolver.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema-resolver.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { UnsupportedSchemaError } from \"./errors.ts\";\nimport { deepEqual } from \"./utils.ts\";\n\n// ─── JSON Schema Resolver ────────────────────────────────────────────────────\n// Utility for navigating a JSON Schema Draft v7 by following a property path\n// (e.g. [\"user\", \"address\", \"city\"]).\n//\n// Handles:\n// - `$ref` resolution (internal references #/definitions/...)\n// - Navigation through `properties`\n// - Navigation through `items` (array elements)\n// - Combinators `allOf`, `anyOf`, `oneOf` (searches each branch)\n// - `additionalProperties` when the property is not explicitly declared\n//\n// Rejects:\n// - Conditional schemas (`if/then/else`) — non-resolvable without runtime data\n\n// ─── Conditional Schema Detection ────────────────────────────────────────────\n// JSON Schema Draft v7 introduced `if/then/else` conditional schemas.\n// These are fundamentally non-resolvable during static analysis because\n// they depend on runtime data values. Rather than silently ignoring them\n// (which would produce incorrect results — missing properties, wrong types),\n// we fail fast with a clear error pointing to the exact location in the schema.\n\n/**\n * Recursively validates that a JSON Schema does not contain `if/then/else`\n * conditional keywords. Throws an `UnsupportedSchemaError` if any are found.\n *\n * This check traverses the entire schema tree, including:\n * - `properties` values\n * - `additionalProperties` (when it's a schema)\n * - `items` (single schema or tuple)\n * - `allOf`, `anyOf`, `oneOf` branches\n * - `not`\n * - `definitions` / `$defs` values\n *\n * A `Set<object>` is used to track visited schemas and prevent infinite loops\n * from circular structures.\n *\n * @param schema - The JSON Schema to validate\n * @param path - The current JSON pointer path (for error reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n *\n * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found\n *\n * @example\n * ```\n * // Throws UnsupportedSchemaError:\n * assertNoConditionalSchema({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // OK — no conditional keywords:\n * assertNoConditionalSchema({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function assertNoConditionalSchema(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): void {\n\t// Cycle protection — avoid infinite loops on circular schema structures\n\tif (visited.has(schema)) return;\n\tvisited.add(schema);\n\n\t// ── Detect if/then/else at the current level ─────────────────────────\n\tif (schema.if !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\t// `then` or `else` without `if` is unusual but still unsupported\n\tif (schema.then !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\tif (schema.else !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\n\t// ── Recurse into properties ──────────────────────────────────────────\n\tif (schema.properties) {\n\t\tfor (const [key, prop] of Object.entries(schema.properties)) {\n\t\t\tif (prop && typeof prop !== \"boolean\") {\n\t\t\t\tassertNoConditionalSchema(prop, `${path}/properties/${key}`, visited);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into additionalProperties ────────────────────────────────\n\tif (\n\t\tschema.additionalProperties &&\n\t\ttypeof schema.additionalProperties === \"object\"\n\t) {\n\t\tassertNoConditionalSchema(\n\t\t\tschema.additionalProperties,\n\t\t\t`${path}/additionalProperties`,\n\t\t\tvisited,\n\t\t);\n\t}\n\n\t// ── Recurse into items ───────────────────────────────────────────────\n\tif (schema.items) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let i = 0; i < schema.items.length; i++) {\n\t\t\t\tconst item = schema.items[i];\n\t\t\t\tif (item && typeof item !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(item, `${path}/items/${i}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof schema.items !== \"boolean\") {\n\t\t\tassertNoConditionalSchema(schema.items, `${path}/items`, visited);\n\t\t}\n\t}\n\n\t// ── Recurse into combinators ─────────────────────────────────────────\n\tfor (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n\t\tconst branches = schema[keyword];\n\t\tif (branches) {\n\t\t\tfor (let i = 0; i < branches.length; i++) {\n\t\t\t\tconst branch = branches[i];\n\t\t\t\tif (branch && typeof branch !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(branch, `${path}/${keyword}/${i}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into not ─────────────────────────────────────────────────\n\tif (schema.not && typeof schema.not !== \"boolean\") {\n\t\tassertNoConditionalSchema(schema.not, `${path}/not`, visited);\n\t}\n\n\t// ── Recurse into definitions / $defs ─────────────────────────────────\n\tfor (const defsKey of [\"definitions\", \"$defs\"] as const) {\n\t\tconst defs = schema[defsKey];\n\t\tif (defs) {\n\t\t\tfor (const [name, def] of Object.entries(defs)) {\n\t\t\t\tif (def && typeof def !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(def, `${path}/${defsKey}/${name}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ─── $ref Resolution ─────────────────────────────────────────────────────────\n// Only supports internal references in the format `#/definitions/Foo`\n// or `#/$defs/Foo` (JSON Schema Draft 2019+). Remote $refs (URLs) are\n// not supported — that is outside the scope of a template engine.\n\n/**\n * Recursively resolves `$ref` in a schema using the root schema as the\n * source of definitions.\n */\nexport function resolveRef(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 {\n\tif (!schema.$ref) return schema;\n\n\tconst ref = schema.$ref;\n\n\t// Expected format: #/definitions/Name or #/$defs/Name\n\tconst match = ref.match(/^#\\/(definitions|\\$defs)\\/(.+)$/);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Unsupported $ref format: \"${ref}\". Only internal #/definitions/ references are supported.`,\n\t\t);\n\t}\n\n\tconst defsKey = match[1] as \"definitions\" | \"$defs\";\n\tconst name = match[2] ?? \"\";\n\n\tconst defs = defsKey === \"definitions\" ? root.definitions : root.$defs;\n\n\tif (!defs || !(name in defs)) {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\n\t// Recursive resolution in case the definition itself contains a $ref\n\tconst def = defs[name];\n\tif (!def || typeof def === \"boolean\") {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\treturn resolveRef(def, root);\n}\n\n// ─── Single-Segment Path Navigation ─────────────────────────────────────────\n\n/**\n * Resolves a single path segment (a property name) within a schema.\n * Returns the corresponding sub-schema, or `undefined` if the path is invalid.\n *\n * @param schema - The current schema (already resolved, no $ref)\n * @param segment - The property name to resolve\n * @param root - The root schema (for resolving any internal $refs)\n */\nfunction resolveSegment(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// 1. Explicit properties\n\tif (resolved.properties && segment in resolved.properties) {\n\t\tconst prop = resolved.properties[segment];\n\t\tif (prop && typeof prop !== \"boolean\") return resolveRef(prop, root);\n\t\tif (prop === true) return {};\n\t}\n\n\t// 2. additionalProperties (when the property is not declared)\n\tif (\n\t\tresolved.additionalProperties !== undefined &&\n\t\tresolved.additionalProperties !== false\n\t) {\n\t\tif (resolved.additionalProperties === true) {\n\t\t\t// additionalProperties: true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\treturn resolveRef(resolved.additionalProperties, root);\n\t}\n\n\t// 3. Intrinsic array properties (e.g. `.length`)\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (isArray && segment === \"length\") {\n\t\treturn { type: \"integer\" };\n\t}\n\n\t// 4. Combinators — search within each branch\n\tconst combinatorResult = resolveInCombinators(resolved, segment, root);\n\tif (combinatorResult) return combinatorResult;\n\n\treturn undefined;\n}\n\n/**\n * Searches for a segment within `allOf`, `anyOf`, `oneOf` branches.\n * Returns the first matching sub-schema, or `undefined`.\n * For `allOf`, found results are merged into a single `allOf`.\n */\nfunction resolveInCombinators(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\t// allOf: the property can be defined in any branch, and all constraints\n\t// apply simultaneously.\n\tif (schema.allOf) {\n\t\tconst matches = schema.allOf\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { allOf: matches };\n\t}\n\n\t// anyOf / oneOf: the property can come from any branch.\n\tfor (const key of [\"anyOf\", \"oneOf\"] as const) {\n\t\tif (!schema[key]) continue;\n\t\tconst matches = schema[key]\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { [key]: matches };\n\t}\n\n\treturn undefined;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Resolves a full path (e.g. [\"user\", \"address\", \"city\"]) within a JSON\n * Schema and returns the corresponding sub-schema.\n *\n * @param schema - The root schema describing the template context\n * @param path - Array of segments (property names)\n * @returns The sub-schema at the end of the path, or `undefined` if the path\n * cannot be resolved.\n *\n * @example\n * ```\n * const schema = {\n * type: \"object\",\n * properties: {\n * user: {\n * type: \"object\",\n * properties: {\n * name: { type: \"string\" }\n * }\n * }\n * }\n * };\n * resolveSchemaPath(schema, [\"user\", \"name\"]);\n * // → { type: \"string\" }\n * ```\n */\nexport function resolveSchemaPath(\n\tschema: JSONSchema7,\n\tpath: string[],\n): JSONSchema7 | undefined {\n\tif (path.length === 0) return resolveRef(schema, schema);\n\n\tlet current: JSONSchema7 = resolveRef(schema, schema);\n\tconst root = schema;\n\n\tfor (const segment of path) {\n\t\tconst next = resolveSegment(current, segment, root);\n\t\tif (next === undefined) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the item schema of an array.\n * If the schema is not of type `array` or has no `items`, returns `undefined`.\n *\n * @param schema - The array schema\n * @param root - The root schema (for resolving $refs)\n */\nexport function resolveArrayItems(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// Verify that it's actually an array\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (!isArray && resolved.items === undefined) {\n\t\treturn undefined;\n\t}\n\n\tif (resolved.items === undefined) {\n\t\t// array without items → element type is unknown\n\t\treturn {};\n\t}\n\n\t// items can be a boolean (true = anything, false = nothing)\n\tif (typeof resolved.items === \"boolean\") {\n\t\treturn {};\n\t}\n\n\t// items can be a single schema or a tuple (array of schemas).\n\t// For template loops, we handle the single-schema case.\n\tif (Array.isArray(resolved.items)) {\n\t\t// Tuple: create a oneOf of all possible types\n\t\tconst schemas = resolved.items\n\t\t\t.filter((item): item is JSONSchema7 => typeof item !== \"boolean\")\n\t\t\t.map((item) => resolveRef(item, root));\n\t\tif (schemas.length === 0) return {};\n\t\treturn { oneOf: schemas };\n\t}\n\n\treturn resolveRef(resolved.items, root);\n}\n\n/**\n * Simplifies an output schema to avoid unnecessarily complex constructs\n * (e.g. `oneOf` with a single element, duplicates, etc.).\n *\n * Uses `deepEqual` for deduplication — more robust and performant than\n * `JSON.stringify` (independent of key order, no intermediate string\n * allocations).\n */\nexport function simplifySchema(schema: JSONSchema7): JSONSchema7 {\n\t// oneOf / anyOf with a single element → unwrap\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length === 1) {\n\t\t\tconst first = arr[0];\n\t\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\t\treturn simplifySchema(first);\n\t\t}\n\t}\n\n\t// allOf with a single element → unwrap\n\tif (schema.allOf && schema.allOf.length === 1) {\n\t\tconst first = schema.allOf[0];\n\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\treturn simplifySchema(first);\n\t}\n\n\t// Deduplicate identical entries in oneOf/anyOf\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length > 1) {\n\t\t\tconst unique: JSONSchema7[] = [];\n\t\t\tfor (const entry of arr) {\n\t\t\t\tif (typeof entry === \"boolean\") continue;\n\t\t\t\t// Use deepEqual instead of JSON.stringify for structural\n\t\t\t\t// comparison — more robust (key order independent) and\n\t\t\t\t// more performant (no string allocations).\n\t\t\t\tconst isDuplicate = unique.some((existing) =>\n\t\t\t\t\tdeepEqual(existing, entry),\n\t\t\t\t);\n\t\t\t\tif (!isDuplicate) {\n\t\t\t\t\tunique.push(simplifySchema(entry));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unique.length === 1) return unique[0] as JSONSchema7;\n\t\t\treturn { ...schema, [key]: unique };\n\t\t}\n\t}\n\n\treturn schema;\n}\n"],"names":["assertNoConditionalSchema","resolveArrayItems","resolveRef","resolveSchemaPath","simplifySchema","schema","path","visited","Set","has","add","if","undefined","UnsupportedSchemaError","then","else","properties","key","prop","Object","entries","additionalProperties","items","Array","isArray","i","length","item","keyword","branches","branch","not","defsKey","defs","name","def","root","$ref","ref","match","Error","definitions","$defs","resolveSegment","segment","resolved","schemaType","type","includes","combinatorResult","resolveInCombinators","allOf","matches","filter","b","map","s","current","next","schemas","oneOf","arr","first","unique","entry","isDuplicate","some","existing","deepEqual","push"],"mappings":"mPA8DgBA,mCAAAA,+BAoRAC,2BAAAA,uBApLAC,oBAAAA,gBA2JAC,2BAAAA,uBAyEAC,wBAAAA,0CAjYuB,sCACb,cA4DnB,SAASJ,0BACfK,MAAmB,CACnBC,KAAO,EAAE,CACTC,QAAuB,IAAIC,GAAK,EAGhC,GAAID,QAAQE,GAAG,CAACJ,QAAS,OACzBE,QAAQG,GAAG,CAACL,QAGZ,GAAIA,OAAOM,EAAE,GAAKC,UAAW,CAC5B,MAAM,IAAIC,gCAAsB,CAAC,eAAgBP,MAAQ,IAC1D,CAEA,GAAID,OAAOS,IAAI,GAAKF,UAAW,CAC9B,MAAM,IAAIC,gCAAsB,CAAC,eAAgBP,MAAQ,IAC1D,CACA,GAAID,OAAOU,IAAI,GAAKH,UAAW,C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,QAErB,GAAI,CAACC,YAAa,CACjBF,OAAOM,IAAI,CAACjE,eAAe4D,OAC5B,CACD,CACA,GAAID,OAAOrC,MAAM,GAAK,EAAG,OAAOqC,MAAM,CAAC,EAAE,CACzC,MAAO,CAAE,GAAG1D,MAAM,CAAE,CAACY,IAAI,CAAE8C,MAAO,CACnC,CACD,CAEA,OAAO1D,MACR"}
1
+ {"version":3,"sources":["../../src/schema-resolver.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { UnsupportedSchemaError } from \"./errors.ts\";\nimport { deepEqual } from \"./utils.ts\";\n\n// ─── JSON Schema Resolver ────────────────────────────────────────────────────\n// Utility for navigating a JSON Schema Draft v7 by following a property path\n// (e.g. [\"user\", \"address\", \"city\"]).\n//\n// Handles:\n// - `$ref` resolution (internal references #/definitions/...)\n// - Navigation through `properties`\n// - Navigation through `items` (array elements)\n// - Combinators `allOf`, `anyOf`, `oneOf` (searches each branch)\n// - `additionalProperties` when the property is not explicitly declared\n//\n// Rejects:\n// - Conditional schemas (`if/then/else`) — non-resolvable without runtime data\n\n// ─── Conditional Schema Detection ────────────────────────────────────────────\n// JSON Schema Draft v7 introduced `if/then/else` conditional schemas.\n// These are fundamentally non-resolvable during static analysis because\n// they depend on runtime data values. Rather than silently ignoring them\n// (which would produce incorrect results — missing properties, wrong types),\n// we fail fast with a clear error pointing to the exact location in the schema.\n\n/**\n * Recursively validates that a JSON Schema does not contain `if/then/else`\n * conditional keywords. Throws an `UnsupportedSchemaError` if any are found.\n *\n * This check traverses the entire schema tree, including:\n * - `properties` values\n * - `additionalProperties` (when it's a schema)\n * - `items` (single schema or tuple)\n * - `allOf`, `anyOf`, `oneOf` branches\n * - `not`\n * - `definitions` / `$defs` values\n *\n * A `Set<object>` is used to track visited schemas and prevent infinite loops\n * from circular structures.\n *\n * @param schema - The JSON Schema to validate\n * @param path - The current JSON pointer path (for error reporting)\n * @param visited - Set of already-visited schema objects (cycle protection)\n *\n * @throws {UnsupportedSchemaError} if `if`, `then`, or `else` is found\n *\n * @example\n * ```\n * // Throws UnsupportedSchemaError:\n * assertNoConditionalSchema({\n * type: \"object\",\n * if: { properties: { kind: { const: \"a\" } } },\n * then: { properties: { a: { type: \"string\" } } },\n * });\n *\n * // OK — no conditional keywords:\n * assertNoConditionalSchema({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * });\n * ```\n */\nexport function assertNoConditionalSchema(\n\tschema: JSONSchema7,\n\tpath = \"\",\n\tvisited: Set<object> = new Set(),\n): void {\n\t// Cycle protection — avoid infinite loops on circular schema structures\n\tif (visited.has(schema)) return;\n\tvisited.add(schema);\n\n\t// ── Detect if/then/else at the current level ─────────────────────────\n\tif (schema.if !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\t// `then` or `else` without `if` is unusual but still unsupported\n\tif (schema.then !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\tif (schema.else !== undefined) {\n\t\tthrow new UnsupportedSchemaError(\"if/then/else\", path || \"/\");\n\t}\n\n\t// ── Recurse into properties ──────────────────────────────────────────\n\tif (schema.properties) {\n\t\tfor (const [key, prop] of Object.entries(schema.properties)) {\n\t\t\tif (prop && typeof prop !== \"boolean\") {\n\t\t\t\tassertNoConditionalSchema(prop, `${path}/properties/${key}`, visited);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into additionalProperties ────────────────────────────────\n\tif (\n\t\tschema.additionalProperties &&\n\t\ttypeof schema.additionalProperties === \"object\"\n\t) {\n\t\tassertNoConditionalSchema(\n\t\t\tschema.additionalProperties,\n\t\t\t`${path}/additionalProperties`,\n\t\t\tvisited,\n\t\t);\n\t}\n\n\t// ── Recurse into items ───────────────────────────────────────────────\n\tif (schema.items) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let i = 0; i < schema.items.length; i++) {\n\t\t\t\tconst item = schema.items[i];\n\t\t\t\tif (item && typeof item !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(item, `${path}/items/${i}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (typeof schema.items !== \"boolean\") {\n\t\t\tassertNoConditionalSchema(schema.items, `${path}/items`, visited);\n\t\t}\n\t}\n\n\t// ── Recurse into combinators ─────────────────────────────────────────\n\tfor (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n\t\tconst branches = schema[keyword];\n\t\tif (branches) {\n\t\t\tfor (let i = 0; i < branches.length; i++) {\n\t\t\t\tconst branch = branches[i];\n\t\t\t\tif (branch && typeof branch !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(branch, `${path}/${keyword}/${i}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ── Recurse into not ─────────────────────────────────────────────────\n\tif (schema.not && typeof schema.not !== \"boolean\") {\n\t\tassertNoConditionalSchema(schema.not, `${path}/not`, visited);\n\t}\n\n\t// ── Recurse into definitions / $defs ─────────────────────────────────\n\tfor (const defsKey of [\"definitions\", \"$defs\"] as const) {\n\t\tconst defs = schema[defsKey];\n\t\tif (defs) {\n\t\t\tfor (const [name, def] of Object.entries(defs)) {\n\t\t\t\tif (def && typeof def !== \"boolean\") {\n\t\t\t\t\tassertNoConditionalSchema(def, `${path}/${defsKey}/${name}`, visited);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ─── $ref Resolution ─────────────────────────────────────────────────────────\n// Only supports internal references in the format `#/definitions/Foo`\n// or `#/$defs/Foo` (JSON Schema Draft 2019+). Remote $refs (URLs) are\n// not supported — that is outside the scope of a template engine.\n\n/**\n * Recursively resolves `$ref` in a schema using the root schema as the\n * source of definitions.\n */\nexport function resolveRef(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 {\n\tif (!schema.$ref) return schema;\n\n\tconst ref = schema.$ref;\n\n\t// Expected format: #/definitions/Name or #/$defs/Name\n\tconst match = ref.match(/^#\\/(definitions|\\$defs)\\/(.+)$/);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Unsupported $ref format: \"${ref}\". Only internal #/definitions/ references are supported.`,\n\t\t);\n\t}\n\n\tconst defsKey = match[1] as \"definitions\" | \"$defs\";\n\tconst name = match[2] ?? \"\";\n\n\tconst defs = defsKey === \"definitions\" ? root.definitions : root.$defs;\n\n\tif (!defs || !(name in defs)) {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\n\t// Recursive resolution in case the definition itself contains a $ref\n\tconst def = defs[name];\n\tif (!def || typeof def === \"boolean\") {\n\t\tthrow new Error(\n\t\t\t`Cannot resolve $ref \"${ref}\": definition \"${name}\" not found.`,\n\t\t);\n\t}\n\treturn resolveRef(def, root);\n}\n\n// ─── Single-Segment Path Navigation ─────────────────────────────────────────\n\n/**\n * Resolves a single path segment (a property name) within a schema.\n * Returns the corresponding sub-schema, or `undefined` if the path is invalid.\n *\n * @param schema - The current schema (already resolved, no $ref)\n * @param segment - The property name to resolve\n * @param root - The root schema (for resolving any internal $refs)\n */\nfunction resolveSegment(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// 1. Explicit properties\n\tif (resolved.properties && segment in resolved.properties) {\n\t\tconst prop = resolved.properties[segment];\n\t\tif (prop && typeof prop !== \"boolean\") return resolveRef(prop, root);\n\t\tif (prop === true) return {};\n\t}\n\n\t// 2. additionalProperties (when the property is not declared)\n\tif (\n\t\tresolved.additionalProperties !== undefined &&\n\t\tresolved.additionalProperties !== false\n\t) {\n\t\tif (resolved.additionalProperties === true) {\n\t\t\t// additionalProperties: true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\treturn resolveRef(resolved.additionalProperties, root);\n\t}\n\n\t// 3. Intrinsic array properties (e.g. `.length`)\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (isArray && segment === \"length\") {\n\t\treturn { type: \"integer\" };\n\t}\n\n\t// 3b. Numeric index access on arrays (e.g. `users.[0]` → items schema)\n\tif (isArray && /^\\d+$/.test(segment)) {\n\t\tif (resolved.items === undefined) {\n\t\t\t// array without items → element type is unknown\n\t\t\treturn {};\n\t\t}\n\t\tif (typeof resolved.items === \"boolean\") {\n\t\t\treturn {};\n\t\t}\n\t\t// Tuple: items is an array of schemas — resolve by index if possible\n\t\tif (Array.isArray(resolved.items)) {\n\t\t\tconst idx = Number.parseInt(segment, 10);\n\t\t\tconst item = resolved.items[idx];\n\t\t\tif (item !== undefined && typeof item !== \"boolean\") {\n\t\t\t\treturn resolveRef(item, root);\n\t\t\t}\n\t\t\tif (item !== undefined && typeof item === \"boolean\") {\n\t\t\t\treturn {};\n\t\t\t}\n\t\t\t// Index out of bounds for tuple → check additionalItems (Draft 7)\n\t\t\t// additionalItems: false → no additional elements allowed\n\t\t\tif (resolved.additionalItems === false) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// additionalItems: schema → additional elements have this type\n\t\t\tif (\n\t\t\t\tresolved.additionalItems !== undefined &&\n\t\t\t\tresolved.additionalItems !== true &&\n\t\t\t\ttypeof resolved.additionalItems === \"object\"\n\t\t\t) {\n\t\t\t\treturn resolveRef(resolved.additionalItems, root);\n\t\t\t}\n\t\t\t// additionalItems absent or true → type is unknown\n\t\t\treturn {};\n\t\t}\n\t\t// Single items schema — all elements share the same type\n\t\treturn resolveRef(resolved.items, root);\n\t}\n\n\t// 4. Combinators — search within each branch\n\tconst combinatorResult = resolveInCombinators(resolved, segment, root);\n\tif (combinatorResult) return combinatorResult;\n\n\treturn undefined;\n}\n\n/**\n * Searches for a segment within `allOf`, `anyOf`, `oneOf` branches.\n * Returns the first matching sub-schema, or `undefined`.\n * For `allOf`, found results are merged into a single `allOf`.\n */\nfunction resolveInCombinators(\n\tschema: JSONSchema7,\n\tsegment: string,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\t// allOf: the property can be defined in any branch, and all constraints\n\t// apply simultaneously.\n\tif (schema.allOf) {\n\t\tconst matches = schema.allOf\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { allOf: matches };\n\t}\n\n\t// anyOf / oneOf: the property can come from any branch.\n\tfor (const key of [\"anyOf\", \"oneOf\"] as const) {\n\t\tif (!schema[key]) continue;\n\t\tconst matches = schema[key]\n\t\t\t.filter((b): b is JSONSchema7 => typeof b !== \"boolean\")\n\t\t\t.map((branch) => resolveSegment(branch, segment, root))\n\t\t\t.filter((s): s is JSONSchema7 => s !== undefined);\n\n\t\tif (matches.length === 1) return matches[0] as JSONSchema7;\n\t\tif (matches.length > 1) return { [key]: matches };\n\t}\n\n\treturn undefined;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Resolves a full path (e.g. [\"user\", \"address\", \"city\"]) within a JSON\n * Schema and returns the corresponding sub-schema.\n *\n * @param schema - The root schema describing the template context\n * @param path - Array of segments (property names)\n * @returns The sub-schema at the end of the path, or `undefined` if the path\n * cannot be resolved.\n *\n * @example\n * ```\n * const schema = {\n * type: \"object\",\n * properties: {\n * user: {\n * type: \"object\",\n * properties: {\n * name: { type: \"string\" }\n * }\n * }\n * }\n * };\n * resolveSchemaPath(schema, [\"user\", \"name\"]);\n * // → { type: \"string\" }\n * ```\n */\nexport function resolveSchemaPath(\n\tschema: JSONSchema7,\n\tpath: string[],\n): JSONSchema7 | undefined {\n\tif (path.length === 0) return resolveRef(schema, schema);\n\n\tlet current: JSONSchema7 = resolveRef(schema, schema);\n\tconst root = schema;\n\n\tfor (const segment of path) {\n\t\tconst next = resolveSegment(current, segment, root);\n\t\tif (next === undefined) return undefined;\n\t\tcurrent = next;\n\t}\n\n\treturn current;\n}\n\n/**\n * Resolves the item schema of an array.\n * If the schema is not of type `array` or has no `items`, returns `undefined`.\n *\n * @param schema - The array schema\n * @param root - The root schema (for resolving $refs)\n */\nexport function resolveArrayItems(\n\tschema: JSONSchema7,\n\troot: JSONSchema7,\n): JSONSchema7 | undefined {\n\tconst resolved = resolveRef(schema, root);\n\n\t// Verify that it's actually an array\n\tconst schemaType = resolved.type;\n\tconst isArray =\n\t\tschemaType === \"array\" ||\n\t\t(Array.isArray(schemaType) && schemaType.includes(\"array\"));\n\n\tif (!isArray && resolved.items === undefined) {\n\t\treturn undefined;\n\t}\n\n\tif (resolved.items === undefined) {\n\t\t// array without items → element type is unknown\n\t\treturn {};\n\t}\n\n\t// items can be a boolean (true = anything, false = nothing)\n\tif (typeof resolved.items === \"boolean\") {\n\t\treturn {};\n\t}\n\n\t// items can be a single schema or a tuple (array of schemas).\n\t// For template loops, we handle the single-schema case.\n\tif (Array.isArray(resolved.items)) {\n\t\t// Tuple: create a oneOf of all possible types\n\t\tconst schemas = resolved.items\n\t\t\t.filter((item): item is JSONSchema7 => typeof item !== \"boolean\")\n\t\t\t.map((item) => resolveRef(item, root));\n\t\tif (schemas.length === 0) return {};\n\t\treturn { oneOf: schemas };\n\t}\n\n\treturn resolveRef(resolved.items, root);\n}\n\n/**\n * Simplifies an output schema to avoid unnecessarily complex constructs\n * (e.g. `oneOf` with a single element, duplicates, etc.).\n *\n * Uses `deepEqual` for deduplication — more robust and performant than\n * `JSON.stringify` (independent of key order, no intermediate string\n * allocations).\n */\nexport function simplifySchema(schema: JSONSchema7): JSONSchema7 {\n\t// oneOf / anyOf with a single element → unwrap\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length === 1) {\n\t\t\tconst first = arr[0];\n\t\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\t\treturn simplifySchema(first);\n\t\t}\n\t}\n\n\t// allOf with a single element → unwrap\n\tif (schema.allOf && schema.allOf.length === 1) {\n\t\tconst first = schema.allOf[0];\n\t\tif (first !== undefined && typeof first !== \"boolean\")\n\t\t\treturn simplifySchema(first);\n\t}\n\n\t// Deduplicate identical entries in oneOf/anyOf\n\tfor (const key of [\"oneOf\", \"anyOf\"] as const) {\n\t\tconst arr = schema[key];\n\t\tif (arr && arr.length > 1) {\n\t\t\tconst unique: JSONSchema7[] = [];\n\t\t\tfor (const entry of arr) {\n\t\t\t\tif (typeof entry === \"boolean\") continue;\n\t\t\t\t// Use deepEqual instead of JSON.stringify for structural\n\t\t\t\t// comparison — more robust (key order independent) and\n\t\t\t\t// more performant (no string allocations).\n\t\t\t\tconst isDuplicate = unique.some((existing) =>\n\t\t\t\t\tdeepEqual(existing, entry),\n\t\t\t\t);\n\t\t\t\tif (!isDuplicate) {\n\t\t\t\t\tunique.push(simplifySchema(entry));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (unique.length === 1) return unique[0] as JSONSchema7;\n\t\t\treturn { ...schema, [key]: unique };\n\t\t}\n\t}\n\n\treturn schema;\n}\n"],"names":["assertNoConditionalSchema","resolveArrayItems","resolveRef","resolveSchemaPath","simplifySchema","schema","path","visited","Set","has","add","if","undefined","UnsupportedSchemaError","then","else","properties","key","prop","Object","entries","additionalProperties","items","Array","isArray","i","length","item","keyword","branches","branch","not","defsKey","defs","name","def","root","$ref","ref","match","Error","definitions","$defs","resolveSegment","segment","resolved","schemaType","type","includes","test","idx","Number","parseInt","additionalItems","combinatorResult","resolveInCombinators","allOf","matches","filter","b","map","s","current","next","schemas","oneOf","arr","first","unique","entry","isDuplicate","some","existing","deepEqual","push"],"mappings":"mPA8DgBA,mCAAAA,+BA2TAC,2BAAAA,uBA3NAC,oBAAAA,gBAkMAC,2BAAAA,uBAyEAC,wBAAAA,0CAxauB,sCACb,cA4DnB,SAASJ,0BACfK,MAAmB,CACnBC,KAAO,EAAE,CACTC,QAAuB,IA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AO,CAAE,GAAG/D,MAAM,CAAE,CAACY,IAAI,CAAEmD,MAAO,CACnC,CACD,CAEA,OAAO/D,MACR"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"Typebars",{enumerable:true,get:function(){return Typebars}});const _handlebars=/*#__PURE__*/_interop_require_default(require("handlebars"));const _analyzerts=require("./analyzer.js");const _compiledtemplatets=require("./compiled-template.js");const _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _executorts=require("./executor.js");const _indexts=require("./helpers/index.js");const _parserts=require("./parser.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}function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}class Typebars{compile(template){if((0,_typests.isArrayInput)(template)){const children=[];for(const element of template){children.push(this.compile(element))}return _compiledtemplatets.CompiledTemplate.fromArray(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if((0,_typests.isObjectInput)(template)){const children={};for(const[key,value]of Object.entries(template)){children[key]=this.compile(value)}return _compiledtemplatets.CompiledTemplate.fromObject(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if((0,_typests.isLiteralInput)(template)){return _compiledtemplatets.CompiledTemplate.fromLiteral(template,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}const ast=this.getCachedAst(template);const options={helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache};return _compiledtemplatets.CompiledTemplate.fromTemplate(ast,template,options)}analyze(template,inputSchema={},options){return(0,_dispatchts.dispatchAnalyze)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);return(0,_analyzerts.analyzeFromAst)(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema})},(child,childOptions)=>this.analyze(child,inputSchema,childOptions))}validate(template,inputSchema={},options){const analysis=this.analyze(template,inputSchema,options);return{valid:analysis.valid,diagnostics:analysis.diagnostics}}isValidSyntax(template){if((0,_typests.isArrayInput)(template)){return template.every(v=>this.isValidSyntax(v))}if((0,_typests.isObjectInput)(template)){return Object.values(template).every(v=>this.isValidSyntax(v))}if((0,_typests.isLiteralInput)(template))return true;try{this.getCachedAst(template);return true}catch{return false}}execute(template,data,options){return(0,_dispatchts.dispatchExecute)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);if(options?.schema){const analysis=(0,_analyzerts.analyzeFromAst)(ast,tpl,options.schema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers});if(!analysis.valid){throw new _errorsts.TemplateAnalysisError(analysis.diagnostics)}}return(0,_executorts.executeFromAst)(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema})},(child,childOptions)=>this.execute(child,data,{...options,...childOptions}))}analyzeAndExecute(template,inputSchema={},data,options){return(0,_dispatchts.dispatchAnalyzeAndExecute)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);const analysis=(0,_analyzerts.analyzeFromAst)(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema});if(!analysis.valid){return{analysis,value:undefined}}const value=(0,_executorts.executeFromAst)(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema});return{analysis,value}},(child,childOptions)=>this.analyzeAndExecute(child,inputSchema,data,childOptions))}registerHelper(name,definition){this.helpers.set(name,definition);this.hbs.registerHelper(name,definition.fn);this.compilationCache.clear();return this}unregisterHelper(name){this.helpers.delete(name);this.hbs.unregisterHelper(name);this.compilationCache.clear();return this}hasHelper(name){return this.helpers.has(name)}clearCaches(){this.astCache.clear();this.compilationCache.clear()}getCachedAst(template){let ast=this.astCache.get(template);if(!ast){ast=(0,_parserts.parse)(template);this.astCache.set(template,ast)}return ast}constructor(options={}){_define_property(this,"hbs",void 0);_define_property(this,"astCache",void 0);_define_property(this,"compilationCache",void 0);_define_property(this,"helpers",new Map);this.hbs=_handlebars.default.create();this.astCache=new _utils.LRUCache(options.astCacheSize??256);this.compilationCache=new _utils.LRUCache(options.compilationCacheSize??256);new _indexts.MathHelpers().register(this);new _indexts.LogicalHelpers().register(this);if(options.helpers){for(const helper of options.helpers){const{name,...definition}=helper;this.registerHelper(name,definition)}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"Typebars",{enumerable:true,get:function(){return Typebars}});const _handlebars=/*#__PURE__*/_interop_require_default(require("handlebars"));const _analyzerts=require("./analyzer.js");const _compiledtemplatets=require("./compiled-template.js");const _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _executorts=require("./executor.js");const _indexts=require("./helpers/index.js");const _parserts=require("./parser.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}function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const DIRECT_EXECUTION_HELPER_NAMES=new Set([_indexts.CollectionHelpers.COLLECT_HELPER_NAME]);function stringifyForTemplate(value){if(value===null||value===undefined)return"";if(Array.isArray(value)){return value.map(item=>{if(item===null||item===undefined)return"";if(typeof item==="object")return JSON.stringify(item);return String(item)}).join(", ")}return String(value)}class Typebars{compile(template){if((0,_typests.isArrayInput)(template)){const children=[];for(const element of template){children.push(this.compile(element))}return _compiledtemplatets.CompiledTemplate.fromArray(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if((0,_typests.isObjectInput)(template)){const children={};for(const[key,value]of Object.entries(template)){children[key]=this.compile(value)}return _compiledtemplatets.CompiledTemplate.fromObject(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if((0,_typests.isLiteralInput)(template)){return _compiledtemplatets.CompiledTemplate.fromLiteral(template,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}const ast=this.getCachedAst(template);const options={helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache};return _compiledtemplatets.CompiledTemplate.fromTemplate(ast,template,options)}analyze(template,inputSchema={},options){return(0,_dispatchts.dispatchAnalyze)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);return(0,_analyzerts.analyzeFromAst)(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema})},(child,childOptions)=>this.analyze(child,inputSchema,childOptions))}validate(template,inputSchema={},options){const analysis=this.analyze(template,inputSchema,options);return{valid:analysis.valid,diagnostics:analysis.diagnostics}}isValidSyntax(template){if((0,_typests.isArrayInput)(template)){return template.every(v=>this.isValidSyntax(v))}if((0,_typests.isObjectInput)(template)){return Object.values(template).every(v=>this.isValidSyntax(v))}if((0,_typests.isLiteralInput)(template))return true;try{this.getCachedAst(template);return true}catch{return false}}execute(template,data,options){return(0,_dispatchts.dispatchExecute)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);if(options?.schema){const analysis=(0,_analyzerts.analyzeFromAst)(ast,tpl,options.schema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers});if(!analysis.valid){throw new _errorsts.TemplateAnalysisError(analysis.diagnostics)}}return(0,_executorts.executeFromAst)(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers})},(child,childOptions)=>this.execute(child,data,{...options,...childOptions}))}analyzeAndExecute(template,inputSchema={},data,options){return(0,_dispatchts.dispatchAnalyzeAndExecute)(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);const analysis=(0,_analyzerts.analyzeFromAst)(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema});if(!analysis.valid){return{analysis,value:undefined}}const value=(0,_executorts.executeFromAst)(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers});return{analysis,value}},(child,childOptions)=>this.analyzeAndExecute(child,inputSchema,data,childOptions))}registerHelper(name,definition){this.helpers.set(name,definition);if(DIRECT_EXECUTION_HELPER_NAMES.has(name)){this.hbs.registerHelper(name,(...args)=>{const hbsArgs=args.slice(0,-1);const raw=definition.fn(...hbsArgs);return stringifyForTemplate(raw)})}else{this.hbs.registerHelper(name,definition.fn)}this.compilationCache.clear();return this}unregisterHelper(name){this.helpers.delete(name);this.hbs.unregisterHelper(name);this.compilationCache.clear();return this}hasHelper(name){return this.helpers.has(name)}clearCaches(){this.astCache.clear();this.compilationCache.clear()}getCachedAst(template){let ast=this.astCache.get(template);if(!ast){ast=(0,_parserts.parse)(template);this.astCache.set(template,ast)}return ast}constructor(options={}){_define_property(this,"hbs",void 0);_define_property(this,"astCache",void 0);_define_property(this,"compilationCache",void 0);_define_property(this,"helpers",new Map);this.hbs=_handlebars.default.create();this.astCache=new _utils.LRUCache(options.astCacheSize??256);this.compilationCache=new _utils.LRUCache(options.compilationCacheSize??256);new _indexts.MathHelpers().register(this);new _indexts.LogicalHelpers().register(this);new _indexts.CollectionHelpers().register(this);if(options.helpers){for(const helper of options.helpers){const{name,...definition}=helper;this.registerHelper(name,definition)}}}}
2
2
  //# sourceMappingURL=typebars.js.map