140 lines
8.9 KiB
JavaScript
140 lines
8.9 KiB
JavaScript
// The HTTP Client's "Preview" of an HTML answer: the page drawn as the site would, in a sandboxed frame (srcdoc, no
|
|
// allow-same-origin: it can never reach the IDE). What the page links (stylesheets, @import, fonts and pictures of the CSS,
|
|
// <img>, srcset, inline style url(), icons) is fetched by the IDE's backend (command http.resources: the request's own TLS
|
|
// setting and cookies, same host / same site only) and put inside the page (CSS as <style>, the rest as data: URLs).
|
|
// Scripts stay off unless "Scripts" is on. "Reload resources" fetches everything again; a note lists what failed.
|
|
import { backend } from './backend.js';
|
|
import { el, t, prefs } from './ui.js';
|
|
import { textOfBase64 } from './html-preview.js';
|
|
import { resolveUrl, srcsetParts, cssNeeds, rewriteCss, mimeOfAnswer } from './http-preview-model.js';
|
|
|
|
const caches = new WeakMap(); // a response -> the resources already fetched (a tab switch does not fetch again)
|
|
const MEDIA = [['img[src]', 'src'], ['source[src]', 'src'], ['video[src]', 'src'], ['audio[src]', 'src'], ['video[poster]', 'poster'],
|
|
['input[type="image" i][src]', 'src'], ['link[rel~="icon" i][href]', 'href'], ['link[rel~="apple-touch-icon" i][href]', 'href'], ['object[data]', 'data'], ['embed[src]', 'src']];
|
|
|
|
/** the preview of the response r (its url is the base of every link), appended to box */
|
|
export function responsePreview(box, r, verify = true) {
|
|
const base = r.url || '';
|
|
let generation = 0;
|
|
const scripts = el('input', { type: 'checkbox', onchange: () => { prefs.set('httpPreviewScripts', scripts.checked); draw(); } });
|
|
scripts.checked = !!prefs.get('httpPreviewScripts', false);
|
|
const note = el('div.hc-preview-note');
|
|
const frame = el('iframe.hc-preview', { sandbox: '', srcdoc: '' });
|
|
const reload = el('button.btn', { title: t('Fetch the stylesheets, pictures and fonts of the page again'), onclick: () => { caches.delete(r); draw(); } }, t('Reload resources'));
|
|
box.append(el('div.hc-line', {}, reload, el('label.hc-check', {}, scripts, t('Scripts')), note), frame);
|
|
|
|
async function draw() {
|
|
const mine = ++generation;
|
|
note.textContent = t('Loading the page\'s resources…');
|
|
note.className = 'hc-preview-note';
|
|
if (!caches.has(r)) caches.set(r, new Map());
|
|
let built;
|
|
try {
|
|
built = await buildPreview(r.body, base, verify, scripts.checked, caches.get(r));
|
|
} catch (e) {
|
|
built = { html: r.body, failed: [{ url: base, why: e.message || String(e) }] };
|
|
}
|
|
if (mine !== generation) return;
|
|
frame.setAttribute('sandbox', scripts.checked ? 'allow-scripts' : '');
|
|
frame.srcdoc = built.html;
|
|
note.className = 'hc-preview-note' + (built.failed.length ? ' warn' : '');
|
|
note.textContent = '';
|
|
if (built.failed.length) {
|
|
note.append(el('span', {}, t('{n} resources not loaded', { n: built.failed.length })),
|
|
el('div.hc-preview-failed', {}, ...built.failed.map((f) => el('div', {}, el('code', {}, f.url), ' ', el('span.hc-hint', {}, t(f.why))))));
|
|
}
|
|
}
|
|
draw();
|
|
}
|
|
|
|
/** @returns {Promise<{html: string, failed: {url: string, why: string}[]}>} */
|
|
export async function buildPreview(source, pageUrl, verify, scripts, cache) {
|
|
const doc = new DOMParser().parseFromString(source, 'text/html');
|
|
let base = pageUrl;
|
|
const baseTag = doc.querySelector('base[href]');
|
|
if (baseTag) base = resolveUrl(pageUrl, baseTag.getAttribute('href')) || pageUrl;
|
|
const failed = new Map();
|
|
const noteFail = (url, why) => { if (!failed.has(url)) failed.set(url, why); };
|
|
const abs = (link) => resolveUrl(base, link);
|
|
|
|
async function fetchMissing(urls) {
|
|
const todo = [...new Set(urls)].filter((u) => !cache.has(u));
|
|
for (let i = 0; i < todo.length; i += 100) {
|
|
const chunk = todo.slice(i, i + 100);
|
|
let got = {};
|
|
try { got = (await backend.invoke('http.resources', { base: pageUrl, urls: chunk, verify })).resources || {}; } catch (e) { for (const u of chunk) got[u] = { ok: false, error: e.message || String(e) }; }
|
|
for (const u of chunk) cache.set(u, got[u] || { ok: false, error: 'no answer' });
|
|
}
|
|
}
|
|
const text = (url) => { const c = cache.get(url); return c?.ok ? textOfBase64(c.base64) : null; };
|
|
const dataUrl = (url) => { const c = cache.get(url); return c?.ok ? `data:${mimeOfAnswer(c.type, url)};base64,${c.base64}` : null; };
|
|
const lookup = (url, kind) => (kind === 'import' ? text(url) : dataUrl(url));
|
|
const check = (url) => { const c = cache.get(url); if (!c?.ok) noteFail(url, c?.error || 'not loaded'); return c?.ok ? c : null; };
|
|
|
|
// 1. the page's own links
|
|
const sheets = [...doc.querySelectorAll('link[rel~="stylesheet" i][href]')].map((link) => ({ link, url: abs(link.getAttribute('href')) })).filter((s) => s.url);
|
|
const pageUrls = sheets.map((s) => s.url);
|
|
const mediaNodes = [];
|
|
for (const [selector, attr] of MEDIA) for (const node of doc.querySelectorAll(selector)) { const url = abs(node.getAttribute(attr)); if (url) { mediaNodes.push({ node, attr, url }); pageUrls.push(url); } }
|
|
const srcsets = [...doc.querySelectorAll('[srcset]')].map((node) => ({ node, parts: srcsetParts(node.getAttribute('srcset')).map((p) => ({ ...p, abs: abs(p.url) })) }));
|
|
for (const s of srcsets) for (const p of s.parts) if (p.abs) pageUrls.push(p.abs);
|
|
const svgImages = [...doc.querySelectorAll('image[href]')].map((node) => ({ node, url: abs(node.getAttribute('href')) })).filter((s) => s.url);
|
|
pageUrls.push(...svgImages.map((s) => s.url));
|
|
const scriptNodes = scripts ? [...doc.querySelectorAll('script[src]')].map((node) => ({ node, url: abs(node.getAttribute('src')) })) : [];
|
|
pageUrls.push(...scriptNodes.map((s) => s.url).filter(Boolean));
|
|
await fetchMissing(pageUrls);
|
|
|
|
// 2. the CSS: what the stylesheets (and their imports) need, round after round
|
|
const inlineCss = [...doc.querySelectorAll('style')].map((s) => ({ text: s.textContent, base }));
|
|
const styled = [...doc.querySelectorAll('[style]')].filter((n) => /url\(/i.test(n.getAttribute('style')));
|
|
const known = [...inlineCss, ...styled.map((n) => ({ text: n.getAttribute('style'), base })), ...sheets.map((s) => ({ text: text(s.url), base: s.url }))];
|
|
const walked = new Set();
|
|
for (let round = 0; round < 5; round++) {
|
|
const needs = [];
|
|
for (const c of known) {
|
|
if (c.text === null || c.text === undefined || walked.has(c)) continue;
|
|
walked.add(c);
|
|
for (const u of cssNeeds(c.text, c.base)) { needs.push(u); }
|
|
}
|
|
if (!needs.length) break;
|
|
await fetchMissing(needs);
|
|
for (const u of needs) if (/\.css(\?|$)|text\/css/i.test(u + ' ' + (cache.get(u)?.type || ''))) known.push({ text: text(u), base: u });
|
|
}
|
|
|
|
// 3. everything into the page
|
|
const css = (value, from) => rewriteCss(value, from, lookup, (u) => check(u));
|
|
for (const { link, url } of sheets) {
|
|
const body = check(url) ? text(url) : null;
|
|
const style = doc.createElement('style');
|
|
style.dataset.hc = '1';
|
|
if (link.media) style.media = link.media;
|
|
style.textContent = body === null ? `/* ${url}: not loaded */` : css(body, url);
|
|
link.replaceWith(style);
|
|
}
|
|
for (const style of doc.querySelectorAll('style:not([data-hc])')) style.textContent = css(style.textContent, base);
|
|
for (const node of styled) node.setAttribute('style', css(node.getAttribute('style'), base));
|
|
for (const { node, attr, url } of mediaNodes) node.setAttribute(attr, check(url) ? dataUrl(url) : '');
|
|
for (const { node, parts } of srcsets) {
|
|
node.setAttribute('srcset', parts.map((p) => [p.abs && check(p.abs) ? dataUrl(p.abs) : p.url, p.rest].filter(Boolean).join(' ')).join(', '));
|
|
}
|
|
for (const { node, url } of svgImages) node.setAttribute('href', check(url) ? dataUrl(url) : '');
|
|
for (const script of [...doc.querySelectorAll('script')]) {
|
|
const entry = scriptNodes.find((s) => s.node === script);
|
|
if (!scripts) { script.remove(); continue; }
|
|
if (script.hasAttribute('src')) {
|
|
const code = entry?.url && check(entry.url) ? text(entry.url) : null;
|
|
if (code === null) { script.remove(); continue; }
|
|
script.removeAttribute('src');
|
|
script.textContent = code;
|
|
}
|
|
}
|
|
// no navigation, no refresh, no other base; our own policy: only what is inside the page
|
|
for (const old of doc.querySelectorAll('meta[http-equiv]')) if (/refresh|content-security-policy/i.test(old.getAttribute('http-equiv'))) old.remove();
|
|
for (const old of doc.querySelectorAll('base')) old.remove();
|
|
const csp = doc.createElement('meta');
|
|
csp.setAttribute('http-equiv', 'Content-Security-Policy');
|
|
csp.setAttribute('content', `default-src 'none'; style-src 'unsafe-inline' data:; img-src data: blob:; font-src data:; media-src data: blob:; script-src ${scripts ? "'unsafe-inline'" : "'none'"}; form-action 'none'; connect-src 'none'; frame-src 'none'`);
|
|
doc.head.prepend(csp);
|
|
if (!doc.querySelector('meta[charset]')) { const m = doc.createElement('meta'); m.setAttribute('charset', 'utf-8'); doc.head.prepend(m); }
|
|
return { html: '<!doctype html>\n' + doc.documentElement.outerHTML, failed: [...failed].map(([url, why]) => ({ url, why })) };
|
|
}
|