Builds the markers, data block and stand-in host for the CMS host injection

The pages carry the CMS markers (data block, list regions, JSON-LD price,
inline price); PackagesProvider reads the host's data block after hydration
and asks the API only when there is none; the site address comes from the
block. A stand-in for the host (config/hostInjector.ts, --cms-data in the
preview server) and browser tests check the behaviour with different data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:21:08 +01:00
co-authored by Claude Sonnet 5.5
parent 16027f5688
commit bf21b6f690
26 changed files with 1207 additions and 70 deletions
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from 'vitest';
import { injectCms, type LiveData } from './hostInjector.ts';
const AUTHORED = 'https://andreaslop.nl';
const page = (inner: string) => `<html><body>${inner}</body></html>`;
const pakket = (slug: string, price: string, extra = {}) => ({
slug,
title: slug.toUpperCase(),
price,
features: ['a'],
displayOrder: 0,
...extra,
});
const live = (
offerings: unknown,
banners: LiveData['banners'] = { top: null, bottom: null },
): LiveData => ({ offerings, banners });
const run = (html: string, data: LiveData, publicBaseUrl?: string) =>
injectCms(html, { data, authoredBaseUrl: AUTHORED, publicBaseUrl });
describe('injectCms regions', () => {
const region = (name: string) =>
`<!--CMS:${name}-->baked<!--/CMS:${name}-->`;
it('writes the lists between the markers and keeps the markers', () => {
const out = run(
page(
region('OFFERINGS-HTML') +
region('BANNER-TOP-HTML') +
region('BANNER-BOTTOM-HTML'),
),
live([pakket('newborn', '€ 185')], {
top: { text: 'Boven' },
bottom: { title: 'Onder' },
}),
);
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><ul class="cms-offerings">',
);
expect(out).toContain('€&nbsp;185');
expect(out).toContain('<!--CMS:BANNER-TOP-HTML--><aside');
expect(out).toContain('<span>Boven</span>');
expect(out).toContain('<strong>Onder</strong>');
expect(out).toContain('<!--/CMS:BANNER-BOTTOM-HTML-->');
expect(out).not.toContain('baked');
});
it('empties a region without data', () => {
const out = run(page(region('OFFERINGS-HTML')), live([]));
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->',
);
});
});
describe('injectCms data block', () => {
const baked =
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"source":"build"}</script>';
it('replaces the marker and the baked block by the live one, with the address', () => {
const out = run(
page(baked),
live([pakket('x', '€ 5')]),
'https://t.nl',
);
expect(out).not.toContain('"source"');
const json = /id="cms-data">(.*?)<\/script>/.exec(out)?.[1] ?? '';
expect(JSON.parse(json)).toMatchObject({
siteUrl: 'https://t.nl',
offerings: [{ slug: 'x' }],
banners: { top: null, bottom: null },
});
});
it('writes the block in place of a lone marker, and escapes it', () => {
const out = run(
page('<!--CMS:DATA-->'),
live([pakket('x', '€ 5', { title: '</script><b>' })]),
);
expect(out).toContain('<script type="application/json" id="cms-data">');
expect(out.match(/<\/script>/g)).toHaveLength(1);
expect(out).toContain('\\u003c/script\\u003e');
});
});
describe('injectCms JSON-LD and prices', () => {
const ld = (offers: unknown) =>
`<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">${JSON.stringify(
{ '@graph': [{ '@type': 'Service', offers }] },
)}</script>`;
it('sets the price of the package', () => {
const out = run(
page(ld({ '@type': 'Offer', price: 1, priceCurrency: 'EUR' })),
live([pakket('newborn', '€ 1.250')]),
);
expect(out).toContain('"price":1250');
expect(out).toContain('"priceCurrency":"EUR"');
expect(out).not.toContain('CMS:OFFER-JSON-LD');
});
it('removes offers when the package is gone or has no readable price', () => {
for (const offerings of [
[pakket('gezin', '€ 1')],
[pakket('newborn', 'op aanvraag')],
]) {
const out = run(page(ld({ price: 1 })), live(offerings));
expect(out).not.toContain('offers');
}
});
it('leaves a block that is not JSON as it is', () => {
const broken =
'<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">{kapot</script>';
expect(run(page(broken), live([]))).toContain(broken);
});
it('sets the text of an inline price and leaves unknown slugs alone', () => {
const out = run(
page(
'<span data-cms-price="newborn" x>€ 1</span><span data-cms-price="onbekend">€ 9</span>',
),
live([pakket('newborn', '€ 185')]),
);
expect(out).toContain(
'<span data-cms-price="newborn" x>€ 185</span>'.replace(
'€ ',
'€' + String.fromCharCode(160),
),
);
expect(out).toContain('<span data-cms-price="onbekend">€ 9</span>');
});
});
describe('injectCms address', () => {
it('replaces the written address everywhere when another one is set', () => {
const html = page(`<link href="${AUTHORED}/a"><i>${AUTHORED}/b</i>`);
const out = run(html, live([]), 'https://t.nl');
expect(out).not.toContain(AUTHORED);
expect(out.match(/https:\/\/t\.nl/g)).toHaveLength(2);
});
it('leaves it when none is set or it is the same', () => {
const html = page(`<i>${AUTHORED}/b</i>`);
expect(run(html, live([]))).toBe(html);
expect(run(html, live([]), AUTHORED)).toBe(html);
});
});
+116
View File
@@ -0,0 +1,116 @@
// A stand-in for what the CMS host does to a prerendered page: it fills the CMS
// markers from live data (the contract is in aidlc-docs/features/
// asf-cms-host-injection/plan.md and contract/host-injection). The real
// injector is C# in the CMS repo; this one lets the preview server and the
// browser tests show how the site behaves when a host rewrites the HTML, so
// hydration, fail-safe behaviour and layout can be checked without a host.
// It uses the site's own mapping and HTML code, so it proves the page copes
// with what the host writes; the golden files prove the host's template
// matches that code.
import { bannerHtml, offeringsHtml } from '../src/lib/cmsHtml.ts';
import { scriptJson } from '../src/lib/cmsData.ts';
import { formatPrice } from '../src/lib/formatPrice.ts';
import { mapBanner, mapOfferings, mapTopBanner } from '../src/lib/offerings.ts';
export interface LiveData {
// The answers as the public API gives them
offerings: unknown;
banners: { top: unknown; bottom: unknown };
}
export interface InjectOptions {
data: LiveData;
// The address the build was written with and the one to show instead
authoredBaseUrl?: string;
publicBaseUrl?: string;
}
// ld+json that cannot close its script element (same rule as the site's)
const jsonLd = (value: unknown) =>
JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
const REGION =
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->[\s\S]*?<!--\/CMS:\1-->/g;
const DATA_BLOCK =
/<!--CMS:DATA-->(?:<script type="application\/json" id="cms-data">[\s\S]*?<\/script>)?/g;
const OFFER_JSON_LD =
/<!--CMS:OFFER-JSON-LD slug="([a-z0-9-]+)"--><script type="application\/ld\+json">([\s\S]*?)<\/script>/g;
const PRICE_SPAN =
/(<span data-cms-price="([a-z0-9-]+)"[^>]*>)[^<]*(<\/span>)/g;
type Price = Map<string, number>;
// Sets or removes offers on every node of a JSON-LD value that has them
function editOffers(value: unknown, price: number | undefined): void {
if (Array.isArray(value)) {
for (const item of value) editOffers(item, price);
return;
}
if (typeof value !== 'object' || value === null) return;
const node = value as Record<string, unknown>;
if ('offers' in node) {
if (price === undefined) delete node.offers;
else {
node.offers = { ...(node.offers as object), price };
}
}
for (const child of Object.values(node)) editOffers(child, price);
}
export function injectCms(html: string, options: InjectOptions): string {
const { data } = options;
const mapped = mapOfferings(data.offerings);
const packages = mapped ? mapped.packages : [];
const prices: Price = new Map(packages.map((pkg) => [pkg.id, pkg.price]));
const regions: Record<string, string> = {
'OFFERINGS-HTML': offeringsHtml(packages),
'BANNER-TOP-HTML': bannerHtml(mapTopBanner(data.banners.top)),
'BANNER-BOTTOM-HTML': bannerHtml(mapBanner(data.banners.bottom)),
};
const siteUrl = options.publicBaseUrl ?? options.authoredBaseUrl;
let out = html
.replace(
REGION,
(_match, name: string) =>
`<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
)
.replace(
DATA_BLOCK,
() =>
'<!--CMS:DATA-->' +
`<script type="application/json" id="cms-data">${scriptJson({
...(siteUrl ? { siteUrl } : {}),
offerings: data.offerings,
banners: data.banners,
})}</script>`,
)
.replace(OFFER_JSON_LD, (match, slug: string, json: string) => {
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
return match;
}
editOffers(parsed, prices.get(slug));
return `<script type="application/ld+json">${jsonLd(parsed)}</script>`;
})
.replace(
PRICE_SPAN,
(match, open: string, slug: string, close: string) => {
const price = prices.get(slug);
return price === undefined
? match
: `${open}${formatPrice(price)}${close}`;
},
);
const { authoredBaseUrl, publicBaseUrl } = options;
if (authoredBaseUrl && publicBaseUrl && authoredBaseUrl !== publicBaseUrl) {
out = out.split(authoredBaseUrl).join(publicBaseUrl);
}
return out;
}
+42 -2
View File
@@ -8,7 +8,7 @@
// slash aan het eind krijgen één 301 (BR-HST-03, 04). /404.html is een echte
// 404; Lighthouse auditeert de 404-pagina via de opt-in route /__audit/404
// (--audit-route, BR-HST-22).
import { createReadStream, statSync } from 'node:fs';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import {
createServer,
type IncomingMessage,
@@ -18,6 +18,7 @@ import {
import { extname, join, resolve, sep, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createGzip } from 'node:zlib';
import { injectCms, type InjectOptions } from './hostInjector.ts';
import { canonicalRedirect, stripTrailingSlashes } from './canonicalUrls.ts';
import {
compressibleExtensions,
@@ -197,6 +198,10 @@ export interface PreviewOptions {
// 202. Productie gebruikt dit nooit; tests kunnen het per pagina met
// page.route vervangen (bijvoorbeeld 404 of een captcha).
contactStub?: boolean;
// Opt-in stand-in for the CMS host's injection (--cms-data=<json file>):
// called for every HTML page; the answer is what the host would write into
// the markers (see hostInjector.ts), null serves the page as built.
inject?: () => InjectOptions | null;
}
const CONTACT_API = '/api/v1/contact-messages';
@@ -307,6 +312,21 @@ export function startPreviewServer(
);
return;
}
const injection = file.endsWith('.html') ? options.inject?.() : null;
if (injection) {
const body = injectCms(readFileSync(target, 'utf8'), injection);
send(
response,
status,
{
'Content-Type': contentTypeOf(file),
'Cache-Control': 'no-cache',
'Content-Length': Buffer.byteLength(body),
},
request.method === 'HEAD' ? null : body,
);
return;
}
const headers: Record<string, string | number> = {
'Content-Type': contentTypeOf(file),
};
@@ -346,6 +366,7 @@ function parseArguments(args: string[]) {
dir: 'dist/client',
auditRoute: false,
contactStub: false,
cmsData: '',
};
for (let i = 0; i < args.length; i++) {
const [name, inline] = args[i].split('=', 2);
@@ -355,6 +376,7 @@ function parseArguments(args: string[]) {
else if (name === '--strictPort') options.strictPort = true;
else if (name === '--audit-route') options.auditRoute = true;
else if (name === '--contact-stub') options.contactStub = true;
else if (name === '--cms-data') options.cmsData = value();
}
return options;
}
@@ -362,7 +384,7 @@ function parseArguments(args: string[]) {
const MAX_PORT_TRIES = 10;
async function main(args: string[]) {
const { port, strictPort, dir, auditRoute, contactStub } =
const { port, strictPort, dir, auditRoute, contactStub, cmsData } =
parseArguments(args);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
console.error(`Ongeldige poort: ${port}`);
@@ -377,6 +399,24 @@ async function main(args: string[]) {
const server = await startPreviewServer(dir, port + attempt, {
auditRoute,
contactStub,
// Read again for every page, so the file can change while the
// server runs: { offerings, banners, publicBaseUrl? }
...(cmsData
? {
inject: () => {
const file = JSON.parse(
readFileSync(cmsData, 'utf8'),
) as InjectOptions['data'] & {
publicBaseUrl?: string;
};
return {
data: file,
authoredBaseUrl: 'https://andreaslop.nl',
publicBaseUrl: file.publicBaseUrl,
};
},
}
: {}),
});
const address = server.address();
const actual =