/**
* Desktop-shell HTML preview inlining.
*
* The shell only injects its `x-dsh-desktop-renderer` header for a subframe
* whose origin is literally `dsh-app://app`; a sandboxed HTML preview frame is
* an opaque origin, so both the document navigation and every resource it
* requests from `dsh-app:` are rejected by the shell before they reach the
* plugin's routes (#1143). The sanctioned shape (the host's own document
* preview uses it) is a self-contained document in a sandboxed `blob:` frame:
* the trusted top frame fetches the HTML and its local resources through the
* plugin routes, rewrites them to `data:` URLs / inline style and script
* blocks, and the frame then needs no `dsh-app:` request at all.
*
* This module is pure on purpose (no fetch, no React): the caller supplies
* `fetchResource`, so the resolution and rewriting rules are unit-testable and
* the component owns transport, aborting and object-URL lifetime.
*
* Only same-origin resources are inlined. External http(s) URLs, `data:`,
* `blob:` and `file:` are left exactly as authored; a failed local fetch also
* leaves the authored reference (the page still renders, the one resource
* may not). The returned document is always UTF-8 and keeps the route's
* `object-src 'none'` defense as a meta CSP; the iframe sandbox attribute
* remains the primary boundary (no `allow-same-origin` is ever added).
*/
/** One fetched local resource, already in memory. */
export interface InlineResource {
readonly bytes: Uint8Array
readonly mediaType: string
}
/**
* Fetch one same-origin resource. The caller decides how (the component uses
* `fetch` with same-origin credentials and an abort signal); returning
* undefined means "leave the authored reference alone".
*/
export type FetchInlineResource = (url: string) => Promise
/** Same protocol, credentials, host and port — `URL.origin` is `null` for
* custom schemes such as `dsh-app:`, so it cannot be used here. */
function sameOrigin(a: URL, b: URL): boolean {
return a.protocol === b.protocol
&& a.username === b.username
&& a.password === b.password
&& a.hostname === b.hostname
&& a.port === b.port
}
/**
* Resolve a same-origin resource reference. Returns undefined for empty /
* fragment destinations, external origins, and every non-http(s)/non-custom
* protocol this preview cannot inline.
*/
export function inlineableUrl(reference: string, baseUrl: string): URL | undefined {
const trimmed = reference.trim()
if (trimmed === '' || trimmed.startsWith('#')) return undefined
let url: URL
let base: URL
try {
base = new URL(baseUrl)
url = new URL(trimmed, base)
} catch {
return undefined
}
if (url.protocol === 'data:' || url.protocol === 'blob:' || url.protocol === 'file:' || url.protocol === 'javascript:') {
return undefined
}
if (!sameOrigin(url, base)) return undefined
return url
}
/** Base64 in bounded chunks so a multi-megabyte asset cannot overflow the
* argument stack through `String.fromCharCode(...bytes)`. */
export function bytesToBase64(bytes: Uint8Array): string {
let binary = ''
const chunk = 0x8000
for (let offset = 0; offset < bytes.length; offset += chunk) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunk))
}
return btoa(binary)
}
/** The displayable `data:` URL for one fetched resource. */
function dataUrlOf(resource: InlineResource): string {
const mediaType = resource.mediaType === '' ? 'application/octet-stream' : resource.mediaType
return `data:${mediaType};base64,${bytesToBase64(resource.bytes)}`
}
/** Decode a text resource (HTML is fetched separately by the caller). */
function decodeText(bytes: Uint8Array): string {
return new TextDecoder('utf-8').decode(bytes)
}
/**
* Per-document resource cache: the same image/CSS URL used twice is fetched
* once, and every failure is memoized as "not inlined" instead of retried.
*/
class ResourceCache {
private readonly entries = new Map>()
constructor(private readonly fetchResource: FetchInlineResource) {}
get(url: string): Promise {
let entry = this.entries.get(url)
if (entry === undefined) {
entry = this.fetchResource(url).catch(() => undefined)
this.entries.set(url, entry)
}
return entry
}
}
/** `url(...)` in CSS, with or without quotes. */
const CSS_URL_RE = /url\(\s*(?:(["'])(.*?)\1|([^'")\s]+))\s*\)/gi
/** `@import "x";` / `@import url(x) screen;`. */
const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?(?:(["'])(.*?)\1|([^'")\s;]+))\s*\)?\s*([^;]*);/gi
/** The referenced URL of one `url(...)` match. */
function cssUrlOf(match: RegExpMatchArray): string | undefined {
return match[2] ?? match[3]
}
/**
* Rewrite one stylesheet's `@import` and `url(...)` references to inlined
* content. Imported stylesheets are recursively expanded; a cycle yields an
* empty expansion. Failures leave the authored reference untouched.
* @param css - The stylesheet source.
* @param cssUrl - The stylesheet's own URL (base for relative references).
* @param cache - Per-document resource cache.
* @param seen - Stylesheet URLs already on the current import chain.
* @returns The rewritten CSS.
*/
async function inlineCss(css: string, cssUrl: string, cache: ResourceCache, seen: ReadonlySet = new Set()): Promise {
if (seen.has(cssUrl)) return ''
const chain = new Set(seen)
chain.add(cssUrl)
const importReplacements = new Map()
for (const match of [...css.matchAll(CSS_IMPORT_RE)]) {
const reference = cssUrlOf(match)
if (reference === undefined) continue
const url = inlineableUrl(reference, cssUrl)
if (url === undefined) continue
const resource = await cache.get(url.href)
if (resource === undefined) continue
const nested = await inlineCss(decodeText(resource.bytes), url.href, cache, chain)
const media = (match[4] ?? '').trim()
importReplacements.set(match[0], media === '' ? nested : `@media ${media} {\n${nested}\n}`)
}
const withImports = css.replace(CSS_IMPORT_RE, (match) => importReplacements.get(match) ?? match)
const urlReplacements = new Map()
const references = new Set()
for (const match of withImports.matchAll(CSS_URL_RE)) {
const reference = cssUrlOf(match)
if (reference === undefined || reference.startsWith('#')) continue
references.add(reference)
}
await Promise.all([...references].map(async (reference) => {
const url = inlineableUrl(reference, cssUrl)
if (url === undefined) return
const resource = await cache.get(url.href)
if (resource === undefined) return
urlReplacements.set(reference, `url("${dataUrlOf(resource)}")`)
}))
return withImports.replace(CSS_URL_RE, (match, _quote: string | undefined, quoted: string | undefined, bare: string | undefined) => {
const reference = quoted ?? bare
if (reference === undefined) return match
return urlReplacements.get(reference) ?? match
})
}
/** Inline one attribute that holds a single resource URL. */
async function inlineAttribute(element: Element, attribute: string, baseUrl: string, cache: ResourceCache): Promise {
const reference = element.getAttribute(attribute)
if (reference === null) return
const url = inlineableUrl(reference, baseUrl)
if (url === undefined) return
const resource = await cache.get(url.href)
if (resource === undefined) return
element.setAttribute(attribute, dataUrlOf(resource))
}
/** Rewrite a `srcset` attribute. A value already carrying an inline/data URL
* is left alone: splitting it on commas would mangle the payload. */
async function inlineSrcset(value: string, baseUrl: string, cache: ResourceCache): Promise {
if (/\b(?:data|blob):/i.test(value)) return value
const candidates = value.split(',').map(candidate => candidate.trim()).filter(candidate => candidate !== '')
const rewritten: string[] = []
for (const candidate of candidates) {
const match = /^(\S+)(\s+.*)?$/.exec(candidate)
if (match === null) {
rewritten.push(candidate)
continue
}
const url = inlineableUrl(match[1] ?? '', baseUrl)
if (url === undefined) {
rewritten.push(candidate)
continue
}
const resource = await cache.get(url.href)
rewritten.push(resource === undefined ? candidate : `${dataUrlOf(resource)}${match[2] ?? ''}`)
}
return rewritten.join(', ')
}
/** Inline one stylesheet `` as a `