From 4aada1d1246acaef183307dbe85f5f03196baa0b Mon Sep 17 00:00:00 2001 From: atinseau Date: Tue, 17 Mar 2026 17:44:54 +0100 Subject: [PATCH] feat(executor): add direct block execution for conditional blocks --- index.ts | 39 +- src/executor.ts | 88 ++++- tests/direct-block-execution.spec.ts | 557 +++++++++++++++++++++++++++ 3 files changed, 675 insertions(+), 9 deletions(-) create mode 100644 tests/direct-block-execution.spec.ts diff --git a/index.ts b/index.ts index 93df6e9..8190154 100644 --- a/index.ts +++ b/index.ts @@ -3,22 +3,47 @@ import { type TemplateInput, Typebars } from "./src"; const tp = new Typebars(); -const params = { accountId: "{{accountId}}", ok: "salut" }; +const params = { + names: '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', +}; -const coerceSchema = { +const coerceSchema = {} as JSONSchema7; + +const inputSchema = { type: "object", properties: { - ok: { type: "string", constraints: "IsUuid" }, - accountId: { type: "string", constraints: "IsUuid" }, + defaultNames: { + type: "array", + items: { + type: "string", + }, + }, + hasUsers: { + type: "boolean", + }, + users: { + type: "array", + items: { + type: "object", + properties: { + name: { + type: "string", + }, + }, + }, + }, }, } as JSONSchema7; const result = tp.analyzeAndExecute( params as TemplateInput, - undefined, - {}, + inputSchema, + { + hasUsers: false, + defaultNames: ["alice", "bob"], + users: [], + }, { - excludeTemplateExpression: true, coerceSchema, }, ); diff --git a/src/executor.ts b/src/executor.ts index 0d79ecf..9b1b4c4 100644 --- a/src/executor.ts +++ b/src/executor.ts @@ -198,10 +198,16 @@ export function executeFromAst( } // ── Case 3: single block (possibly surrounded by whitespace) ───────── - // Render via Handlebars then attempt to coerce the result to the - // detected literal type (number, boolean, null). + // For conditional blocks (#if/#unless), try to evaluate the condition + // and execute the selected branch directly to preserve non-string types + // (e.g. arrays from `map`). Falls back to Handlebars rendering. const singleBlock = getEffectivelySingleBlock(ast); if (singleBlock) { + const directResult = tryDirectBlockExecution(singleBlock, data, ctx); + if (directResult !== undefined) { + return directResult.value; + } + const merged = mergeDataWithIdentifiers(data, identifierData); const raw = renderWithHandlebars(template, merged, ctx); return coerceValue(raw, ctx?.coerceSchema); @@ -584,6 +590,84 @@ export function clearCompilationCache(): void { globalCompilationCache.clear(); } +// ─── Direct Block Execution ────────────────────────────────────────────────── +// For conditional blocks (#if/#unless), we can evaluate the condition directly +// and execute the selected branch through the type-preserving execution paths. +// This avoids Handlebars stringification when the branch contains helpers that +// return non-primitive values (e.g. `map` returning arrays). + +/** + * Attempts to execute a conditional block directly by evaluating its condition + * and executing the selected branch through type-preserving paths. + * + * Only handles `#if` and `#unless` blocks. Returns `{ value }` if the branch + * was executed directly, or `undefined` to fall back to Handlebars rendering. + */ +function tryDirectBlockExecution( + block: hbs.AST.BlockStatement, + data: unknown, + ctx?: ExecutorContext, +): { value: unknown } | undefined { + if (block.path.type !== "PathExpression") return undefined; + const helperName = (block.path as hbs.AST.PathExpression).original; + + // Only handle built-in conditional blocks + if (helperName !== "if" && helperName !== "unless") return undefined; + if (block.params.length !== 1) return undefined; + + // Evaluate the condition + const condition = resolveExpression( + block.params[0] as hbs.AST.Expression, + data, + ctx?.identifierData, + ctx?.helpers, + ); + + // Handlebars truthiness: empty arrays are falsy + let isTruthy: boolean; + if (Array.isArray(condition)) { + isTruthy = condition.length > 0; + } else { + isTruthy = !!condition; + } + if (helperName === "unless") isTruthy = !isTruthy; + + const branch = isTruthy ? block.program : block.inverse; + if (!branch) { + // No matching branch (e.g. falsy #if with no {{else}}) → empty string + return { value: "" }; + } + + // Try to execute the branch as a single expression (preserves types) + const singleExpr = getEffectivelySingleExpression(branch); + if (singleExpr) { + if (singleExpr.params.length === 0 && !singleExpr.hash) { + return { + value: resolveExpression( + singleExpr.path, + data, + ctx?.identifierData, + ctx?.helpers, + ), + }; + } + // Single expression with helper (e.g. {{map users "name"}}) + if (singleExpr.params.length > 0 || singleExpr.hash) { + const directResult = tryDirectHelperExecution(singleExpr, data, ctx); + if (directResult !== undefined) return directResult; + } + } + + // Try to execute the branch as a nested conditional block (recursive) + const nestedBlock = getEffectivelySingleBlock(branch); + if (nestedBlock) { + return tryDirectBlockExecution(nestedBlock, data, ctx); + } + + // Branch is too complex for direct execution → fall back + return undefined; +} + // ─── Direct Helper Execution ───────────────────────────────────────────────── // Some helpers (e.g. `map`) return non-primitive values (arrays, objects) // that Handlebars would stringify. For these helpers, we resolve their diff --git a/tests/direct-block-execution.spec.ts b/tests/direct-block-execution.spec.ts new file mode 100644 index 0000000..cadd7b7 --- /dev/null +++ b/tests/direct-block-execution.spec.ts @@ -0,0 +1,557 @@ +import { beforeEach, describe, expect, test } from "bun:test"; +import type { JSONSchema7 } from "json-schema"; +import { clearCompilationCache, execute } from "../src/executor.ts"; +import { Typebars } from "../src/typebars.ts"; + +// ─── Fixtures ──────────────────────────────────────────────────────────────── + +const usersSchema: JSONSchema7 = { + type: "object", + properties: { + hasUsers: { type: "boolean" }, + isAdmin: { type: "boolean" }, + enabled: { type: "boolean" }, + level: { type: "number" }, + defaultNames: { + type: "array", + items: { type: "string" }, + }, + fallbackIds: { + type: "array", + items: { type: "number" }, + }, + users: { + type: "array", + items: { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, + }, + }, + admins: { + type: "array", + items: { + type: "object", + properties: { + name: { type: "string" }, + }, + }, + }, + guests: { + type: "array", + items: { + type: "object", + properties: { + name: { type: "string" }, + }, + }, + }, + }, +}; + +const usersData = { + hasUsers: true, + isAdmin: true, + enabled: true, + level: 3, + defaultNames: ["default1", "default2"], + fallbackIds: [100, 200, 300], + users: [ + { name: "Alice", age: 30 }, + { name: "Bob", age: 25 }, + { name: "Charlie", age: 35 }, + ], + admins: [{ name: "Root" }, { name: "SuperUser" }], + guests: [{ name: "Guest1" }, { name: "Guest2" }], +}; + +// ─── Tests ─────────────────────────────────────────────────────────────────── + +describe("direct block execution — type preservation through conditionals", () => { + let tp: Typebars; + + beforeEach(() => { + clearCompilationCache(); + tp = new Typebars(); + }); + + // ── Basic #if with map helper ──────────────────────────────────────── + + describe("#if with map helper → preserves array", () => { + test("truthy condition: map inside #if returns array", () => { + const result = tp.execute( + '{{#if hasUsers}}{{map users "name"}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("falsy condition with else: map in else branch returns array", () => { + const result = tp.execute( + '{{#if hasUsers}}{{defaultNames}}{{else}}{{map users "name"}}{{/if}}', + { ...usersData, hasUsers: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("truthy condition with else: map in main branch, variable in else", () => { + const result = tp.execute( + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("falsy condition with else: variable in else returns array", () => { + const result = tp.execute( + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, hasUsers: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("both branches are map helpers → preserves array from truthy branch", () => { + const result = tp.execute( + '{{#if isAdmin}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Root", "SuperUser"]); + }); + + test("both branches are map helpers → preserves array from falsy branch", () => { + const result = tp.execute( + '{{#if isAdmin}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}', + { ...usersData, isAdmin: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Guest1", "Guest2"]); + }); + }); + + // ── #unless with map helper ────────────────────────────────────────── + + describe("#unless with map helper → preserves array", () => { + test("unless truthy (hasUsers=true): else branch with map returns array", () => { + const result = tp.execute( + '{{#unless hasUsers}}{{defaultNames}}{{else}}{{map users "name"}}{{/unless}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("unless truthy: main branch variable returns array", () => { + const result = tp.execute( + '{{#unless hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/unless}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("unless falsy: map in main branch returns array", () => { + const result = tp.execute( + '{{#unless hasUsers}}{{map users "name"}}{{/unless}}', + { ...usersData, hasUsers: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + }); + + // ── Nested #if blocks ──────────────────────────────────────────────── + + describe("nested #if blocks → preserves array through nesting", () => { + test("two levels of #if: map at innermost level", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#if isAdmin}}{{map admins "name"}}{{/if}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Root", "SuperUser"]); + }); + + test("two levels of #if: inner condition falsy → else branch", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#if isAdmin}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}{{/if}}', + { ...usersData, isAdmin: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Guest1", "Guest2"]); + }); + + test("two levels of #if: outer condition falsy → outer else", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#if isAdmin}}{{map admins "name"}}{{/if}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, hasUsers: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("three levels of #if nesting", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#if isAdmin}}{{#if enabled}}{{map admins "name"}}{{/if}}{{/if}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Root", "SuperUser"]); + }); + + test("three levels: deepest condition falsy → else branch", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#if isAdmin}}{{#if enabled}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}{{/if}}{{/if}}', + { ...usersData, enabled: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Guest1", "Guest2"]); + }); + + test("nested #if + #unless combination", () => { + const result = tp.execute( + '{{#if hasUsers}}{{#unless isAdmin}}{{map guests "name"}}{{else}}{{map admins "name"}}{{/unless}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Root", "SuperUser"]); + }); + }); + + // ── #if with variable reference (non-helper) preserves type ────────── + + describe("#if with direct variable reference → preserves type", () => { + test("truthy: direct array variable in main branch", () => { + const result = execute( + "{{#if hasUsers}}{{defaultNames}}{{else}}{{fallbackIds}}{{/if}}", + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("falsy: direct array variable in else branch", () => { + const result = execute( + "{{#if hasUsers}}{{defaultNames}}{{else}}{{fallbackIds}}{{/if}}", + { ...usersData, hasUsers: false }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual([100, 200, 300]); + }); + + test("truthy: preserves object type", () => { + const data = { + flag: true, + objA: { x: 1, y: 2 }, + objB: { x: 10, y: 20 }, + }; + const result = execute( + "{{#if flag}}{{objA}}{{else}}{{objB}}{{/if}}", + data, + ); + expect(result).toEqual({ x: 1, y: 2 }); + }); + + test("falsy: preserves object type in else branch", () => { + const data = { + flag: false, + objA: { x: 1, y: 2 }, + objB: { x: 10, y: 20 }, + }; + const result = execute( + "{{#if flag}}{{objA}}{{else}}{{objB}}{{/if}}", + data, + ); + expect(result).toEqual({ x: 10, y: 20 }); + }); + + test("truthy: preserves number type", () => { + const result = execute( + "{{#if hasUsers}}{{level}}{{else}}{{level}}{{/if}}", + usersData, + ); + expect(result).toBe(3); + expect(typeof result).toBe("number"); + }); + + test("truthy: preserves boolean type", () => { + const result = execute( + "{{#if hasUsers}}{{isAdmin}}{{else}}{{enabled}}{{/if}}", + usersData, + ); + expect(result).toBe(true); + expect(typeof result).toBe("boolean"); + }); + }); + + // ── Edge cases ─────────────────────────────────────────────────────── + + describe("edge cases", () => { + test("empty array condition is falsy (Handlebars semantics)", () => { + const result = tp.execute( + '{{#if users}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, users: [] }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("non-empty array condition is truthy", () => { + const result = tp.execute( + '{{#if users}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("#if with no else, falsy condition → empty string", () => { + const result = tp.execute('{{#if hasUsers}}{{map users "name"}}{{/if}}', { + ...usersData, + hasUsers: false, + }); + expect(result).toBe(""); + }); + + test("#unless with no else, truthy condition → empty string", () => { + const result = tp.execute( + '{{#unless hasUsers}}{{map users "name"}}{{/unless}}', + usersData, + ); + expect(result).toBe(""); + }); + + test("map returning empty array is preserved through #if", () => { + const result = tp.execute('{{#if hasUsers}}{{map users "name"}}{{/if}}', { + ...usersData, + users: [], + }); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual([]); + }); + + test("map returning single-element array through #if", () => { + const result = tp.execute('{{#if hasUsers}}{{map users "name"}}{{/if}}', { + ...usersData, + users: [{ name: "Solo" }], + }); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Solo"]); + }); + + test("map returning number array through #if", () => { + const result = tp.execute( + '{{#if hasUsers}}{{map users "age"}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual([30, 25, 35]); + }); + + test("condition on undefined value → falsy", () => { + const result = tp.execute( + '{{#if missingVar}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("condition on null value → falsy", () => { + const result = tp.execute( + '{{#if nullVal}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, nullVal: null }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("condition on zero → falsy", () => { + const result = tp.execute( + '{{#if count}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, count: 0 }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("condition on empty string → falsy", () => { + const result = tp.execute( + '{{#if label}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + { ...usersData, label: "" }, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("whitespace around block does not break direct execution", () => { + const result = tp.execute( + ' {{#if hasUsers}}{{map users "name"}}{{/if}} ', + usersData, + ); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + }); + + // ── analyzeAndExecute integration ──────────────────────────────────── + + describe("analyzeAndExecute integration", () => { + test("map inside #if/else: analysis valid, value is array", () => { + const { analysis, value } = tp.analyzeAndExecute( + { + names: + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + }, + usersSchema, + usersData, + ); + expect(analysis.valid).toBe(true); + const v = value as Record; + expect(Array.isArray(v.names)).toBe(true); + expect(v.names).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("map inside #if/else falsy: analysis valid, value is array from else", () => { + const { analysis, value } = tp.analyzeAndExecute( + { + names: + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + }, + usersSchema, + { ...usersData, hasUsers: false }, + ); + expect(analysis.valid).toBe(true); + const v = value as Record; + expect(Array.isArray(v.names)).toBe(true); + expect(v.names).toEqual(["default1", "default2"]); + }); + + test("multiple fields with conditional maps", () => { + const { analysis, value } = tp.analyzeAndExecute( + { + names: + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + roleNames: + '{{#if isAdmin}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}', + }, + usersSchema, + usersData, + ); + expect(analysis.valid).toBe(true); + const v = value as Record; + expect(v.names).toEqual(["Alice", "Bob", "Charlie"]); + expect(v.roleNames).toEqual(["Root", "SuperUser"]); + }); + + test("nested #if with analyzeAndExecute", () => { + const { analysis, value } = tp.analyzeAndExecute( + { + names: + '{{#if hasUsers}}{{#if isAdmin}}{{map admins "name"}}{{else}}{{map users "name"}}{{/if}}{{/if}}', + }, + usersSchema, + usersData, + ); + expect(analysis.valid).toBe(true); + const v = value as Record; + expect(v.names).toEqual(["Root", "SuperUser"]); + }); + }); + + // ── compile() integration ──────────────────────────────────────────── + + describe("compile() integration", () => { + test("compiled template preserves array through #if", () => { + const compiled = tp.compile( + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + ); + const result = compiled.execute(usersData); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Alice", "Bob", "Charlie"]); + }); + + test("compiled template preserves array in else branch", () => { + const compiled = tp.compile( + '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}', + ); + const result = compiled.execute({ ...usersData, hasUsers: false }); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["default1", "default2"]); + }); + + test("compiled nested #if preserves array", () => { + const compiled = tp.compile( + '{{#if hasUsers}}{{#if isAdmin}}{{map admins "name"}}{{else}}{{map guests "name"}}{{/if}}{{/if}}', + ); + const result = compiled.execute(usersData); + expect(Array.isArray(result)).toBe(true); + expect(result).toEqual(["Root", "SuperUser"]); + }); + }); + + // ── Fallback to Handlebars (complex branches) ──────────────────────── + + describe("fallback: complex branches still render via Handlebars", () => { + test("#if with text + expression in branch → string", () => { + const result = execute( + "{{#if hasUsers}}Hello {{level}}{{else}}Bye{{/if}}", + usersData, + ); + expect(result).toBe("Hello 3"); + expect(typeof result).toBe("string"); + }); + + test("#if with #each in branch → string (falls back to Handlebars)", () => { + const result = tp.execute( + "{{#if hasUsers}}{{#each users}}{{name}} {{/each}}{{else}}none{{/if}}", + usersData, + ); + expect(result).toBe("Alice Bob Charlie "); + expect(typeof result).toBe("string"); + }); + + test("literal coercion still works in fallback path", () => { + const result = execute("{{#if hasUsers}}42{{else}}0{{/if}}", usersData); + expect(result).toBe(42); + expect(typeof result).toBe("number"); + }); + + test("boolean literal coercion still works in fallback path", () => { + const result = execute( + "{{#if hasUsers}}true{{else}}false{{/if}}", + usersData, + ); + expect(result).toBe(true); + expect(typeof result).toBe("boolean"); + }); + }); + + // ── Mixed template: #if inside text → remains a string ─────────────── + + describe("mixed template: #if inside text → string (no direct execution)", () => { + test("text before #if with map → string with comma-joined array", () => { + const result = tp.execute( + 'Names: {{#if hasUsers}}{{map users "name"}}{{/if}}', + usersData, + ); + expect(typeof result).toBe("string"); + expect(result).toBe("Names: Alice, Bob, Charlie"); + }); + + test("text after #if with map → string", () => { + const result = tp.execute( + '{{#if hasUsers}}{{map users "name"}}{{/if}} done', + usersData, + ); + expect(typeof result).toBe("string"); + expect(result).toBe("Alice, Bob, Charlie done"); + }); + }); +});