Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions src/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,10 @@ function resolveExpressionWithDiagnostics(
* a plain `{{$root}}`. Instead of navigating into properties, it returns
* the identifier's root schema directly.
*
* When the identifier schema is an array (aggregated multi-version data),
* the full array schema is returned as-is — the caller receives the
* complete `{ type: "array", items: ... }` schema.
*
* Emits an error diagnostic if:
* - No `identifierSchemas` were provided
* - Identifier N has no associated schema
Expand Down Expand Up @@ -1138,14 +1142,22 @@ function resolveRootWithIdentifier(
return undefined;
}

// Return the entire schema for identifier N
// Return the entire schema for identifier N.
// For aggregated identifiers (array schemas), this returns the full
// array schema — e.g. { type: "array", items: { type: "object", ... } }
return idSchema;
}

/**
* Resolves an expression with identifier `{{key:N}}` by looking up the
* schema associated with identifier N.
*
* When the identifier schema is an array (aggregated multi-version data),
* the property is resolved within the array's `items` schema, and the
* result is wrapped in `{ type: "array", items: <resolved> }`. This
* models the runtime behavior where `{{accountId:4}}` on an array of
* objects extracts the property from each element, producing an array.
*
* Emits an error diagnostic if:
* - No `identifierSchemas` were provided
* - Identifier N has no associated schema
Expand Down Expand Up @@ -1186,7 +1198,41 @@ function resolveWithIdentifier(
return undefined;
}

// Resolve the path within the identifier's schema
// ── Aggregated identifier (array schema) ─────────────────────────────
// When the identifier schema is an array of objects (e.g. from a
// multi-versioned workflow node), resolve the property within the
// items schema and wrap the result in an array type.
//
// Example: identifierSchemas[4] = { type: "array", items: { type: "object",
// properties: { accountId: { type: "string" } } } }
// Expression: {{accountId:4}}
// Result: { type: "array", items: { type: "string" } }
const itemSchema = resolveArrayItems(idSchema, ctx.root);
if (itemSchema !== undefined) {
// The identifier schema is an array — resolve within items
const resolved = resolveSchemaPath(itemSchema, cleanSegments);
if (resolved === undefined) {
const availableProperties = getSchemaPropertyNames(itemSchema);
addDiagnostic(
ctx,
"IDENTIFIER_PROPERTY_NOT_FOUND",
"error",
`Property "${fullPath}" does not exist in the items schema for identifier ${identifier}`,
node,
{
path: fullPath,
identifier,
availableProperties,
},
);
return undefined;
}
// Wrap the resolved property schema in an array
return { type: "array", items: resolved };
}

// ── Standard identifier (single object schema) ───────────────────────
// Resolve the path within the identifier's schema directly.
const resolved = resolveSchemaPath(idSchema, cleanSegments);
if (resolved === undefined) {
const availableProperties = getSchemaPropertyNames(idSchema);
Expand Down
3 changes: 2 additions & 1 deletion src/compiled-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
AnalysisResult,
ExecuteOptions,
HelperDefinition,
IdentifierData,
TemplateData,
ValidationResult,
} from "./types.ts";
Expand Down Expand Up @@ -392,7 +393,7 @@ export class CompiledTemplate {
data: TemplateData,
options?: {
identifierSchemas?: Record<number, JSONSchema7>;
identifierData?: Record<number, Record<string, unknown>>;
identifierData?: IdentifierData;
coerceSchema?: JSONSchema7;
},
): { analysis: AnalysisResult; value: unknown } {
Expand Down
4 changes: 2 additions & 2 deletions src/dispatch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { JSONSchema7 } from "json-schema";
import { hasHandlebarsExpression } from "./parser.ts";
import { resolveSchemaPath } from "./schema-resolver.ts";
import type { AnalysisResult, TemplateInput } from "./types.ts";
import type { AnalysisResult, IdentifierData, TemplateInput } from "./types.ts";
import {
inferPrimitiveSchema,
isArrayInput,
Expand Down Expand Up @@ -219,7 +219,7 @@ export function dispatchExecute(
/** Options for combined analyze-and-execute dispatching */
export interface DispatchAnalyzeAndExecuteOptions {
identifierSchemas?: Record<number, JSONSchema7>;
identifierData?: Record<number, Record<string, unknown>>;
identifierData?: IdentifierData;
coerceSchema?: JSONSchema7;
/** When true, exclude entries containing Handlebars expressions */
excludeTemplateExpression?: boolean;
Expand Down
47 changes: 39 additions & 8 deletions src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ import {
parse,
ROOT_TOKEN,
} from "./parser.ts";
import type { HelperDefinition, TemplateInput } from "./types.ts";
import type {
HelperDefinition,
IdentifierData,
TemplateInput,
} from "./types.ts";
import { LRUCache } from "./utils.ts";

// ─── Template Executor ───────────────────────────────────────────────────────
Expand Down Expand Up @@ -58,8 +62,14 @@ import { LRUCache } from "./utils.ts";

/** Optional context for execution (used by Typebars/CompiledTemplate) */
export interface ExecutorContext {
/** Data by identifier `{ [id]: { key: value } }` */
identifierData?: Record<number, Record<string, unknown>>;
/**
* Data by identifier `{ [id]: { key: value } }`.
*
* Each identifier can map to a single object (standard) or an array
* of objects (aggregated multi-version data). When the value is an
* array, `{{key:N}}` extracts the property from each element.
*/
identifierData?: IdentifierData;
/** Pre-compiled Handlebars template (for CompiledTemplate) */
compiledTemplate?: HandlebarsTemplateDelegate;
/** Isolated Handlebars environment (for custom helpers) */
Expand Down Expand Up @@ -100,7 +110,7 @@ const globalCompilationCache = new LRUCache<string, HandlebarsTemplateDelegate>(
export function execute(
template: TemplateInput,
data: unknown,
identifierData?: Record<number, Record<string, unknown>>,
identifierData?: IdentifierData,
): unknown {
return dispatchExecute(
template,
Expand Down Expand Up @@ -274,7 +284,7 @@ function coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown {
function executeFastPath(
ast: hbs.AST.Program,
data: unknown,
identifierData?: Record<number, Record<string, unknown>>,
identifierData?: IdentifierData,
): string {
let result = "";

Expand Down Expand Up @@ -316,7 +326,7 @@ function executeFastPath(
function resolveExpression(
expr: hbs.AST.Expression,
data: unknown,
identifierData?: Record<number, Record<string, unknown>>,
identifierData?: IdentifierData,
helpers?: Map<string, HelperDefinition>,
): unknown {
// this / . → return the entire context
Expand Down Expand Up @@ -398,6 +408,16 @@ function resolveExpression(
if (identifier !== null && identifierData) {
const source = identifierData[identifier];
if (source) {
// ── Aggregated identifier (array of objects) ──────────────────
// When the identifier maps to an array of objects (multi-version
// data), extract the property from each element to produce a
// result array. E.g. {{accountId:4}} on [{accountId:"A"},{accountId:"B"}]
// → ["A", "B"]
if (Array.isArray(source)) {
return source
.map((item) => resolveDataPath(item, cleanSegments))
.filter((v) => v !== undefined);
}
return resolveDataPath(source, cleanSegments);
}
// Source does not exist → undefined (like a missing key)
Expand Down Expand Up @@ -465,7 +485,7 @@ export function resolveDataPath(data: unknown, segments: string[]): unknown {
*/
function mergeDataWithIdentifiers(
data: unknown,
identifierData?: Record<number, Record<string, unknown>>,
identifierData?: IdentifierData,
): Record<string, unknown> {
// Always include $root so that Handlebars can resolve {{$root}} in
// mixed templates and block helpers (where we delegate to Handlebars
Expand All @@ -483,9 +503,20 @@ function mergeDataWithIdentifiers(
for (const [id, idData] of Object.entries(identifierData)) {
// Add `$root:N` so Handlebars can resolve {{$root:N}} in mixed/block
// templates (where we delegate to Handlebars instead of resolving
// expressions ourselves). The value is the entire identifier data object.
// expressions ourselves). The value is the entire identifier data
// object (or array for aggregated identifiers).
merged[`${ROOT_TOKEN}:${id}`] = idData;

// ── Aggregated identifier (array of objects) ─────────────────
// When the identifier data is an array (multi-version), we cannot
// flatten individual properties into `"key:N"` keys because there
// are multiple values per key. The array is only accessible via
// `$root:N` (already set above). Handlebars helpers like `map`
// can then consume it: `{{ map ($root:4) "accountId" }}`.
if (Array.isArray(idData)) {
continue;
}

for (const [key, value] of Object.entries(idData)) {
merged[`${key}:${id}`] = value;
}
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ export * from "./errors";
export { Typebars } from "./typebars";
export {
defineHelper,
type IdentifierData,
type IdentifierDataEntry,
isArrayInput,
type TemplateData,
type TemplateInput,
Expand Down
57 changes: 53 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,43 @@
import type { JSONSchema7 } from "json-schema";
import type { FromSchema, JSONSchema } from "json-schema-to-ts";

// ─── Identifier Data ─────────────────────────────────────────────────────────
// Maps template identifier integers to their associated data objects.
//
// Each identifier can hold either:
// - A **single object** — the standard case (one data source per identifier)
// - An **array of objects** — the aggregated case (multiple versions of a
// node merged into a collection, e.g. from a multi-versioned workflow node)
//
// When the value is an array, expressions like `{{key:N}}` automatically
// extract the property from each element, producing a result array.
// The full array is accessible via `{{$root:N}}` and can be used with
// the `map` helper: `{{ map ($root:N) "property" }}`.

/**
* Data associated with a single template identifier.
*
* Can be a single record (scalar case) or an array of records
* (aggregated multi-version case).
*/
export type IdentifierDataEntry =
| Record<string, unknown>
| Record<string, unknown>[];

/**
* Mapping from template identifier integers to their data.
*
* @example
* ```ts
* // Scalar identifiers (standard)
* { 1: { meetingId: "abc" }, 2: { name: "Alice" } }
*
* // Aggregated identifier (multi-version node)
* { 4: [{ accountId: "A" }, { accountId: "B" }, { accountId: "C" }] }
* ```
*/
export type IdentifierData = Record<number, IdentifierDataEntry>;

// ─── Template Input ──────────────────────────────────────────────────────────
// The engine accepts primitive values in addition to template strings.
// When a non-string value is passed, it is treated as a literal passthrough:
Expand Down Expand Up @@ -309,8 +346,14 @@ export interface CommonTypebarsOptions {
export interface ExecuteOptions extends CommonTypebarsOptions {
/** JSON Schema for pre-execution static validation */
schema?: JSONSchema7;
/** Data by identifier `{ [id]: { key: value } }` */
identifierData?: Record<number, Record<string, unknown>>;
/**
* Data by identifier `{ [id]: { key: value } }`.
*
* Each identifier can map to a single object (standard) or an array
* of objects (aggregated multi-version data). When the value is an
* array, `{{key:N}}` extracts the property from each element.
*/
identifierData?: IdentifierData;
/** Schemas by identifier (for static validation with identifiers) */
identifierSchemas?: Record<number, JSONSchema7>;
}
Expand All @@ -322,8 +365,14 @@ export interface ExecuteOptions extends CommonTypebarsOptions {
export interface AnalyzeAndExecuteOptions extends CommonTypebarsOptions {
/** Schemas by identifier `{ [id]: JSONSchema7 }` for static analysis */
identifierSchemas?: Record<number, JSONSchema7>;
/** Data by identifier `{ [id]: { key: value } }` for execution */
identifierData?: Record<number, Record<string, unknown>>;
/**
* Data by identifier `{ [id]: { key: value } }` for execution.
*
* Each identifier can map to a single object (standard) or an array
* of objects (aggregated multi-version data). When the value is an
* array, `{{key:N}}` extracts the property from each element.
*/
identifierData?: IdentifierData;
}

// ─── Custom Helpers ──────────────────────────────────────────────────────────
Expand Down
Loading
Loading