Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(commons): move the safe template evaluator out of trilium-core
Claude570bb63c4bf0
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 558762485d..91ff515a0c 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -4,6 +4,7 @@ export * from "./lib/options_interface.js";export * from "./lib/keyboard_actions_interface.js";export * from "./lib/hidden_subtree.js";export * from "./lib/rows.js";+export * from "./lib/safe_template.js";export * from "./lib/test-utils.js";export * from "./lib/attachment_roles.js";export * from "./lib/custom_fonts.js";diff --git a/packages/commons/src/lib/safe_template.spec.ts b/packages/commons/src/lib/safe_template.spec.tsnew file mode 100644index 0000000000..eff44b375b--- /dev/null+++ b/packages/commons/src/lib/safe_template.spec.ts@@ -0,0 +1,181 @@+import { describe, expect, it } from "vitest";++import { evaluateTemplate } from "./safe_template.js";++/**+ * A stand-in for the note-like objects passed into template evaluation. Only the+ * whitelisted properties/methods are exercised; method calls record their args so+ * we can assert the single string literal is forwarded verbatim.+ */+function fakeNote(overrides: Record<string, unknown> = {}) {+ return {+ title: "My Note",+ type: "text",+ noteId: "abc123",+ getLabelValue: (name: string) => `label:${name}`,+ getRelationValue: (name: string) => `relation:${name}`,+ format: (fmt: string) => `formatted(${fmt})`,+ ...overrides+ };+}++describe("safe_template - evaluateTemplate", () => {+ it("returns literal text unchanged when there are no expressions", () => {+ expect(evaluateTemplate("just text", {})).toBe("just text");+ });++ it("resolves a bare variable reference", () => {+ expect(evaluateTemplate("${note}", { note: "value" })).toBe("value");+ });++ it("resolves a single-level property access", () => {+ expect(evaluateTemplate("${note.title}", { note: fakeNote() })).toBe(+ "My Note"+ );+ });++ it("resolves a multi-level property chain (both segments whitelisted)", () => {+ // `content` and `title` are both whitelisted, so a two-hop chain resolves.+ const note = fakeNote({ content: { title: "inner" } });+ expect(evaluateTemplate("${note.content.title}", { note })).toBe(+ "inner"+ );+ });++ it("interpolates multiple expressions mixed with literal text", () => {+ const note = fakeNote();+ expect(evaluateTemplate("[${note.type}] ${note.title}", { note })).toBe(+ "[text] My Note"+ );+ });++ it("calls a whitelisted method with a single-quoted string argument", () => {+ const note = fakeNote();+ expect(+ evaluateTemplate("${note.getLabelValue('authorName')}", { note })+ ).toBe("label:authorName");+ });++ it("calls a whitelisted method with a double-quoted string argument", () => {+ const note = fakeNote();+ expect(evaluateTemplate('${note.format("YYYY-MM-DD")}', { note })).toBe(+ "formatted(YYYY-MM-DD)"+ );+ });++ it("calls a whitelisted method through a property chain", () => {+ const note = fakeNote({+ dateCreatedObj: { format: (f: string) => `date(${f})` }+ });+ expect(+ evaluateTemplate("${note.dateCreatedObj.format('MM-DD')}", {+ note+ })+ ).toBe("date(MM-DD)");+ });++ it("calls a whitelisted no-arg method", () => {+ const note = fakeNote({ getLabelValue: () => "no-arg-value" });+ expect(evaluateTemplate("${note.getLabelValue()}", { note })).toBe(+ "no-arg-value"+ );+ });++ it("returns empty string when a no-arg method target along the chain is null", () => {+ // `dateCreatedObj` is whitelisted but null, so the chain resolves to null+ // and the no-arg method call short-circuits to null (rendered empty).+ const note = fakeNote({ dateCreatedObj: null });+ expect(evaluateTemplate("${note.dateCreatedObj.format()}", { note })).toBe(+ ""+ );+ });++ it("renders null/undefined results as an empty string", () => {+ expect(+ evaluateTemplate("[${note.title}]", {+ note: fakeNote({ title: null })+ })+ ).toBe("[]");+ expect(+ evaluateTemplate("[${note.title}]", {+ note: fakeNote({ title: undefined })+ })+ ).toBe("[]");+ });++ it("returns empty string when a method target along the chain is null", () => {+ // resolvePropertyChain yields null because the root variable itself is null.+ expect(+ evaluateTemplate("${note.getLabelValue('x')}", { note: null })+ ).toBe("");+ });++ it("returns null (rendered empty) when a property on a null intermediate is accessed", () => {+ expect(evaluateTemplate("[${note.title}]", { note: null })).toBe("[]");+ });++ it("treats an empty string argument as a valid method argument", () => {+ const note = fakeNote({ getLabelValue: (name: string) => `[${name}]` });+ expect(evaluateTemplate("${note.getLabelValue('')}", { note })).toBe(+ "[]"+ );+ });+});++describe("safe_template - rejected expressions", () => {+ it("throws for an unknown root variable", () => {+ expect(() => evaluateTemplate("${missing.title}", {})).toThrow(+ /Unknown variable 'missing'/+ );+ });++ it("throws for a non-whitelisted property", () => {+ const note = fakeNote({ constructor: "evil" });+ expect(() => evaluateTemplate("${note.constructor}", { note })).toThrow(+ /Property 'constructor' is not allowed/+ );+ });++ it("throws for a non-whitelisted method", () => {+ const note = fakeNote({ toString: () => "boom" });+ expect(() => evaluateTemplate("${note.toString()}", { note })).toThrow(+ /Method 'toString' is not allowed/+ );+ });++ it("throws for a non-whitelisted method with an argument", () => {+ const note = fakeNote({ eval: (s: string) => s });+ expect(() => evaluateTemplate("${note.eval('1+1')}", { note })).toThrow(+ /Method 'eval' is not allowed/+ );+ });++ it("throws when a whitelisted method name resolves to a non-function", () => {+ // `format` is whitelisted but here it is a plain string, not callable.+ const note = fakeNote({ format: "not a function" });+ expect(() => evaluateTemplate("${note.format('x')}", { note })).toThrow(+ /'format' is not a function/+ );+ });++ it("throws when a whitelisted no-arg method name resolves to a non-function", () => {+ const note = fakeNote({ getLabelValue: 42 });+ expect(() =>+ evaluateTemplate("${note.getLabelValue()}", { note })+ ).toThrow(/'getLabelValue' is not a function/);+ });++ it("throws for syntactically unsupported expressions", () => {+ expect(() => evaluateTemplate("${1 + 1}", {})).toThrow(+ /is not a supported expression/+ );+ expect(() =>+ evaluateTemplate("${note['title']}", { note: fakeNote() })+ ).toThrow(/is not a supported expression/);+ expect(() =>+ evaluateTemplate("${note.method(unquotedArg)}", {+ note: fakeNote()+ })+ ).toThrow(/is not a supported expression/);+ });+});diff --git a/packages/commons/src/lib/safe_template.ts b/packages/commons/src/lib/safe_template.tsnew file mode 100644index 0000000000..e6172ef524--- /dev/null+++ b/packages/commons/src/lib/safe_template.ts@@ -0,0 +1,166 @@+/**+ * Safe template evaluator that replaces eval()-based template string interpolation.+ *+ * Supports only a controlled set of operations within ${...} expressions:+ * - Property access chains: `obj.prop.subprop`+ * - Method calls with a single string literal argument: `obj.method('arg')`+ * - Chained combinations: `obj.prop.method('arg')`+ *+ * This prevents arbitrary code execution while supporting the documented+ * titleTemplate, bulk rename and calendar event title use cases:+ * - ${now.format('YYYY-MM-DD')}+ * - ${parentNote.title}+ * - ${parentNote.getLabelValue('authorName')}+ * - ${note.title}+ * - ${note.dateCreatedObj.format('MM-DD')}+ * - ${title} (${age})+ */++/** Allowed method names that can be called on template variables. */+const ALLOWED_METHODS = new Set([+ "format",+ "getLabelValue",+ "getLabel",+ "getLabelValues",+ "getRelationValue",+ "getAttributeValue"+]);++/** Allowed property names that can be accessed on template variables. */+const ALLOWED_PROPERTIES = new Set([+ "title",+ "type",+ "mime",+ "noteId",+ "dateCreated",+ "dateModified",+ "utcDateCreated",+ "utcDateModified",+ "dateCreatedObj",+ "utcDateCreatedObj",+ "isProtected",+ "content"+]);++export interface TemplateVariables {+ [key: string]: unknown;+}++/**+ * Evaluates a template string safely without using eval().+ *+ * Template strings can contain ${...} expressions which are evaluated+ * against the provided variables map.+ *+ * @param template - The template string, e.g. "Note: ${now.format('YYYY-MM-DD')}"+ * @param variables - Map of variable names to their values+ * @returns The interpolated string+ * @throws Error if an expression cannot be safely evaluated+ */+export function evaluateTemplate(template: string, variables: TemplateVariables): string {+ return template.replace(/\$\{([^}]+)\}/g, (_match, expression: string) => {+ const result = evaluateExpression(expression.trim(), variables);+ return result == null ? "" : String(result);+ });+}++/**+ * Evaluates a single expression like "now.format('YYYY-MM-DD')" or "parentNote.title".+ *+ * Supported forms:+ * - `varName` -> variables[varName]+ * - `varName.prop` -> variables[varName].prop+ * - `varName.prop1.prop2` -> variables[varName].prop1.prop2+ * - `varName.method('arg')` -> variables[varName].method('arg')+ * - `varName.prop.method('arg')` -> variables[varName].prop.method('arg')+ */+function evaluateExpression(expr: string, variables: TemplateVariables): unknown {+ // First, check for a method call at the end: .methodName('arg') or .methodName("arg")+ const methodCallMatch = expr.match(+ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")\s*\)$/+ );++ if (methodCallMatch) {+ const [, chainStr, methodName, singleQuoteArg, doubleQuoteArg] = methodCallMatch;+ const methodArg = singleQuoteArg !== undefined ? singleQuoteArg : doubleQuoteArg;++ if (!ALLOWED_METHODS.has(methodName)) {+ throw new Error(`Method '${methodName}' is not allowed in template expressions`);+ }++ const target = resolvePropertyChain(chainStr, variables);+ if (target == null) {+ return null;+ }++ const method = (target as Record<string, unknown>)[methodName];+ if (typeof method !== "function") {+ throw new Error(`'${methodName}' is not a function on the resolved object`);+ }++ return (method as (arg: string) => unknown).call(target, methodArg as string);+ }++ // Check for a no-arg method call at the end: .methodName()+ const noArgMethodMatch = expr.match(+ /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*\)$/+ );++ if (noArgMethodMatch) {+ const [, chainStr, methodName] = noArgMethodMatch;++ if (!ALLOWED_METHODS.has(methodName)) {+ throw new Error(`Method '${methodName}' is not allowed in template expressions`);+ }++ const target = resolvePropertyChain(chainStr, variables);+ if (target == null) {+ return null;+ }++ const method = (target as Record<string, unknown>)[methodName];+ if (typeof method !== "function") {+ throw new Error(`'${methodName}' is not a function on the resolved object`);+ }++ return (method as () => unknown).call(target);+ }++ // Otherwise it's a pure property chain: varName.prop1.prop2...+ const propChainMatch = expr.match(/^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/);+ if (!propChainMatch) {+ throw new Error(`Template expression '${expr}' is not a supported expression. ` ++ `Only property access and whitelisted method calls are allowed.`);+ }++ return resolvePropertyChain(expr, variables);+}++/**+ * Resolves a dot-separated property chain like "parentNote.title" against variables.+ */+function resolvePropertyChain(chain: string, variables: TemplateVariables): unknown {+ const parts = chain.split(".");+ const rootName = parts[0];++ if (!(rootName in variables)) {+ throw new Error(`Unknown variable '${rootName}' in template expression`);+ }++ let current: unknown = variables[rootName];++ for (let i = 1; i < parts.length; i++) {+ if (current == null) {+ return null;+ }++ const prop = parts[i];+ if (!ALLOWED_PROPERTIES.has(prop)) {+ throw new Error(`Property '${prop}' is not allowed in template expressions`);+ }++ current = (current as Record<string, unknown>)[prop];+ }++ return current;+}diff --git a/packages/trilium-core/src/services/bulk_actions.ts b/packages/trilium-core/src/services/bulk_actions.tsindex 01205fc3a6..eae88602eb 100644--- a/packages/trilium-core/src/services/bulk_actions.ts+++ b/packages/trilium-core/src/services/bulk_actions.ts@@ -1,4 +1,4 @@-import { ActionHandlers, BulkAction, BulkActionData } from "@triliumnext/commons";+import { ActionHandlers, BulkAction, BulkActionData, evaluateTemplate } from "@triliumnext/commons";import branchService from "./branches";import eraseService from "./erase.js";@@ -7,7 +7,6 @@ import type BNote from "../becca/entities/bnote.js";import cloningService from "./cloning.js";import { getLog } from "./log";import noteFormatConversionService from "./note_format_conversion.js";-import { evaluateTemplate } from "./safe_template.js";import { executeBundle } from "./script.js";import { assertScriptingEnabled } from "./scripting_guard.js";import { randomString } from "./utils/index.js";diff --git a/packages/trilium-core/src/services/safe_template.spec.ts b/packages/trilium-core/src/services/safe_template.spec.tsindex 6d65a8787c..36c1db2f8a 100644--- a/packages/trilium-core/src/services/safe_template.spec.ts+++ b/packages/trilium-core/src/services/safe_template.spec.ts@@ -1,188 +1,11 @@import { describe, expect, it, vi } from "vitest";-import { getLog } from "./log.js";-import { evaluateTemplate, evaluateTemplateSafe } from "./safe_template.js";--/**- * A stand-in for the note-like objects passed into template evaluation. Only the- * whitelisted properties/methods are exercised; method calls record their args so- * we can assert the single string literal is forwarded verbatim.- */-function fakeNote(overrides: Record<string, unknown> = {}) {- return {- title: "My Note",- type: "text",- noteId: "abc123",- getLabelValue: (name: string) => `label:${name}`,- getRelationValue: (name: string) => `relation:${name}`,- format: (fmt: string) => `formatted(${fmt})`,- ...overrides- };-}--describe("safe_template - evaluateTemplate", () => {- it("returns literal text unchanged when there are no expressions", () => {- expect(evaluateTemplate("just text", {})).toBe("just text");- });-- it("resolves a bare variable reference", () => {- expect(evaluateTemplate("${note}", { note: "value" })).toBe("value");- });-- it("resolves a single-level property access", () => {- expect(evaluateTemplate("${note.title}", { note: fakeNote() })).toBe(- "My Note"- );- });-- it("resolves a multi-level property chain (both segments whitelisted)", () => {- // `content` and `title` are both whitelisted, so a two-hop chain resolves.- const note = fakeNote({ content: { title: "inner" } });- expect(evaluateTemplate("${note.content.title}", { note })).toBe(- "inner"- );- });-- it("interpolates multiple expressions mixed with literal text", () => {- const note = fakeNote();- expect(evaluateTemplate("[${note.type}] ${note.title}", { note })).toBe(- "[text] My Note"- );- });-- it("calls a whitelisted method with a single-quoted string argument", () => {- const note = fakeNote();- expect(- evaluateTemplate("${note.getLabelValue('authorName')}", { note })- ).toBe("label:authorName");- });-- it("calls a whitelisted method with a double-quoted string argument", () => {- const note = fakeNote();- expect(evaluateTemplate('${note.format("YYYY-MM-DD")}', { note })).toBe(- "formatted(YYYY-MM-DD)"- );- });-- it("calls a whitelisted method through a property chain", () => {- const note = fakeNote({- dateCreatedObj: { format: (f: string) => `date(${f})` }- });- expect(- evaluateTemplate("${note.dateCreatedObj.format('MM-DD')}", {- note- })- ).toBe("date(MM-DD)");- });- it("calls a whitelisted no-arg method", () => {- const note = fakeNote({ getLabelValue: () => "no-arg-value" });- expect(evaluateTemplate("${note.getLabelValue()}", { note })).toBe(- "no-arg-value"- );- });-- it("returns empty string when a no-arg method target along the chain is null", () => {- // `dateCreatedObj` is whitelisted but null, so the chain resolves to null- // and the no-arg method call short-circuits to null (rendered empty).- const note = fakeNote({ dateCreatedObj: null });- expect(evaluateTemplate("${note.dateCreatedObj.format()}", { note })).toBe(- ""- );- });-- it("renders null/undefined results as an empty string", () => {- expect(- evaluateTemplate("[${note.title}]", {- note: fakeNote({ title: null })- })- ).toBe("[]");- expect(- evaluateTemplate("[${note.title}]", {- note: fakeNote({ title: undefined })- })- ).toBe("[]");- });-- it("returns empty string when a method target along the chain is null", () => {- // resolvePropertyChain yields null because the root variable itself is null.- expect(- evaluateTemplate("${note.getLabelValue('x')}", { note: null })- ).toBe("");- });-- it("returns null (rendered empty) when a property on a null intermediate is accessed", () => {- expect(evaluateTemplate("[${note.title}]", { note: null })).toBe("[]");- });-- it("treats an empty string argument as a valid method argument", () => {- const note = fakeNote({ getLabelValue: (name: string) => `[${name}]` });- expect(evaluateTemplate("${note.getLabelValue('')}", { note })).toBe(- "[]"- );- });-});--describe("safe_template - rejected expressions", () => {- it("throws for an unknown root variable", () => {- expect(() => evaluateTemplate("${missing.title}", {})).toThrow(- /Unknown variable 'missing'/- );- });-- it("throws for a non-whitelisted property", () => {- const note = fakeNote({ constructor: "evil" });- expect(() => evaluateTemplate("${note.constructor}", { note })).toThrow(- /Property 'constructor' is not allowed/- );- });-- it("throws for a non-whitelisted method", () => {- const note = fakeNote({ toString: () => "boom" });- expect(() => evaluateTemplate("${note.toString()}", { note })).toThrow(- /Method 'toString' is not allowed/- );- });-- it("throws for a non-whitelisted method with an argument", () => {- const note = fakeNote({ eval: (s: string) => s });- expect(() => evaluateTemplate("${note.eval('1+1')}", { note })).toThrow(- /Method 'eval' is not allowed/- );- });-- it("throws when a whitelisted method name resolves to a non-function", () => {- // `format` is whitelisted but here it is a plain string, not callable.- const note = fakeNote({ format: "not a function" });- expect(() => evaluateTemplate("${note.format('x')}", { note })).toThrow(- /'format' is not a function/- );- });-- it("throws when a whitelisted no-arg method name resolves to a non-function", () => {- const note = fakeNote({ getLabelValue: 42 });- expect(() =>- evaluateTemplate("${note.getLabelValue()}", { note })- ).toThrow(/'getLabelValue' is not a function/);- });-- it("throws for syntactically unsupported expressions", () => {- expect(() => evaluateTemplate("${1 + 1}", {})).toThrow(- /is not a supported expression/- );- expect(() =>- evaluateTemplate("${note['title']}", { note: fakeNote() })- ).toThrow(/is not a supported expression/);- expect(() =>- evaluateTemplate("${note.method(unquotedArg)}", {- note: fakeNote()- })- ).toThrow(/is not a supported expression/);- });-});+import { getLog } from "./log.js";+import { evaluateTemplateSafe } from "./safe_template.js";describe("safe_template - evaluateTemplateSafe", () => {it("returns the interpolated value on success", () => {- const note = fakeNote();+ const note = { title: "My Note" };expect(evaluateTemplateSafe("${note.title}", { note }, "fallback", "test")).toBe("My Note");diff --git a/packages/trilium-core/src/services/safe_template.ts b/packages/trilium-core/src/services/safe_template.tsindex d22091b737..214c82914e 100644--- a/packages/trilium-core/src/services/safe_template.ts+++ b/packages/trilium-core/src/services/safe_template.ts@@ -1,171 +1,7 @@-/**- * Safe template evaluator that replaces eval()-based template string interpolation.- *- * Supports only a controlled set of operations within ${...} expressions:- * - Property access chains: `obj.prop.subprop`- * - Method calls with a single string literal argument: `obj.method('arg')`- * - Chained combinations: `obj.prop.method('arg')`- *- * This prevents arbitrary code execution while supporting the documented- * titleTemplate and bulk rename use cases:- * - ${now.format('YYYY-MM-DD')}- * - ${parentNote.title}- * - ${parentNote.getLabelValue('authorName')}- * - ${note.title}- * - ${note.dateCreatedObj.format('MM-DD')}- */+import { evaluateTemplate, type TemplateVariables } from "@triliumnext/commons";import { getLog } from "./log.js";-/** Allowed method names that can be called on template variables. */-const ALLOWED_METHODS = new Set([- "format",- "getLabelValue",- "getLabel",- "getLabelValues",- "getRelationValue",- "getAttributeValue"-]);--/** Allowed property names that can be accessed on template variables. */-const ALLOWED_PROPERTIES = new Set([- "title",- "type",- "mime",- "noteId",- "dateCreated",- "dateModified",- "utcDateCreated",- "utcDateModified",- "dateCreatedObj",- "utcDateCreatedObj",- "isProtected",- "content"-]);--interface TemplateVariables {- [key: string]: unknown;-}--/**- * Evaluates a template string safely without using eval().- *- * Template strings can contain ${...} expressions which are evaluated- * against the provided variables map.- *- * @param template - The template string, e.g. "Note: ${now.format('YYYY-MM-DD')}"- * @param variables - Map of variable names to their values- * @returns The interpolated string- * @throws Error if an expression cannot be safely evaluated- */-export function evaluateTemplate(template: string, variables: TemplateVariables): string {- return template.replace(/\$\{([^}]+)\}/g, (_match, expression: string) => {- const result = evaluateExpression(expression.trim(), variables);- return result == null ? "" : String(result);- });-}--/**- * Evaluates a single expression like "now.format('YYYY-MM-DD')" or "parentNote.title".- *- * Supported forms:- * - `varName` -> variables[varName]- * - `varName.prop` -> variables[varName].prop- * - `varName.prop1.prop2` -> variables[varName].prop1.prop2- * - `varName.method('arg')` -> variables[varName].method('arg')- * - `varName.prop.method('arg')` -> variables[varName].prop.method('arg')- */-function evaluateExpression(expr: string, variables: TemplateVariables): unknown {- // First, check for a method call at the end: .methodName('arg') or .methodName("arg")- const methodCallMatch = expr.match(- /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*(?:'([^']*)'|"([^"]*)")\s*\)$/- );-- if (methodCallMatch) {- const [, chainStr, methodName, singleQuoteArg, doubleQuoteArg] = methodCallMatch;- const methodArg = singleQuoteArg !== undefined ? singleQuoteArg : doubleQuoteArg;-- if (!ALLOWED_METHODS.has(methodName)) {- throw new Error(`Method '${methodName}' is not allowed in template expressions`);- }-- const target = resolvePropertyChain(chainStr, variables);- if (target == null) {- return null;- }-- const method = (target as Record<string, unknown>)[methodName];- if (typeof method !== "function") {- throw new Error(`'${methodName}' is not a function on the resolved object`);- }-- return (method as (arg: string) => unknown).call(target, methodArg as string);- }-- // Check for a no-arg method call at the end: .methodName()- const noArgMethodMatch = expr.match(- /^([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)\.([a-zA-Z_]\w*)\(\s*\)$/- );-- if (noArgMethodMatch) {- const [, chainStr, methodName] = noArgMethodMatch;-- if (!ALLOWED_METHODS.has(methodName)) {- throw new Error(`Method '${methodName}' is not allowed in template expressions`);- }-- const target = resolvePropertyChain(chainStr, variables);- if (target == null) {- return null;- }-- const method = (target as Record<string, unknown>)[methodName];- if (typeof method !== "function") {- throw new Error(`'${methodName}' is not a function on the resolved object`);- }-- return (method as () => unknown).call(target);- }-- // Otherwise it's a pure property chain: varName.prop1.prop2...- const propChainMatch = expr.match(/^[a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*$/);- if (!propChainMatch) {- throw new Error(`Template expression '${expr}' is not a supported expression. ` +- `Only property access and whitelisted method calls are allowed.`);- }-- return resolvePropertyChain(expr, variables);-}--/**- * Resolves a dot-separated property chain like "parentNote.title" against variables.- */-function resolvePropertyChain(chain: string, variables: TemplateVariables): unknown {- const parts = chain.split(".");- const rootName = parts[0];-- if (!(rootName in variables)) {- throw new Error(`Unknown variable '${rootName}' in template expression`);- }-- let current: unknown = variables[rootName];-- for (let i = 1; i < parts.length; i++) {- if (current == null) {- return null;- }-- const prop = parts[i];- if (!ALLOWED_PROPERTIES.has(prop)) {- throw new Error(`Property '${prop}' is not allowed in template expressions`);- }-- current = (current as Record<string, unknown>)[prop];- }-- return current;-}-/*** Convenience wrapper that evaluates a template and catches errors,* logging them and returning the fallback value.