assets.ts (7141B)
1 import DOMPurify from 'dompurify'; 2 import { extensionOf, resolvePath, templateReference } from './paths'; 3 import type { TemplateSet } from './types'; 4 5 const MIME = new Map([ 6 ['.css', 'text/css'], 7 ['.svg', 'image/svg+xml'], 8 ['.png', 'image/png'], 9 ['.jpg', 'image/jpeg'], 10 ['.jpeg', 'image/jpeg'], 11 ['.webp', 'image/webp'], 12 ['.gif', 'image/gif'], 13 ['.woff', 'font/woff'], 14 ['.woff2', 'font/woff2'], 15 ['.ttf', 'font/ttf'], 16 ['.otf', 'font/otf'], 17 ]); 18 19 const EXTERNAL = /^(?:https?:)?\/\//i; 20 const DATA = /^data:/i; 21 const BLOB = /^blob:/i; 22 23 function mimeFor(path: string) { 24 return MIME.get(extensionOf(path)) || 'application/octet-stream'; 25 } 26 27 export class TemplateAssets { 28 private objectUrls = new Map<string, string>(); 29 private styleUrls = new Map<string, string>(); 30 private styleLinks = new Map<string, HTMLLinkElement>(); 31 private styleReady = new Map<string, Promise<void>>(); 32 private cssStack = new Set<string>(); 33 34 constructor(private templates: TemplateSet) {} 35 36 private file(path: string) { 37 const file = this.templates.files.get(path); 38 if (!file) throw new Error(`Missing template asset: ${path}`); 39 return file; 40 } 41 42 private objectUrl(path: string) { 43 const cached = this.objectUrls.get(path); 44 if (cached) return cached; 45 46 const file = this.file(path); 47 const url = URL.createObjectURL(new Blob([file.data], { type: mimeFor(path) })); 48 this.objectUrls.set(path, url); 49 return url; 50 } 51 52 private rewriteReference(reference: string, baseFile: string) { 53 const value = reference.trim(); 54 if (!value) throw new Error(`Empty asset reference in ${baseFile}`); 55 if (DATA.test(value) || BLOB.test(value) || value.startsWith('#')) return value; 56 if (EXTERNAL.test(value)) { 57 throw new Error(`External template asset is not allowed: ${value}`); 58 } 59 60 const templatePath = templateReference(value); 61 const path = templatePath || resolvePath(baseFile, value); 62 return this.objectUrl(path); 63 } 64 65 rewriteCss(css: string, baseFile: string) { 66 let output = css 67 .replace(/expression\s*\(/gi, '') 68 .replace(/behavior\s*:/gi, '') 69 .replace(/-moz-binding\s*:/gi, ''); 70 71 output = output.replace( 72 /@import\s+(?:url\(\s*)?(["']?)([^"')\s]+)\1\s*\)?\s*;/gi, 73 (_match, _quote, reference) => { 74 const templatePath = templateReference(reference); 75 const path = templatePath || resolvePath(baseFile, reference); 76 return `@import url("${this.cssUrl(path)}");`; 77 } 78 ); 79 80 return output.replace( 81 /url\(\s*(["']?)([^"')]+)\1\s*\)/gi, 82 (_match, _quote, reference) => 83 `url("${this.rewriteReference(reference, baseFile)}")` 84 ); 85 } 86 87 private cssUrl(path: string) { 88 const cached = this.styleUrls.get(path); 89 if (cached) return cached; 90 if (this.cssStack.has(path)) throw new Error(`Circular CSS import: ${path}`); 91 92 this.cssStack.add(path); 93 try { 94 const text = new TextDecoder().decode(this.file(path).data); 95 const css = this.rewriteCss(text, path); 96 const url = URL.createObjectURL(new Blob([css], { type: 'text/css' })); 97 this.styleUrls.set(path, url); 98 this.objectUrls.set(`css:${path}`, url); 99 return url; 100 } finally { 101 this.cssStack.delete(path); 102 } 103 } 104 105 private addStylesheet(path: string, element: Element) { 106 if (this.styleLinks.has(path)) return; 107 108 const link = document.createElement('link'); 109 link.rel = 'stylesheet'; 110 link.href = this.cssUrl(path); 111 link.dataset.templatePocStyle = path; 112 const media = element.getAttribute('media'); 113 if (media) link.media = media; 114 115 const ready = new Promise<void>((resolve) => { 116 link.addEventListener('load', () => resolve(), { once: true }); 117 link.addEventListener('error', () => resolve(), { once: true }); 118 }); 119 120 document.head.append(link); 121 this.styleLinks.set(path, link); 122 this.styleReady.set(path, ready); 123 } 124 125 async stylesReady() { 126 await Promise.all(this.styleReady.values()); 127 } 128 129 private rewriteAttribute(element: Element, name: string) { 130 const value = element.getAttribute(name); 131 if (!value) return; 132 133 try { 134 element.setAttribute(name, this.rewriteReference(value, 'inline.hbs')); 135 } catch (error) { 136 element.removeAttribute(name); 137 if (element.tagName === 'IMG' || element.tagName === 'SOURCE') { 138 element.remove(); 139 } 140 throw error; 141 } 142 } 143 144 private rewriteSrcset(element: Element) { 145 const value = element.getAttribute('srcset'); 146 if (!value) return; 147 148 const candidates = value 149 .split(',') 150 .map((candidate) => candidate.trim()) 151 .filter(Boolean) 152 .map((candidate) => { 153 const [reference, ...descriptor] = candidate.split(/\s+/); 154 const url = this.rewriteReference(reference, 'inline.hbs'); 155 return [url, ...descriptor].join(' '); 156 }); 157 158 if (candidates.length > 0) element.setAttribute('srcset', candidates.join(', ')); 159 } 160 161 private prepareHeadStyles(fragment: DocumentFragment) { 162 for (const link of [...fragment.querySelectorAll('link')]) { 163 const rel = (link.getAttribute('rel') || '').toLowerCase().split(/\s+/); 164 const href = link.getAttribute('href') || ''; 165 const path = templateReference(href); 166 167 if (!rel.includes('stylesheet') || !path) { 168 link.remove(); 169 continue; 170 } 171 172 this.addStylesheet(path, link); 173 link.remove(); 174 } 175 } 176 177 private rewriteElement(element: Element, page: string) { 178 const tag = element.tagName.toLowerCase(); 179 if (tag === 'script' || tag === 'iframe' || tag === 'object' || tag === 'embed') { 180 element.remove(); 181 return; 182 } 183 184 if (tag === 'style') { 185 element.textContent = this.rewriteCss(element.textContent || '', page); 186 } 187 188 const style = element.getAttribute('style'); 189 if (style) element.setAttribute('style', this.rewriteCss(style, page)); 190 191 for (const name of ['src', 'poster']) { 192 if (element.hasAttribute(name)) this.rewriteAttribute(element, name); 193 } 194 if (element.hasAttribute('srcset')) this.rewriteSrcset(element); 195 196 if (tag === 'a') { 197 const href = element.getAttribute('href') || ''; 198 if (/^javascript:/i.test(href)) element.removeAttribute('href'); 199 } 200 } 201 202 rewriteHtml(input: string, page: string) { 203 const raw = document.createElement('template'); 204 raw.innerHTML = input; 205 this.prepareHeadStyles(raw.content); 206 207 const clean = DOMPurify.sanitize(raw.innerHTML, { 208 ALLOW_DATA_ATTR: true, 209 FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'base', 'meta', 'link'], 210 }); 211 212 const container = document.createElement('div'); 213 container.innerHTML = clean; 214 215 for (const element of [...container.querySelectorAll('*')]) { 216 this.rewriteElement(element, page); 217 } 218 219 return container.innerHTML; 220 } 221 222 dispose() { 223 for (const link of this.styleLinks.values()) link.remove(); 224 this.styleLinks.clear(); 225 this.styleUrls.clear(); 226 this.styleReady.clear(); 227 this.cssStack.clear(); 228 229 for (const url of this.objectUrls.values()) URL.revokeObjectURL(url); 230 this.objectUrls.clear(); 231 } 232 }