perf(bundle): lazy-load the nunjucks template engine (#2535)

Closes #2531.

## Summary

The full `nunjucks` templating engine (~226KB) plus `ha-nunjucks`
(~46KB) — roughly **272KB, ~13% of the eager entry chunk** — was
statically imported and downloaded by every card on initial load, even
though templates only apply when a config value contains a `{{ … }}` /
`{% … %}` delimiter. Most cards use no templates and never need the
engine.

This defers the engine behind a dynamic `import('ha-nunjucks/dist')` so
it ships in a separate, on-demand chunk instead of the eager
`card-*.js`.

## Approach

The render path (`TemplateRenderer.renderRecursively`) is **kept
synchronous** — it is called from many synchronous hot paths
(condition/trigger evaluators, picture-elements rendering, actions,
folder matchers), and making it async would be a large, high-risk
refactor of the evaluation core.

Instead:

- **New `src/card-controller/templates/engine.ts`** — a module-level
singleton lazy loader (`loadTemplateEngine()` / `getTemplateEngine()`)
shared across all `TemplateRenderer` instances, plus a
`containsTemplate()` delimiter helper.
- **Delimiter gating** — strings without a delimiter never touch the
engine (the overwhelming majority of renders).
- **Pre-warm at config time** — because every template string originates
in the config, a new mandatory `TEMPLATE_ENGINE` initialization aspect
loads the engine before first render whenever the config contains a
delimiter. This **guarantees no raw `{{ … }}` flash**: content/condition
rendering is blocked until the engine is present for template-using
cards. Cards without templates never load it.

## Result

- nunjucks + ha-nunjucks move out of the eager chunk into a separate
chunk fetched only when a card actually uses templates.
- No change to the synchronous public render API; condition/trigger
evaluation core untouched.

## Tests

- New `engine.ts` loader coverage (concurrent load, cached reuse,
not-loaded fallback).
- The 11 existing test files that render real (delimiter-bearing)
templates declare their dependency explicitly via
`beforeAll(loadTemplateEngine)` — no global/implicit setup hook.
- Full suite green (4764 tests), lint and ts-prune clean, per-file 100%
coverage maintained for the affected directories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c

---
_Generated by [Claude
Code](https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c)_
This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
parent b33c034810
commit ea251ca988
59 changed files with 1420 additions and 541 deletions
+9 -8
View File
@@ -5,16 +5,17 @@ import type { ConditionState } from '../conditions/types';
// `vol.Any(boolean, template)`): a boolean, or a template rendered against the
// current state. Returns whether the trigger/condition is active.
//
// `enabledWithoutHass` is the fallback when a template `enabled` cannot be
// rendered (no hass yet, e.g. at startup). It differs by caller because
// "disabled" has opposite consequences: a disabled *trigger* simply does not
// fire (so triggers fail closed -- pass `false`), whereas a disabled
// *condition* is skipped (so the condition may evaluate to `true`)
// `fallback` is the result used when a template `enabled` cannot be rendered
// (no hass yet, or the renderer has not finished loading -- both happen at
// startup). It differs by caller because "disabled" has opposite consequences:
// a disabled *trigger* simply does not fire (so triggers fail closed -- pass
// `false`), whereas a disabled *condition* is skipped (so the condition may
// evaluate to `true`).
export const isEnabled = (
templateRenderer: TemplateRenderer,
enabled?: boolean | string,
state?: ConditionState,
enabledWithoutHass = true,
fallback = true,
): boolean => {
if (enabled === undefined) {
return true;
@@ -22,8 +23,8 @@ export const isEnabled = (
if (typeof enabled === 'boolean') {
return enabled;
}
if (!state?.hass) {
return enabledWithoutHass;
if (!state?.hass || !templateRenderer.isLoaded()) {
return fallback;
}
return (
templateRenderer.renderRecursively(state.hass, enabled, {
@@ -22,6 +22,11 @@ export const readNumericStateValue = (
let rawValue: unknown;
if (config.value_template) {
// Until the renderer has loaded the template cannot be evaluated; treat as
// non-numeric (so the match fails) rather than parsing a raw `{{…}}`.
if (!templateRenderer.isLoaded()) {
return null;
}
rawValue = templateRenderer.renderRecursively(hass, config.value_template, {
conditionState: state,
});
@@ -1,4 +1,4 @@
import { TemplateRenderer } from '../../card-controller/templates';
import type { TemplateRenderer } from '../../card-controller/templates';
import type { Condition } from '../../config/schema/condition-trigger/conditions/types';
import { isEnabled } from '../common/is-enabled';
import type {
@@ -27,7 +27,7 @@ interface ManagedCondition {
*/
export class ConditionsManager implements ConditionsManagerReadonlyInterface {
private _stateManager: ConditionStateManagerReadonlyInterface | null;
private _templateRenderer = new TemplateRenderer();
private _templateRenderer: TemplateRenderer;
private _conditions: ManagedCondition[];
private _listeners: ConditionsListener[] = [];
@@ -36,9 +36,11 @@ export class ConditionsManager implements ConditionsManagerReadonlyInterface {
constructor(
conditions: Condition[],
templateRenderer: TemplateRenderer,
stateManager?: ConditionStateManagerReadonlyInterface | null,
) {
const context = { templateRenderer: this._templateRenderer };
this._templateRenderer = templateRenderer;
const context = { templateRenderer };
this._conditions = conditions.map((config) => ({
config,
evaluator: createConditionEvaluator(config, context),
@@ -15,6 +15,9 @@ export class TemplateConditionEvaluator implements ConditionEvaluator {
return {
result:
!!newState?.hass &&
// Until the renderer has loaded the template cannot be evaluated; fail
// (rather than render a raw `{{…}}`), and re-evaluate once it loads.
this._context.templateRenderer.isLoaded() &&
isTemplateTrue(
this._context.templateRenderer.renderRecursively(
newState.hass,
+17 -4
View File
@@ -1,5 +1,5 @@
import type { HASSManagerReadonlyInterface } from '../../card-controller/hass/types';
import { TemplateRenderer } from '../../card-controller/templates';
import type { TemplateRenderer } from '../../card-controller/templates';
import type { Trigger } from '../../config/schema/condition-trigger/triggers/types';
import { isEnabled } from '../common/is-enabled';
import type { ConditionStateManagerReadonlyInterface } from '../conditions/types';
@@ -27,27 +27,40 @@ export class TriggersManager {
private _context: TriggerEvaluatorContext;
private _triggers: ManagedTrigger[];
private _listeners: TriggerCallback[] = [];
private _subscribed = false;
constructor(
triggers: Trigger[],
stateManager: ConditionStateManagerReadonlyInterface,
hassManager: HASSManagerReadonlyInterface,
templateRenderer: TemplateRenderer,
) {
this._context = {
stateManager,
templateRenderer: new TemplateRenderer(),
templateRenderer,
hassManager,
};
this._triggers = triggers.map((config) => ({
config,
evaluator: createTriggerEvaluator(config, this._context),
}));
}
/**
* Subscribe the evaluators to the state manager, establishing their
* pre-trigger baselines.
*/
public subscribe(): void {
if (this._subscribed) {
return;
}
this._subscribed = true;
// `enabled` is a live per-trigger gate (re-evaluated each time), UNLIKE
// HA's once-at-attach: a deliberate deviation to allow dynamic triggering.
this._triggers.forEach(({ config, evaluator }) =>
evaluator.subscribe((data) => {
if (
// `enabled` is a live per-trigger gate (re-evaluated each time), UNLIKE
// HA's once-at-attach: a deliberate deviation to allow dynamic triggering.
isEnabled(
this._context.templateRenderer,
config.enabled,
@@ -69,6 +69,9 @@ export class TemplateTrigger implements TriggerEvaluator {
private _render(state: ConditionState): boolean {
return (
!!state.hass &&
// Until the renderer has loaded the template cannot be evaluated; report
// not-true (matching a raw render) so no false rising edge is recorded.
this._context.templateRenderer.isLoaded() &&
isTemplateTrue(
this._context.templateRenderer.renderRecursively(
state.hass,