import type { ISeoVariable } from '../../service/seo/seo.interface'; const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** * What a title or description template renders to, with every variable * replaced by the example the server lists for it. Mirrors the PHP engine: * unknown variables disappear and separators left without a side are * dropped. */ export const previewTemplate = ( template: string, variables: ISeoVariable[], separator: string ): string => { const examples = new Map( variables.map(variable => [variable.name, variable.example]) ); const sep = separator.trim() || '-'; const rendered = template.replace(/%[a-z_]+(?:\([^)]*\))?%/gi, token => token === '%sep%' ? sep : (examples.get(token) ?? '') ); const edge = new RegExp( `^(?:\\s*${escapeRegExp(sep)}\\s*)+|(?:\\s*${escapeRegExp(sep)}\\s*)+$`, 'g' ); const repeated = new RegExp(`(?:\\s*${escapeRegExp(sep)}\\s*){2,}`, 'g'); return rendered .replace(/\s+/g, ' ') .replace(repeated, ` ${sep} `) .replace(edge, '') .trim(); };