Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

htmlRender.ts

449 lines20.8 KB

1import { HTML_RENDER_SELECTION_SCRIPT } from "./htmlRenderSelectionScript.ts";
2import {
3 T3_CODE_DARK_THEME_COLORS,
4 T3_CODE_LIGHT_THEME_COLORS,
5 type ThemeAppearance,
6 type ThemeColors,
7} from "./themePalettes.ts";
8import { EVENT_CODE_SHORTCUT_KEYS } from "./keybindings.ts";
9​
10export const HTML_RENDER_TOOL_NAME = "html_render";
11export const HTML_RENDER_MIN_HEIGHT = 80;
12export const HTML_RENDER_MAX_HEIGHT = 2000;
13// A client fits the frame to the live page up to this height. It only stops a
14// page that grows with its frame, since vh units are rejected at publish.
15export const HTML_RENDER_MAX_FIT_HEIGHT = 20_000;
16export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
17​
18export interface HtmlRenderReference {
19 readonly attachmentId: string;
20 readonly title: string;
21 readonly height: number;
22 readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
24​
25export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;
26​
27export const HTML_RENDER_COLUMN_WIDTH = 728;
28​
29const MAX_MEASURED_HEIGHTS = 24;
30​
31function readMeasuredHeights(value: unknown) {
32 if (!Array.isArray(value) || value.length === 0 || value.length > MAX_MEASURED_HEIGHTS) {
33 return undefined;
34 }
35 const heights = value.flatMap((entry) =>
36 Array.isArray(entry) &&
37 entry.length === 2 &&
38 Number.isInteger(entry[0]) &&
39 entry[0] >= 1 &&
40 entry[0] <= 10_000 &&
41 typeof entry[1] === "number" &&
42 Number.isFinite(entry[1])
43 ? [[entry[0] as number, clampHtmlRenderHeight(entry[1])] as const]
44 : [],
45 );
46 return heights.length === value.length
47 ? [...heights].sort((left, right) => left[0] - right[0])
48 : undefined;
50​
51export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
52 if (typeof value !== "object" || value === null) return undefined;
53 const { attachmentId, title, height, heights } = value as Record<string, unknown>;
54 if (
55 typeof attachmentId !== "string" ||
56 attachmentId.length === 0 ||
57 attachmentId.length > 256 ||
58 typeof title !== "string" ||
59 typeof height !== "number" ||
60 !Number.isFinite(height)
61 ) {
62 return undefined;
63 }
64 const measured = readMeasuredHeights(heights);
65 return {
66 attachmentId,
67 title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
68 height: clampHtmlRenderHeight(height),
69 ...(measured === undefined ? {} : { heights: measured }),
70 };
72​
73export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: HtmlRenderReference) {
74 return (
75 left.attachmentId === right.attachmentId &&
76 left.title === right.title &&
77 left.height === right.height &&
78 (left.heights ?? []).length === (right.heights ?? []).length &&
79 (left.heights ?? []).every(
80 ([width, height], index) =>
81 right.heights?.[index]?.[0] === width && right.heights[index][1] === height,
82 )
83 );
85​
86// Use the taller neighboring measurement because breakpoints can select either height.
87function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
88 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
89 const high = above === -1 ? heights.length - 1 : above;
90 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
91 return Math.max(heights[low]![1], heights[high]![1]);
93​
94/**
95 * A page even a few pixels taller than its frame scrolls inside it and takes
96 * the reader's scroll, so the frame fits the page. A client that measured the
97 * live page passes `contentHeight`, which wins over the agent's height: client
98 * fonts often wrap the page taller than the server or agent measured it.
99 */
100export function htmlRenderFrameHeight(
101 reference: HtmlRenderReference,
102 width: number,
103 contentHeight?: number,
104) {
105 if (contentHeight !== undefined) {
106 return Math.min(
107 HTML_RENDER_MAX_FIT_HEIGHT,
108 Math.max(HTML_RENDER_MIN_HEIGHT, Math.ceil(contentHeight)),
109 );
110 }
111 const heights = reference.heights;
112 if (heights === undefined || heights.length === 0) {
113 return clampHtmlRenderHeight(reference.height);
114 }
115 const cap =
116 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
117 ? reference.height
118 : HTML_RENDER_MAX_HEIGHT;
119 return clampHtmlRenderHeight(Math.min(cap, measuredHeight(heights, width)));
121​
122export function htmlRenderFileName(title: string) {
123 const name = title
124 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
125 .replace(/\s+/g, " ")
126 .trim()
127 .slice(0, 120)
128 .trim();
129 return `${name || "Page"}.html`;
131​
132export function clampHtmlRenderHeight(height: number): number {
133 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
135​
136export interface HtmlRenderFonts {
137 readonly sans: string;
138 readonly mono: string;
140​
141export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
142 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
143 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
144 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
145};
146​
147/** Arial-metric substitutes keep measured wrapping close to client system fonts. */
148export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
149 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
150 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
151};
152​
153export interface HtmlRenderTheme {
154 readonly appearance: ThemeAppearance;
155 readonly variables: Readonly<Record<string, string>>;
157​
158const FIXED_COLORS = {
159 light: {
160 success: "#10b981",
161 successForeground: "#047857",
162 info: "#3b82f6",
163 infoForeground: "#1d4ed8",
164 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
165 },
166 dark: {
167 success: "#10b981",
168 successForeground: "#34d399",
169 info: "#3b82f6",
170 infoForeground: "#60a5fa",
171 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
172 },
173} as const;
174​
175/** Uses app tokens, except --accent is the brand color rather than a neutral hover surface. */
176export function htmlRenderTheme(
177 colors: ThemeColors,
178 appearance: ThemeAppearance,
179 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
180): HtmlRenderTheme {
181 const fixed = FIXED_COLORS[appearance];
182 return {
183 appearance,
184 variables: {
185 "--background": colors.canvas,
186 "--foreground": colors.text,
187 "--muted": colors.muted,
188 "--muted-foreground": colors.mutedForeground,
189 "--card": colors.surface,
190 "--card-foreground": colors.text,
191 "--popover": colors.surfaceOverlay,
192 "--popover-foreground": colors.text,
193 "--secondary": colors.secondary,
194 "--secondary-foreground": colors.secondaryForeground,
195 "--border": colors.border,
196 "--input": colors.input,
197 "--ring": colors.focus,
198 "--primary": colors.messageAction,
199 "--primary-foreground": colors.messageActionForeground,
200 "--accent": colors.accent,
201 "--accent-foreground": colors.accentForeground,
202 "--accent-surface": colors.accentSurface,
203 "--accent-surface-foreground": colors.accentSurfaceForeground,
204 "--destructive": colors.error,
205 "--destructive-foreground": colors.errorForeground,
206 "--destructive-surface": colors.errorSurface,
207 "--warning": colors.warning,
208 "--warning-foreground": colors.warningForeground,
209 "--warning-surface": colors.warningSurface,
210 "--success": fixed.success,
211 "--success-foreground": fixed.successForeground,
212 "--info": fixed.info,
213 "--info-foreground": fixed.infoForeground,
214 "--code-background": colors.codeBackground,
215 "--code-foreground": colors.codeForeground,
216 "--chart-1": colors.accent,
217 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
218 "--radius": "0.625rem",
219 "--font-sans": fonts.sans,
220 "--font-mono": fonts.mono,
221 },
222 };
224​
225export const HTML_RENDER_THEME_GUIDE = [
226 "Use theme CSS variables on :root, not fixed colors:",
227 "--background, --foreground, --muted, --card, --popover, --secondary, --border, --ring, --primary, --accent, --destructive, --warning, --success, --info, --code-background",
228 "(most have a matching -foreground; accent, destructive, and warning also have -surface),",
229 "--chart-1 to --chart-6, --radius, --font-sans, --font-mono.",
230 "The base sheet sets background, text, and font.",
231].join(" ");
232​
233export const HTML_RENDER_LAYOUT_GUIDE = [
234 `Frame width is reply width (${HTML_RENDER_COLUMN_WIDTH}px desktop, about 360px phones), on the thread background.`,
235 "Leave html, body, and the outer element with no background color, no outer card, border, banner title, or side padding. This wins over any rule that sets a page background.",
236 "T3 adds an overridable 8px html gutter for selection rings and shadows. Use fluid widths within it.",
237 "A box that needs its own background gets 16px padding and var(--radius) corners. Give charts fixed pixel heights.",
238 "Let content set the height. Do not use vh units or height:100% on html or body. Both are rejected or loop.",
239].join(" ");
240​
241const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
242const OPEN_LINK_METHOD = "ui/open-link";
243const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
244// Custom bridge forwards app shortcuts because focused frames otherwise capture them.
245const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
246const KEY_DOWN_METHOD = "t3/notifications/keydown";
247const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
248​
249export function readHtmlRenderContentHeight(data: unknown): number | undefined {
250 if (typeof data !== "object" || data === null) return undefined;
251 const { jsonrpc, method, params } = data as Record<string, unknown>;
252 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
253 const height =
254 typeof params === "object" && params !== null
255 ? (params as { height?: unknown }).height
256 : undefined;
257 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
259​
260export function readHtmlRenderLinkRequest(data: unknown):
261 | {
262 readonly id: string | number;
263 readonly url: string;
264 readonly metaKey: boolean;
265 readonly ctrlKey: boolean;
266 }
267 | undefined {
268 if (typeof data !== "object" || data === null) return undefined;
269 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
270 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
271 if (typeof id !== "string" && typeof id !== "number") return undefined;
272 if (typeof params !== "object" || params === null) return undefined;
273 const { url, metaKey, ctrlKey } = params as Record<string, unknown>;
274 return typeof url === "string" && /^https?:\/\//i.test(url)
275 ? { id, url, metaKey: metaKey === true, ctrlKey: ctrlKey === true }
276 : undefined;
278​
279/** Published local images arrive as `data:image/` URLs. */
280export function readHtmlRenderImageRequest(
281 data: unknown,
282): { readonly src: string; readonly name: string } | undefined {
283 if (typeof data !== "object" || data === null) return undefined;
284 const { jsonrpc, method, params } = data as Record<string, unknown>;
285 if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
286 if (typeof params !== "object" || params === null) return undefined;
287 const { src, name } = params as Record<string, unknown>;
288 if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
289 const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";
290 return { src, name: label || "Image" };
292​
293export function readHtmlRenderKeyDown(data: unknown):
294 | {
295 readonly key: string;
296 readonly code: string;
297 readonly metaKey: boolean;
298 readonly ctrlKey: boolean;
299 readonly shiftKey: boolean;
300 readonly altKey: boolean;
301 readonly repeat: boolean;
302 }
303 | undefined {
304 if (typeof data !== "object" || data === null) return undefined;
305 const { jsonrpc, method, params } = data as Record<string, unknown>;
306 if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
307 if (typeof params !== "object" || params === null) return undefined;
308 const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
309 string,
310 unknown
311 >;
312 if (typeof key !== "string" || typeof code !== "string") return undefined;
313 return {
314 key,
315 code,
316 metaKey: metaKey === true,
317 ctrlKey: ctrlKey === true,
318 shiftKey: shiftKey === true,
319 altKey: altKey === true,
320 repeat: repeat === true,
321 };
323​
324export interface HtmlRenderShortcut {
325 readonly key: string;
326 readonly metaKey: boolean;
327 readonly ctrlKey: boolean;
328 readonly shiftKey: boolean;
329 readonly altKey: boolean;
331​
332export function htmlRenderShortcutsMessage(
333 shortcuts: ReadonlyArray<HtmlRenderShortcut>,
334 blocked: ReadonlyArray<HtmlRenderShortcut>,
335) {
336 return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
338​
339export function htmlRenderResult(id: string | number) {
340 return { jsonrpc: "2.0", id, result: {} } as const;
342​
343const THEME_FRAGMENT_KEY = "t3-theme";
344​
345export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
346 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
348​
349export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
350 return {
351 jsonrpc: "2.0",
352 method: HOST_CONTEXT_CHANGED_METHOD,
353 params: { theme: theme.appearance, styles: { variables: theme.variables } },
354 } as const;
356​
357const BASE_CSS =
358 "html{box-sizing:border-box;padding:8px;background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;scrollbar-width:none}" +
359 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
360 // Focus outlines paint inside the element, so the frame edge never clips them.
361 ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
362 ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
363​
364function rootRule(theme: HtmlRenderTheme): string {
365 const declarations = Object.entries(theme.variables)
366 .map(([name, value]) => `${name}:${value};`)
367 .join("");
368 return `:root{color-scheme:${theme.appearance};${declarations}}`;
370​
371// Apply overridable theme CSS before paint and strip the fragment before routing; framed navigation uses the client.
372// Forward shortcuts after page handlers; text fields retain their keys.
373const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href,metaKey:e.metaKey,ctrlKey:e.ctrlKey}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);window.addEventListener("click",function(e){var t=e.composedPath()[0],u;if(!e.isTrusted||e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||!t||t.tagName!=="IMG"||t.closest("a[href],button"))return;u=t.currentSrc||t.src;if(u)setTimeout(function(){if(!e.defaultPrevented)window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||""}},"*");});});var K=[],B=[],C=${JSON.stringify(EVENT_CODE_SHORTCUT_KEYS)};window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(e.source===window.parent&&d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(SHORTCUTS_METHOD)}&&p&&Array.isArray(p.shortcuts)&&Array.isArray(p.blocked)){K=p.shortcuts;B=p.blocked;}});window.addEventListener("keydown",function(e){var t=e.composedPath()[0],c=e.code||"",l=e.key.toLowerCase(),x=/^[a-z]$/.test(l)?[l]:[l,/^Key[A-Z]$/.test(c)?c.slice(3).toLowerCase():"",C.hasOwnProperty(c)?C[c]:""],f,m=function(s){return s&&s.metaKey===e.metaKey&&s.ctrlKey===e.ctrlKey&&s.shiftKey===e.shiftKey&&s.altKey===e.altKey&&x.indexOf(s.key)>-1;};if(!e.isTrusted||e.isComposing||e.getModifierState("AltGraph")&&!/^[a-z0-9]$/i.test(e.key)||t&&(t.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(t.tagName))||!K.some(m)||B.some(m))return;f=function(v){window.removeEventListener("keydown",f);if(v!==e||e.defaultPrevented)return;e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(KEY_DOWN_METHOD)},params:{key:e.key,code:e.code,metaKey:e.metaKey,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,repeat:e.repeat}},"*");};window.addEventListener("keydown",f);setTimeout(function(){window.removeEventListener("keydown",f);});},true);}})();`;
374​
375function bootstrapMarkup(markup: string): string {
376 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
377 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
378 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
379 return [
380 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
381 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
382 ? ""
383 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
384 `<style id="t3-theme">${defaultCss}</style>`,
385 `<script>${BOOTSTRAP_SCRIPT}</script>`,
386 ].join("");
388​
389// Blank inert content without shifting offsets so it cannot receive the bootstrap.
390const blankNonMarkup = (html: string) => {
391 const scan = html.replace(
392 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
393 (match) => " ".repeat(match.length),
394 );
395 const parts: string[] = [];
396 let depth = 0;
397 let start = 0;
398 let at = 0;
399 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
400 if (!match[1]) {
401 if (depth++ === 0) start = match.index;
402 } else if (depth > 0 && --depth === 0) {
403 const end = match.index + match[0].length;
404 parts.push(scan.slice(at, start), " ".repeat(end - start));
405 at = end;
406 }
407 }
408 if (depth > 0) {
409 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
410 at = scan.length;
411 }
412 parts.push(scan.slice(at));
413 return parts.join("");
414};
415​
416export function injectHtmlRenderBootstrap(html: string): string {
417 const scan = blankNonMarkup(html);
418 const markup = bootstrapMarkup(scan);
419 return injectHtmlRenderHead(html, markup);
421​
422/** Adds selection support to saved renders without changing their stored contents. */
423export function injectHtmlSelectionBridge(html: string): string {
424 return injectHtmlRenderHead(
425 html,
426 `<style>::highlight(t3-html-citation){background:color-mix(in srgb,var(--accent) 45%,transparent)}</style><script>${HTML_RENDER_SELECTION_SCRIPT}</script>`,
427 );
429​
430/** Inserts host-owned bridge markup ahead of an agent page's head content. */
431function injectHtmlRenderHead(html: string, markup: string): string {
432 const scan = blankNonMarkup(html);
433 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
434 if (headOpen) {
435 const at = headOpen.index + headOpen[0].length;
436 return html.slice(0, at) + markup + html.slice(at);
437 }
438 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
439 if (htmlOpen) {
440 const at = htmlOpen.index + htmlOpen[0].length;
441 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
442 }
443 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
444 if (doctype) {
445 const at = doctype[0].length;
446 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
447 }
448 return `<!doctype html><head>${markup}</head>${html}`;