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
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from 'vitest';
import { GeneratedAction } from '../../../../src/card-controller/actions/actions/generated-action';
import type { TriggerData } from '../../../../src/condition-trigger/triggers/types';
import type { ActionGenerator } from '../../../../src/config/schema/actions/custom/generated-action';
import { createCameraAction, createGeneratedAction } from '../../../../src/utils/action';
import { createCardAPI } from '../../../test-utils';
describe('GeneratedAction', () => {
it('should run the generated action as a nested action set', async () => {
const api = createCardAPI();
const generated = createCameraAction('camera.office');
const action = new GeneratedAction(
{},
createGeneratedAction(() => generated),
);
await action.execute(api);
expect(api.getActionsManager().executeNestedActions).toBeCalledWith({
actions: generated,
config: undefined,
triggerData: undefined,
});
});
it('should run multiple generated actions when the generator returns several', async () => {
const api = createCardAPI();
const generated = [
createCameraAction('camera.one'),
createCameraAction('camera.two'),
];
const action = new GeneratedAction(
{},
createGeneratedAction(() => generated),
);
await action.execute(api);
expect(api.getActionsManager().executeNestedActions).toBeCalledWith({
actions: generated,
config: undefined,
triggerData: undefined,
});
});
it('should do nothing when the generator produces nothing', async () => {
const api = createCardAPI();
const action = new GeneratedAction(
{},
createGeneratedAction(() => null),
);
await action.execute(api);
expect(api.getActionsManager().executeNestedActions).not.toBeCalled();
});
it('should pass the api and trigger data to the generator', async () => {
const api = createCardAPI();
const triggerData: TriggerData = {
platform: 'state',
entity_id: 'input_select.camera',
};
const generator: ActionGenerator = vi.fn(() => null);
const action = new GeneratedAction(
{},
createGeneratedAction(generator),
undefined,
triggerData,
);
await action.execute(api);
expect(generator).toBeCalledWith({ api, triggerData });
});
});
@@ -35,7 +35,7 @@ describe('IfAction', () => {
await action.execute(api);
expect(api.getActionsManager().executeActions).toBeCalledWith({
expect(api.getActionsManager().executeNestedActions).toBeCalledWith({
actions: thenActions,
config: undefined,
triggerData: undefined,
@@ -59,7 +59,7 @@ describe('IfAction', () => {
await action.execute(api);
expect(api.getActionsManager().executeActions).toBeCalledWith({
expect(api.getActionsManager().executeNestedActions).toBeCalledWith({
actions: elseActions,
config: undefined,
triggerData: undefined,
@@ -82,6 +82,6 @@ describe('IfAction', () => {
await action.execute(api);
expect(api.getActionsManager().executeActions).not.toBeCalled();
expect(api.getActionsManager().executeNestedActions).not.toBeCalled();
});
});
@@ -2,11 +2,20 @@ import { describe, expect, it, vi } from 'vitest';
import { ActionSet } from '../../../../src/card-controller/actions/actions/set';
import { createLogAction } from '../../../../src/utils/action';
import { arrayify } from '../../../../src/utils/basic';
import { createCardAPI } from '../../../test-utils';
describe('ActionSet', () => {
it('should execute single action', async () => {
const createAPI = () => {
const api = createCardAPI();
vi.mocked(api.getLockManager().getAllowedActions).mockImplementation((actions) =>
arrayify(actions),
);
return api;
};
it('should execute single action', async () => {
const api = createAPI();
const set = new ActionSet({}, createLogAction('Hello, world!'));
@@ -16,7 +25,7 @@ describe('ActionSet', () => {
});
it('should not execute invalid action', async () => {
const api = createCardAPI();
const api = createAPI();
const set = new ActionSet(
{},
createLogAction('Hello, world!', {
@@ -30,7 +39,7 @@ describe('ActionSet', () => {
});
it('should stop execution', async () => {
const api = createCardAPI();
const api = createAPI();
const set = new ActionSet({}, createLogAction('Hello, world!'));