diff --git a/src/utils/lang/html.ts b/src/utils/lang/html.ts index 8a897b2..1fe3d40 100644 --- a/src/utils/lang/html.ts +++ b/src/utils/lang/html.ts @@ -4,6 +4,53 @@ export function isHTML(maybeHTML: string): boolean { return [...$div.childNodes].reverse().some(($child) => $child.nodeType === 1) } +function getFetchResolverScript() { + return `` +} + function getTitle(html: string) { // TODO: Regex might reasonably be faster here const $div = document.createElement('div') @@ -24,7 +71,10 @@ export interface HTMLPageData { export function processHTML(html: string, url: string): HTMLPageData { const processedHTML = html // Add base tag to iframe - .replace(/]*)>/i, ``) + .replace( + /]*)>/i, + `${getFetchResolverScript()}`, + ) // Replace absolute paths with relative paths .replace(/((src|href|content)=")\/(.*?")/gm, '$1$3') diff --git a/tests/html.test.ts b/tests/html.test.ts new file mode 100644 index 0000000..53cb387 --- /dev/null +++ b/tests/html.test.ts @@ -0,0 +1,50 @@ +import { processHTML } from '../src/utils/lang/html' + +const HTML_URL = + 'https://gitlab.com/sirajchokshi/static-preview-test/-/raw/main/wasm.html' + +describe('[HTML] processHTML', () => { + it('injects base url and runtime fetch resolver', () => { + const html = ` + + + + WASM | Static Preview Test + + + + + + ` + + const { processedHTML, title } = processHTML(html, HTML_URL) + + expect(processedHTML).toContain(``) + expect(processedHTML).toContain('data-static-preview-fetch-resolver') + expect(processedHTML).toContain('window.fetch = (input, init) =>') + expect(title).toEqual('WASM | Static Preview Test') + }) + + it('rewrites leading slash paths to document-relative paths', () => { + const html = ` + + + + + + + + Home + + + + ` + + const { processedHTML } = processHTML(html, HTML_URL) + + expect(processedHTML).toContain('href="assets/main.css"') + expect(processedHTML).toContain('content="assets/preview.png"') + expect(processedHTML).toContain('href="index.html"') + expect(processedHTML).toContain('src="assets/wasm.js"') + }) +})