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:
committed by
dermotduffy
parent
b33c034810
commit
ea251ca988
@@ -8,7 +8,6 @@ import {
|
||||
it,
|
||||
vi,
|
||||
} from 'vitest';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
|
||||
import {
|
||||
ActionsManager,
|
||||
@@ -16,14 +15,20 @@ import {
|
||||
type InteractionName,
|
||||
} from '../../../src/card-controller/actions/actions-manager';
|
||||
import type { CardController } from '../../../src/card-controller/controller';
|
||||
import { TemplateRenderer } from '../../../src/card-controller/templates';
|
||||
import { TemplateManager } from '../../../src/card-controller/templates';
|
||||
import type { AdvancedCameraCardView } from '../../../src/config/schema/common/const';
|
||||
import {
|
||||
createInternalCallbackAction,
|
||||
createLogAction,
|
||||
} from '../../../src/utils/action';
|
||||
import { arrayify } from '../../../src/utils/basic';
|
||||
import { createCardAPI, createConfig, createHASS, createView } from '../../test-utils';
|
||||
import {
|
||||
createCardAPI,
|
||||
createConfig,
|
||||
createHASS,
|
||||
createMockTemplateRenderer,
|
||||
createView,
|
||||
} from '../../test-utils';
|
||||
|
||||
const createAPI = (): CardController => {
|
||||
const api = createCardAPI();
|
||||
@@ -337,10 +342,9 @@ describe('ActionsManager', () => {
|
||||
it('should render templates', async () => {
|
||||
const action = createLogAction('{{ acc.camera }}');
|
||||
|
||||
const templateRenderer = mock<TemplateRenderer>();
|
||||
templateRenderer.renderRecursivelyAsType.mockReturnValue(action);
|
||||
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(createMockTemplateRenderer());
|
||||
|
||||
const hass = createHASS();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(hass);
|
||||
|
||||
@@ -349,7 +353,7 @@ describe('ActionsManager', () => {
|
||||
};
|
||||
vi.mocked(api.getConditionStateManager().getState).mockReturnValue(conditionState);
|
||||
|
||||
const manager = new ActionsManager(api, templateRenderer);
|
||||
const manager = new ActionsManager(api);
|
||||
const config = { entity: 'light.office' };
|
||||
const triggerData = {
|
||||
platform: 'acc',
|
||||
@@ -361,10 +365,14 @@ describe('ActionsManager', () => {
|
||||
|
||||
await manager.executeActions({ actions: action, config, triggerData });
|
||||
|
||||
expect(templateRenderer.renderRecursivelyAsType).toBeCalledWith(hass, action, {
|
||||
conditionState,
|
||||
triggerData,
|
||||
});
|
||||
expect(vi.mocked(api.getTemplateManager().renderRecursivelyAsType)).toBeCalledWith(
|
||||
hass,
|
||||
action,
|
||||
{
|
||||
conditionState,
|
||||
triggerData,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('should filter actions through the lock manager before rendering them', async () => {
|
||||
@@ -377,20 +385,18 @@ describe('ActionsManager', () => {
|
||||
allowedRan();
|
||||
});
|
||||
|
||||
const templateRenderer = mock<TemplateRenderer>();
|
||||
templateRenderer.renderRecursivelyAsType.mockReturnValue(allowedAction);
|
||||
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(createMockTemplateRenderer());
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getLockManager().getAllowedActions).mockReturnValue([allowedAction]);
|
||||
|
||||
const manager = new ActionsManager(api, templateRenderer);
|
||||
const manager = new ActionsManager(api);
|
||||
|
||||
await manager.executeActions({ actions: rawAction });
|
||||
|
||||
// The lock manager sees the raw (unrendered) action; only the action it
|
||||
// returns is rendered and run.
|
||||
expect(api.getLockManager().getAllowedActions).toBeCalledWith(rawAction);
|
||||
expect(api.getLockManager().getAllowedActions).toBeCalledWith([rawAction]);
|
||||
expect(allowedRan).toBeCalled();
|
||||
expect(rawRan).not.toBeCalled();
|
||||
});
|
||||
@@ -398,17 +404,16 @@ describe('ActionsManager', () => {
|
||||
it('should render each action against the state at its turn', async () => {
|
||||
let camera = 'first';
|
||||
|
||||
const templateRenderer = mock<TemplateRenderer>();
|
||||
// Identity render -- assert on the render *inputs*, not a swapped output.
|
||||
templateRenderer.renderRecursivelyAsType.mockImplementation((_hass, data) => data);
|
||||
|
||||
const api = createAPI();
|
||||
// The mock renderer passes values through, so assert on the render
|
||||
// *inputs*, not a swapped output.
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(createMockTemplateRenderer());
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConditionStateManager().getState).mockImplementation(() => ({
|
||||
camera,
|
||||
}));
|
||||
|
||||
const manager = new ActionsManager(api, templateRenderer);
|
||||
const manager = new ActionsManager(api);
|
||||
|
||||
await manager.executeActions({
|
||||
actions: [
|
||||
@@ -423,13 +428,17 @@ describe('ActionsManager', () => {
|
||||
|
||||
// Each action renders with the state as it is at its turn: the second
|
||||
// sees the camera the first action set.
|
||||
expect(templateRenderer.renderRecursivelyAsType).toHaveBeenNthCalledWith(
|
||||
expect(
|
||||
vi.mocked(api.getTemplateManager().renderRecursivelyAsType),
|
||||
).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
expect.objectContaining({ conditionState: { camera: 'first' } }),
|
||||
);
|
||||
expect(templateRenderer.renderRecursivelyAsType).toHaveBeenNthCalledWith(
|
||||
expect(
|
||||
vi.mocked(api.getTemplateManager().renderRecursivelyAsType),
|
||||
).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
@@ -440,16 +449,14 @@ describe('ActionsManager', () => {
|
||||
it('should render against the hass available at each step', async () => {
|
||||
const ran: string[] = [];
|
||||
|
||||
const templateRenderer = mock<TemplateRenderer>();
|
||||
templateRenderer.renderRecursivelyAsType.mockImplementation((_hass, data) => data);
|
||||
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(createMockTemplateRenderer());
|
||||
// No HASS for the first action's render; HASS thereafter.
|
||||
vi.mocked(api.getHASSManager().getHASS)
|
||||
.mockReturnValueOnce(null)
|
||||
.mockReturnValue(createHASS());
|
||||
|
||||
const manager = new ActionsManager(api, templateRenderer);
|
||||
const manager = new ActionsManager(api);
|
||||
|
||||
await manager.executeActions({
|
||||
actions: [
|
||||
@@ -465,23 +472,27 @@ describe('ActionsManager', () => {
|
||||
// Both actions ran; only the second was rendered -- the first saw no
|
||||
// HASS, so HASS is read per action rather than captured once.
|
||||
expect(ran).toEqual(['one', 'two']);
|
||||
expect(templateRenderer.renderRecursivelyAsType).toBeCalledTimes(1);
|
||||
expect(
|
||||
vi.mocked(api.getTemplateManager().renderRecursivelyAsType),
|
||||
).toBeCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should abort the remaining actions when one fails to render', async () => {
|
||||
const ran: string[] = [];
|
||||
|
||||
const templateRenderer = mock<TemplateRenderer>();
|
||||
templateRenderer.renderRecursivelyAsType
|
||||
const api = createAPI();
|
||||
const renderer = createMockTemplateRenderer();
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(renderer);
|
||||
|
||||
// The second action's render throws, to exercise a mid-sequence failure.
|
||||
vi.mocked(renderer.renderRecursivelyAsType)
|
||||
.mockImplementationOnce((_hass, data) => data)
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error('bad template');
|
||||
});
|
||||
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const manager = new ActionsManager(api, templateRenderer);
|
||||
const manager = new ActionsManager(api);
|
||||
const warnSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
await manager.executeActions({
|
||||
@@ -511,7 +522,11 @@ describe('ActionsManager', () => {
|
||||
fullscreen: true,
|
||||
});
|
||||
|
||||
const manager = new ActionsManager(api, new TemplateRenderer());
|
||||
// The if-action renders its own (non-branch) fields, so give it an
|
||||
// identity renderer that passes the config through unchanged.
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(createMockTemplateRenderer());
|
||||
|
||||
const manager = new ActionsManager(api);
|
||||
const consoleSpy = vi.spyOn(global.console, 'info').mockReturnValue(undefined);
|
||||
|
||||
const thenAction = createLogAction('{{ trigger.entity_id }}');
|
||||
@@ -527,7 +542,7 @@ describe('ActionsManager', () => {
|
||||
// The branch is left raw (template intact) and forwarded with the trigger
|
||||
// data, so the nested executor renders it per-step when it runs -- not
|
||||
// frozen against the state at the `if` step.
|
||||
expect(api.getActionsManager().executeActions).toBeCalledWith({
|
||||
expect(api.getActionsManager().executeNestedActions).toBeCalledWith({
|
||||
actions: [thenAction],
|
||||
config: undefined,
|
||||
triggerData: { platform: 'state', entity_id: 'binary_sensor.door' },
|
||||
@@ -541,14 +556,20 @@ describe('ActionsManager', () => {
|
||||
it('should render if-action branch actions per-step', async () => {
|
||||
let camera = 'before';
|
||||
|
||||
// This case renders a real branch template, so load the lazily-imported
|
||||
// engine for the synchronous renderer.
|
||||
const templateManager = new TemplateManager();
|
||||
await templateManager.loadRenderer();
|
||||
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
vi.mocked(api.getConditionStateManager().getState).mockImplementation(() => ({
|
||||
camera,
|
||||
fullscreen: true,
|
||||
}));
|
||||
vi.mocked(api.getTemplateManager).mockReturnValue(templateManager);
|
||||
|
||||
const manager = new ActionsManager(api, new TemplateRenderer());
|
||||
const manager = new ActionsManager(api);
|
||||
// The if-action's nested executor is the same (real) manager.
|
||||
vi.mocked(api.getActionsManager).mockReturnValue(manager);
|
||||
|
||||
@@ -578,7 +599,7 @@ describe('ActionsManager', () => {
|
||||
const api = createAPI();
|
||||
vi.mocked(api.getHASSManager().getHASS).mockReturnValue(createHASS());
|
||||
|
||||
const manager = new ActionsManager(api, new TemplateRenderer());
|
||||
const manager = new ActionsManager(api);
|
||||
const warnSpy = vi.spyOn(global.console, 'warn').mockReturnValue(undefined);
|
||||
|
||||
await manager.executeActions({
|
||||
|
||||
@@ -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!'));
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { DownloadAction } from '../../../src/card-controller/actions/actions/dow
|
||||
import { EffectAction } from '../../../src/card-controller/actions/actions/effect';
|
||||
import { ExpandAction } from '../../../src/card-controller/actions/actions/expand';
|
||||
import { FullscreenAction } from '../../../src/card-controller/actions/actions/fullscreen';
|
||||
import { GeneratedAction } from '../../../src/card-controller/actions/actions/generated-action';
|
||||
import { IfAction } from '../../../src/card-controller/actions/actions/if';
|
||||
import { InfoAction } from '../../../src/card-controller/actions/actions/info';
|
||||
import { InternalCallbackAction } from '../../../src/card-controller/actions/actions/internal-callback';
|
||||
@@ -48,6 +49,7 @@ import { UnmuteAction } from '../../../src/card-controller/actions/actions/unmut
|
||||
import { URLAction } from '../../../src/card-controller/actions/actions/url';
|
||||
import { ViewAction } from '../../../src/card-controller/actions/actions/view';
|
||||
import { ActionFactory } from '../../../src/card-controller/actions/factory';
|
||||
import { GENERATED_ACTION } from '../../../src/config/schema/actions/custom/generated-action';
|
||||
import { INTERNAL_CALLBACK_ACTION } from '../../../src/config/schema/actions/custom/internal';
|
||||
import type { ActionConfig } from '../../../src/config/schema/actions/types';
|
||||
|
||||
@@ -203,6 +205,13 @@ describe('ActionFactory', () => {
|
||||
},
|
||||
InternalCallbackAction,
|
||||
],
|
||||
[
|
||||
{
|
||||
advanced_camera_card_action: GENERATED_ACTION,
|
||||
generator: vi.fn(),
|
||||
},
|
||||
GeneratedAction,
|
||||
],
|
||||
[{ advanced_camera_card_action: 'reload' as const }, ReloadAction],
|
||||
[{ advanced_camera_card_action: 'set_review' as const }, SetReviewAction],
|
||||
[{ advanced_camera_card_action: 'effect' as const }, EffectAction],
|
||||
|
||||
Reference in New Issue
Block a user