Adds the neutral HTML, the data block helpers and the golden files of the host injection

cmsHtml.ts writes the plain list and banner HTML that sits between the CMS
markers; contract/host-injection holds the inputs, the expected HTML and the
rules the CMS host's C# template must follow. cmsData.ts reads, validates and
writes the cms-data block.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:05:42 +01:00
co-authored by Claude Sonnet 5.5
parent ed4a19d146
commit 16027f5688
28 changed files with 615 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
import { describe, expect, it } from 'vitest';
import {
bakedCmsData,
parseCmsData,
rawBanner,
rawOfferings,
readCmsData,
scriptJson,
} from './cmsData';
import { mapBanner, mapOfferings, mapTopBanner } from './offerings';
import { PRODUCTION_SITE_URL } from './siteUrl';
const packages = [
{
id: 'newborn',
name: 'Newborn',
price: 185,
features: ['a', 'b'],
featured: true,
description: 'd',
priceNote: 'n',
ctaLabel: 'c',
},
{ id: 'gezin', name: 'Gezin', price: 1250, features: ['x'] },
];
describe('parseCmsData', () => {
it('reads the three parts and checks the address', () => {
const data = parseCmsData(
JSON.stringify({
siteUrl: 'https://test.andreaslop.nl/',
offerings: [{ slug: 'x' }],
banners: { top: null, bottom: { title: 'T' } },
}),
);
expect(data).toEqual({
siteUrl: 'https://test.andreaslop.nl',
offerings: [{ slug: 'x' }],
banners: { top: null, bottom: { title: 'T' } },
});
});
it('falls back to production for an address that is not an origin', () => {
expect(
parseCmsData(JSON.stringify({ siteUrl: 'ftp://x' }))?.siteUrl,
).toBe(PRODUCTION_SITE_URL);
});
it('leaves out what is missing or of the wrong kind', () => {
expect(
parseCmsData(JSON.stringify({ offerings: 'x', siteUrl: '' })),
).toEqual({
siteUrl: undefined,
offerings: undefined,
banners: undefined,
});
});
it.each([null, undefined, '', 'niet json', '[1]', '"x"', 'null'])(
'gives null for %s',
(text) => expect(parseCmsData(text)).toBeNull(),
);
});
describe('readCmsData', () => {
it('reads the block of the page', () => {
const doc = {
getElementById: (id: string) =>
id === 'cms-data' ? { textContent: '{"offerings":[]}' } : null,
} as unknown as Document;
expect(readCmsData(doc)?.offerings).toEqual([]);
});
it('gives null without a block', () => {
const doc = { getElementById: () => null } as unknown as Document;
expect(readCmsData(doc)).toBeNull();
});
});
describe('scriptJson', () => {
it('cannot end the script element or contain a line separator', () => {
const text = scriptJson({
a: '</script><!-- & \u2028 \u2029',
});
expect(text).not.toMatch(/[<>&\u2028\u2029]/);
expect(JSON.parse(text)).toEqual({
a: '</script><!-- & \u2028 \u2029',
});
});
});
describe('the baked block', () => {
it('maps back to the same packages and banners', () => {
const data = bakedCmsData(
'https://andreaslop.nl',
packages,
{ title: 'Onder', text: 't', link: { label: 'L', url: '/x' } },
{ text: 'Boven' },
);
expect(data.siteUrl).toBe('https://andreaslop.nl');
const mapped = mapOfferings(data.offerings);
expect(mapped?.packages).toEqual(
packages.map((pkg) => ({
priceNote: undefined,
description: undefined,
ctaLabel: undefined,
featured: undefined,
...pkg,
})),
);
expect(mapBanner(data.banners?.bottom)).toEqual({
title: 'Onder',
text: 't',
link: { label: 'L', url: '/x' },
});
expect(mapTopBanner(data.banners?.top)).toMatchObject({
text: 'Boven',
});
});
it('gives null for no banner and keeps the order', () => {
expect(rawBanner(null, 'top')).toBeNull();
expect(rawBanner({ title: 'Alleen' }, 'bottom')).toEqual({
title: 'Alleen',
text: null,
linkLabel: null,
linkUrl: null,
position: 'bottom',
});
expect(
rawOfferings(packages).map((raw) => (raw as { slug: string }).slug),
).toEqual(['newborn', 'gezin']);
});
});
+113
View File
@@ -0,0 +1,113 @@
import type { PricingBanner, PricingPackage } from '@/content/types';
import { formatPrice } from './formatPrice';
import type { OfferingTopBanner } from './offerings';
import { resolveSiteUrl } from './siteUrl';
// The data island of a page: what the CMS host writes into
// <script type="application/json" id="cms-data"> after the <!--CMS:DATA-->
// marker, exactly in the shape of the public API:
// { "siteUrl": "...", "offerings": [...], "banners": { "top": ..., "bottom": ... } }
// The build writes the same block with the data it baked, so the page always
// has one. Everything here is lenient: a block that cannot be used is ignored
// and the page keeps what it was built with.
export interface CmsData {
// Already checked by resolveSiteUrl
siteUrl?: string;
offerings?: unknown;
// undefined: not in the block; null: no active banner
banners?: { top?: unknown; bottom?: unknown };
}
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
export function parseCmsData(text: string | null | undefined): CmsData | null {
if (!text) return null;
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
return null;
}
if (!isObject(raw)) return null;
const banners = isObject(raw.banners)
? { top: raw.banners.top, bottom: raw.banners.bottom }
: undefined;
return {
siteUrl:
typeof raw.siteUrl === 'string' && raw.siteUrl !== ''
? resolveSiteUrl(raw.siteUrl)
: undefined,
offerings: Array.isArray(raw.offerings) ? raw.offerings : undefined,
banners,
};
}
export const CMS_DATA_ID = 'cms-data';
// The block of the page, or null without a usable one (a preview, a test, a
// host that does not inject)
export function readCmsData(
doc: Pick<Document, 'getElementById'>,
): CmsData | null {
return parseCmsData(doc.getElementById(CMS_DATA_ID)?.textContent);
}
// JSON that cannot end the script element or break a line terminator rule:
// < > & and U+2028/2029 as \u escapes (the host does the same)
export function scriptJson(value: unknown): string {
return JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
}
// The mapped packages back in the shape of GET /api/v1/offerings, for the
// block the build bakes (the price as the free text the CMS has)
export function rawOfferings(packages: readonly PricingPackage[]): unknown[] {
return packages.map((pkg, index) => ({
slug: pkg.id,
title: pkg.name,
price: formatPrice(pkg.price).replace(/\u00a0/g, ' '),
features: pkg.features,
displayOrder: index,
...(pkg.featured ? { featured: true } : {}),
...(pkg.description ? { description: pkg.description } : {}),
...(pkg.priceNote ? { priceNote: pkg.priceNote } : {}),
...(pkg.ctaLabel ? { ctaLabel: pkg.ctaLabel } : {}),
}));
}
// A banner back in the shape of GET /api/v1/offerings/banner, or null
export function rawBanner(
banner: PricingBanner | OfferingTopBanner | null,
position: 'top' | 'bottom',
): unknown {
if (!banner) return null;
return {
title: banner.title ?? '',
text: banner.text ?? null,
linkLabel: banner.link?.label ?? null,
linkUrl: banner.link?.url ?? null,
position,
};
}
export function bakedCmsData(
siteUrl: string,
packages: readonly PricingPackage[],
banner: PricingBanner | null,
topBanner: OfferingTopBanner | null,
): CmsData {
return {
siteUrl,
offerings: rawOfferings(packages),
banners: {
top: rawBanner(topBanner, 'top'),
bottom: rawBanner(banner, 'bottom'),
},
};
}
+87
View File
@@ -0,0 +1,87 @@
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import {
bannerHtml,
escapeHtml,
offeringsHtml,
regionMarkers,
} from './cmsHtml';
import { mapBanner, mapOfferings, mapTopBanner } from './offerings';
// The contract with the CMS host: for every *.input.json in
// contract/host-injection there is an *.expected.html, and the host's C#
// template must give exactly the same text for the same input. Regenerate the
// expected files after a deliberate change with UPDATE_GOLDEN=1 and send the
// new files to the CMS session.
const DIR = join(process.cwd(), 'contract', 'host-injection');
const inputs = readdirSync(DIR).filter((name) => name.endsWith('.input.json'));
interface BannerInput {
position: 'top' | 'bottom';
answer: unknown;
}
function render(name: string, input: unknown): string {
if (name.startsWith('offerings-')) {
const mapped = mapOfferings(input);
return offeringsHtml(mapped ? mapped.packages : []);
}
const { position, answer } = input as BannerInput;
return bannerHtml(
position === 'top' ? mapTopBanner(answer) : mapBanner(answer),
);
}
describe('host injection golden files', () => {
it('has inputs for the packages and for both banners', () => {
expect(inputs.length).toBeGreaterThanOrEqual(10);
expect(inputs.some((name) => name.startsWith('offerings-'))).toBe(true);
expect(inputs.some((name) => name.startsWith('banner-'))).toBe(true);
});
it.each(inputs)('%s gives the expected HTML', (file) => {
const name = file.replace('.input.json', '');
const input: unknown = JSON.parse(
readFileSync(join(DIR, file), 'utf8'),
);
const html = render(name, input);
const expectedFile = join(DIR, `${name}.expected.html`);
if (process.env.UPDATE_GOLDEN === '1') {
writeFileSync(expectedFile, html + '\n');
}
expect(html + '\n').toBe(readFileSync(expectedFile, 'utf8'));
});
});
describe('offeringsHtml and bannerHtml', () => {
it('writes nothing for no package and no banner', () => {
expect(offeringsHtml([])).toBe('');
expect(bannerHtml(null)).toBe('');
});
it('escapes what comes from the CMS', () => {
expect(escapeHtml(`<a href="x">'&'</a>`)).toBe(
'&lt;a href=&quot;x&quot;&gt;&#39;&amp;&#39;&lt;/a&gt;',
);
const html = offeringsHtml([
{ id: 'x', name: '<b>', price: 10, features: ['"q"'] },
]);
expect(html).not.toContain('<b>');
expect(html).toContain('&lt;b&gt;');
expect(html).toContain('&quot;q&quot;');
});
it('puts a non-breaking space in the price, as an entity', () => {
const html = offeringsHtml([
{ id: 'x', name: 'X', price: 1250, features: ['a'] },
]);
expect(html).toContain('€&nbsp;1.250');
});
it('wraps a region in its markers', () => {
expect(regionMarkers('OFFERINGS-HTML', '<ul></ul>')).toBe(
'<!--CMS:OFFERINGS-HTML--><ul></ul><!--/CMS:OFFERINGS-HTML-->',
);
});
});
+70
View File
@@ -0,0 +1,70 @@
import type { PricingBanner, PricingPackage } from '@/content/types';
import type { OfferingTopBanner } from './offerings';
import { formatPrice } from './formatPrice';
// The plain, crawlable HTML that sits between the CMS markers in the
// prerendered pages. The host (SLP Modular CMS) writes the same markup from
// live data with a C# template; the golden files in contract/host-injection
// are the contract between the two, so a change here changes them too.
// Everything that comes from the CMS is escaped.
const ESCAPES: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};
export const escapeHtml = (text: string): string =>
text.replace(/[&<>"']/g, (char) => ESCAPES[char]);
// "€ 185" with a non-breaking space, written as an entity so the golden files
// stay readable
const priceHtml = (price: number): string =>
escapeHtml(formatPrice(price)).replace(/\u00a0/g, '&nbsp;');
function packageHtml(pkg: PricingPackage): string {
const features = pkg.features
.map((feature) => `<li>${escapeHtml(feature)}</li>`)
.join('');
const featured = pkg.featured ? ' data-featured="true"' : '';
return (
`<li class="cms-offering" data-slug="${escapeHtml(pkg.id)}"${featured}>` +
`<h3>${escapeHtml(pkg.name)}</h3>` +
`<p class="cms-price">${priceHtml(pkg.price)}</p>` +
`<ul class="cms-features">${features}</ul>` +
`<a href="/?pakket=${escapeHtml(pkg.id)}#contact">Boek ${escapeHtml(pkg.name)}</a>` +
'</li>'
);
}
// The cards as a plain list; nothing at all for no package. The packages are
// the mapped ones (mapOfferings), so order and skipping rules are the same as
// the site's.
export function offeringsHtml(packages: readonly PricingPackage[]): string {
if (packages.length === 0) return '';
return `<ul class="cms-offerings">${packages.map(packageHtml).join('')}</ul>`;
}
type AnyBanner = PricingBanner | OfferingTopBanner;
// A banner as one <aside>; nothing at all for no banner. Title, text and link
// appear only when present; the link needs both parts (mapBanner already
// dropped a half or unsafe one).
export function bannerHtml(banner: AnyBanner | null): string {
if (!banner) return '';
const title = banner.title
? `<strong>${escapeHtml(banner.title)}</strong>`
: '';
const text = banner.text ? `<span>${escapeHtml(banner.text)}</span>` : '';
const link = banner.link
? `<a href="${escapeHtml(banner.link.url)}">${escapeHtml(banner.link.label)}</a>`
: '';
const parts = [title, text, link].filter((part) => part !== '');
return `<aside class="cms-banner">${parts.join(' ')}</aside>`;
}
// What sits between an opening and closing marker comment
export const regionMarkers = (name: string, inner: string): string =>
`<!--CMS:${name}-->${inner}<!--/CMS:${name}-->`;