@format.dev/zip 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -25
- package/dist/index.d.mts +279 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1001 -0
- package/dist/index.mjs.map +1 -0
- package/dist/scan.d.mts +61 -0
- package/dist/scan.d.mts.map +1 -0
- package/dist/scan.mjs +263 -0
- package/dist/scan.mjs.map +1 -0
- package/dist/web.d.mts +245 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +13896 -0
- package/dist/web.mjs.map +1 -0
- package/package.json +67 -34
- package/index.d.ts +0 -2
- package/index.js +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["matchAll","out: string[]","code: FormatZipErrorCode","relPath: string","ref: string","url: string","mimeType?: string","urls: string[]","out: string[]","importPromises: Promise<void>[]","context: CssWalkContext","cssPromises: Promise<void>[]","files: Record<string, Uint8Array>","resolve","manifest: Record<string, string>","entries: Record<string, Uint8Array>","resolveFromZip: AssetResolver","zip","files: Record<string, Uint8Array>","ordered: Record<string, Uint8Array>","ENTITIES: Record<string, string>","out: string[]","parseHtmlRefs","linkHrefs: string[]","scanRemoteRefs","zipWithResolver"],"sources":["../src/parse-css.ts","../src/parse.ts","../src/errors.ts","../package.json","../src/constants.ts","../src/path-utils.ts","../src/helpers.ts","../src/zip.ts","../src/dir-resolver.ts","../src/junk-files.ts","../src/zip-dir.ts","../src/url-resolver.ts","../src/scan-core.ts","../src/scan-lite.ts","../src/scan-remote.ts","../src/index.ts"],"sourcesContent":["import type { CssRefs } from './scan-core'\n\n// CSS needs only url() and @import targets — narrow enough that a small,\n// comment-stripped tokenizer beats pulling in postcss. Zero dependencies, so\n// both the node-html-parser path (parse.ts, used by zip()) and the regex\n// scanner (scan-lite.ts, used by the cheap static check) share this one CSS\n// implementation without either dragging in the other's HTML parser.\n\nconst CSS_COMMENT_RE = /\\/\\*[\\s\\S]*?\\*\\//g\nconst CSS_URL_RE = /url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)'\"\\s][^)]*?))\\s*\\)/gi\nconst CSS_IMPORT_RE = /@import\\s+(?:url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)'\"]+?))\\s*\\)|\"([^\"]*)\"|'([^']*)')/gi\n\nfunction matchAll(input: string, pattern: RegExp): string[] {\n\tconst out: string[] = []\n\n\tfor (const match of input.matchAll(pattern)) {\n\t\tconst value = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5]\n\n\t\t// keep an empty value (url(\"\")) — the collector reports it as a broken ref;\n\t\t// only skip when no capture group matched at all\n\t\tif (value != null) {\n\t\t\tout.push(value.trim())\n\t\t}\n\t}\n\n\treturn out\n}\n\n/**\n * Pull every `url(...)` target and every `@import` target out of a CSS string.\n * Comments are stripped first so a commented-out reference is never collected.\n * Pure and IO-free.\n */\nexport function parseCssRefs(cssText: string): CssRefs {\n\tconst withoutComments = cssText.replace(CSS_COMMENT_RE, '')\n\tconst imports = matchAll(withoutComments, CSS_IMPORT_RE)\n\n\t// strip @import statements before scanning url() so an @import url() form\n\t// isn't counted twice (the full parser separated these by rule type)\n\tconst withoutImports = withoutComments.replace(CSS_IMPORT_RE, '')\n\t// a bare fragment like url(#gradient) points at an element already in the\n\t// document (an SVG paint server, clip-path, mask, or filter) so there is no\n\t// file to bundle\n\tconst urls = matchAll(withoutImports, CSS_URL_RE).filter(ref => !ref.startsWith('#'))\n\n\treturn { urls, imports }\n}\n","import type { HtmlRefs } from './scan-core'\n\nimport { parse } from 'node-html-parser'\n\n// The HTML parser behind zip()'s collection: node-html-parser, real parsing\n// that runs in Node and browsers. This is the heavier path and ships only\n// where zip() is imported (dynamic-mode wrappers, the public Node entry,\n// Studio's server) — never in static-mode bundles, which use the regex scanner\n// in scan-lite for their cheap check. CSS is handled by parse-css (shared).\n\nexport { parseCssRefs } from './parse-css'\n\n/**\n * Pull raw asset references out of an HTML string with a single parse pass.\n * Pure and IO-free.\n */\nexport function parseHtmlRefs(html: string): HtmlRefs {\n\tconst root = parse(html)\n\n\t// a present-but-empty ref (src=\"\", href=\"\") is kept, not dropped: it names no\n\t// file, so zip()'s collector reports it as a broken reference. only a\n\t// genuinely absent attribute (getAttribute returns null/undefined) is filtered\n\t// out here.\n\tconst imgSrcs = root\n\t\t.querySelectorAll('img[src]')\n\t\t.map(element => element.getAttribute('src'))\n\t\t.filter((src): src is string => src != null)\n\n\t// inline-SVG external references: <image href> and <use href>, plus the legacy\n\t// `xlink:href` form – a bare fragment (e.g. <use href=\"#icon\">) points at an\n\t// element already in the document, so there is no file to bundle\n\tconst svgHrefs = root\n\t\t.querySelectorAll('image, use')\n\t\t.map(element => element.getAttribute('href') ?? element.getAttribute('xlink:href'))\n\t\t.filter((href): href is string => href != null && !href.startsWith('#'))\n\n\tconst linkHrefs = root\n\t\t.querySelectorAll('link[rel=\"stylesheet\"][href]')\n\t\t.map(element => element.getAttribute('href'))\n\t\t.filter((href): href is string => href != null)\n\n\tconst styleBlocks = root.querySelectorAll('style').map(element => element.innerHTML)\n\tconst styleAttrs = root.querySelectorAll('[style]').map(element => element.getAttribute('style') ?? '')\n\n\treturn { imgSrcs, svgHrefs, linkHrefs, inlineCss: [...styleBlocks, ...styleAttrs] }\n}\n","/**\n * Every error thrown by `@format.dev/zip` (and by compiled documents while building\n * their assets zip) extends this class. The umbrella check lets callers branch\n * once on \"this is a zip-side failure\", then narrow further by `code`.\n *\n * Mirrors `FormatError` from `@format.dev/client`: a single class to catch, a\n * `code` field to dispatch on.\n */\nexport type FormatZipErrorCode =\n\t| 'MISSING_ASSET'\n\t| 'UNRESOLVABLE_REF'\n\t| 'ASSET_MISMATCH'\n\t| 'INVALID_EXTENSION'\n\t| 'REMOTE_ASSETS_DISABLED'\n\t| 'REMOTE_ASSET_FETCH'\n\nexport class FormatZipError extends Error {\n\tconstructor(\n\t\tpublic readonly code: FormatZipErrorCode,\n\t\tmessage: string,\n\t\toptions?: ErrorOptions\n\t) {\n\t\tsuper(message, options)\n\t}\n}\n\nexport class MissingAssetError extends FormatZipError {\n\tconstructor(public relPath: string) {\n\t\tsuper('MISSING_ASSET', `Asset not found: ${relPath}`)\n\t}\n}\n\n/**\n * Thrown by `zip()` when the HTML references a local asset that resolves to no\n * file: an empty `src`/`href`/`url(\"\")`, or one like `/`, `.`, or `..` that\n * points at the bundle root (a directory) rather than a file. A same-document\n * fragment (`url(#gradient)`) is not this: it names an element already in the\n * document and is skipped silently. Reported with a warning instead of thrown\n * when `skipMissing` is set.\n */\nexport class UnresolvableRefError extends FormatZipError {\n\tconstructor(public ref: string) {\n\t\tconst reason = ref.trim() === '' ? 'it is empty' : 'it resolves to the bundle root, not a file'\n\t\tsuper('UNRESOLVABLE_REF', `Unresolvable asset reference ${JSON.stringify(ref)}: ${reason}`)\n\t}\n}\n\nexport interface AssetMismatchDetail {\n\tdocumentName: string\n\tmode: 'static' | 'dynamic'\n\tmissing: string[]\n\tknown: string[]\n\t/**\n\t * Remote (http/https) URLs the HTML references. The render-time check attaches\n\t * these so a later step can find broken remotes even when local assets are\n\t * already missing — they are referenced, not yet known to be unreachable.\n\t */\n\tremoteRefs?: string[]\n\t/** Remote URLs that could not be loaded, filled in once they have been probed. */\n\tbrokenRemote?: string[]\n}\n\nconst toBullets = (items: string[]) => items.map(item => `- ${item}`).join('\\n')\n\nfunction buildAssetMismatchMessage(detail: AssetMismatchDetail): string {\n\tconst { documentName, mode, missing, known, brokenRemote = [] } = detail\n\n\tconst sections = [`Missing assets for document \"${documentName}\"`]\n\n\tif (missing.length) {\n\t\tsections.push(`Missing local assets:\\n${toBullets(missing)}`)\n\t}\n\n\tif (brokenRemote.length) {\n\t\tsections.push(`Unreachable remote assets:\\n${toBullets(brokenRemote)}`)\n\t}\n\n\tif (known.length) {\n\t\tsections.push(`Known assets:\\n${toBullets(known)}`)\n\t}\n\n\tif (missing.length) {\n\t\t// In dynamic mode the asset is genuinely absent, so the static-only escape\n\t\t// hatch (switching to dynamic) does not apply — only suggest it for static.\n\t\tconst placement =\n\t\t\t\"Add the missing files to your shared assets folder (`sharedAssetsDir`) or the document's `assets` folder\"\n\n\t\tsections.push(\n\t\t\tmode === 'dynamic'\n\t\t\t\t? `${placement}.`\n\t\t\t\t: `${placement}, or consider using dynamic assets. Check the CLI options for \\`--assets\\`.`\n\t\t)\n\t}\n\n\tif (brokenRemote.length) {\n\t\tsections.push('Make sure the remote assets are reachable when the document is built.')\n\t}\n\n\treturn sections.join('\\n\\n')\n}\n\n/**\n * Thrown by a compiled document wrapper when rendered HTML references assets\n * the bundle cannot supply: local files not in its known-asset set, or remote\n * URLs that could not be loaded. Carries enough context for the consumer to fix\n * the source: add the file to the shared assets folder or the document's\n * `./assets/` folder, switch asset mode, or make the remote URL reachable.\n */\nexport class AssetMismatchError extends FormatZipError {\n\tpublic documentName: string\n\tpublic mode: 'static' | 'dynamic'\n\tpublic missing: string[]\n\tpublic known: string[]\n\tpublic remoteRefs: string[]\n\tpublic brokenRemote: string[]\n\n\tconstructor(detail: AssetMismatchDetail) {\n\t\tsuper('ASSET_MISMATCH', buildAssetMismatchMessage(detail))\n\n\t\tthis.name = 'AssetMismatchError'\n\t\tthis.documentName = detail.documentName\n\t\tthis.mode = detail.mode\n\t\tthis.missing = detail.missing\n\t\tthis.known = detail.known\n\t\tthis.remoteRefs = detail.remoteRefs ?? []\n\t\tthis.brokenRemote = detail.brokenRemote ?? []\n\t}\n}\n\nexport class InvalidExtensionError extends FormatZipError {\n\tconstructor(\n\t\tpublic url: string,\n\t\tpublic mimeType?: string\n\t) {\n\t\tsuper('INVALID_EXTENSION', `Cannot infer asset extension from URL and MIME type: ${url} (${mimeType})`)\n\t}\n}\n\n/**\n * Thrown by `zip()` when the HTML references remote (http/https) assets and\n * `remoteAssets` is not enabled. PDF generation never fetches remote\n * references at render time, so a zip built without them produces a broken\n * PDF — failing loudly here makes the gap visible at the source.\n */\nexport class RemoteAssetsDisabledError extends FormatZipError {\n\tconstructor(public urls: string[]) {\n\t\tsuper(\n\t\t\t'REMOTE_ASSETS_DISABLED',\n\t\t\t`Cannot fetch remote assets.\\n\\n` +\n\t\t\t\t`Your HTML references the following remote assets:\\n${toBullets(urls)}\\n\\n` +\n\t\t\t\t`Use \\`remoteAssets.enabled\\` to fetch assets, or use local assets (recommended).`\n\t\t)\n\t}\n}\n\n/**\n * Thrown when a remote asset cannot be fetched because the network itself\n * failed (offline machine, DNS failure, blocked egress, timeout) — as opposed\n * to the server answering with an error status. The message is written for the\n * common trap: a CI runner with no outbound network access.\n */\nexport class RemoteAssetFetchError extends FormatZipError {\n\tconstructor(\n\t\tpublic url: string,\n\t\tcause?: unknown\n\t) {\n\t\tsuper(\n\t\t\t'REMOTE_ASSET_FETCH',\n\t\t\t`Could not fetch remote asset \"${url}\". The machine running this build needs network access to that host`,\n\t\t\t{ cause }\n\t\t)\n\t}\n}\n","{\n\t\"name\": \"@format.dev/zip\",\n\t\"version\": \"0.1.1\",\n\t\"license\": \"MIT\",\n\t\"description\": \"Asset bundling for Format documents.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/zip\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.mjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": \"./dist/web.d.mts\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"worker\": {\n\t\t\t\t\"types\": \"./dist/web.d.mts\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": \"./dist/index.d.mts\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": \"./dist/web.d.mts\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t},\n\t\t\"./scan\": {\n\t\t\t\"types\": \"./dist/scan.d.mts\",\n\t\t\t\"default\": \"./dist/scan.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown && node scripts/check-self-contained.mjs\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"@format.dev/utils\": \"workspace:*\",\n\t\t\"fflate\": \"^0.8.2\",\n\t\t\"node-html-parser\": \"^7.1.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\",\n\t\t\"vitest\": \"^4.0.18\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=22.13.0\"\n\t}\n}\n","import { version } from '../package.json'\n\n// `process` is absent in workers/browsers; the platform suffix is best-effort.\nconst platformSuffix =\n\ttypeof process !== 'undefined' && process.platform ? ` (${process.platform}) node ${process.version}` : ''\n\nexport const USER_AGENT = `@format.dev/zip/${version}${platformSuffix}`\n\nexport const MANIFEST_FILE_NAME = 'format.manifest.json'\n\n/**\n * Fixed modification time stamped into every ZIP entry so archives are\n * reproducible. Without it, fflate writes `Date.now()` into each entry, so a\n * byte-identical asset set hashes differently on every build and can't be\n * deduplicated by content. Noon UTC on 1980-01-01 (the ZIP epoch) stays at or\n * above the format's 1980 minimum in every timezone. fflate encodes the DOS\n * time from local components, so output is reproducible within a timezone,\n * which is what content dedup from a given runtime needs.\n */\nexport const ZIP_EPOCH = Date.UTC(1980, 0, 1, 12)\n","// Minimal POSIX-style path helpers, dependency-free and runtime-portable.\n// `node:path` is unavailable in browsers and workers, so the shared zip core\n// can't reach for it. These cover only what the pipeline needs: normalize,\n// parse, and join, all operating on '/'-separated paths.\n\n/** Collapse '.', '..', and duplicate slashes, mirroring `path.posix.normalize`. */\nexport function normalizePath(input: string): string {\n\tconst isAbsolute = input.startsWith('/')\n\tconst out: string[] = []\n\n\tfor (const segment of input.split('/')) {\n\t\tif (segment === '' || segment === '.') {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (segment === '..') {\n\t\t\tconst canPop = out.length > 0 && out[out.length - 1] !== '..'\n\n\t\t\tif (canPop) {\n\t\t\t\tout.pop()\n\t\t\t} else if (!isAbsolute) {\n\t\t\t\tout.push('..')\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tout.push(segment)\n\t}\n\n\tconst joined = out.join('/')\n\n\tif (isAbsolute) {\n\t\treturn '/' + joined\n\t}\n\n\treturn joined || '.'\n}\n\n/** Split a path into dir/name/ext, mirroring `path.posix.parse`. */\nexport function parsePath(input: string): { dir: string; name: string; ext: string } {\n\tconst lastSlash = input.lastIndexOf('/')\n\tconst dir = lastSlash >= 0 ? input.slice(0, lastSlash) : ''\n\tconst base = lastSlash >= 0 ? input.slice(lastSlash + 1) : input\n\n\tconst lastDot = base.lastIndexOf('.')\n\n\t// A leading dot is part of the name (e.g. '.env'), so ignore dot at index 0.\n\tif (lastDot <= 0) {\n\t\treturn { dir, name: base, ext: '' }\n\t}\n\n\treturn { dir, name: base.slice(0, lastDot), ext: base.slice(lastDot) }\n}\n\n/** Join and normalize '/'-separated segments, mirroring `path.posix.join`. */\nexport function joinPath(...segments: string[]): string {\n\treturn normalizePath(segments.filter(Boolean).join('/'))\n}\n\n/**\n * Small, fast, non-cryptographic hash (FNV-1a, 32-bit) rendered as 8 hex chars.\n * Used only to give a remote asset's query string a stable, collision-resistant\n * filename suffix — it is not security-sensitive.\n */\nexport function hash8(input: string): string {\n\tlet hash = 0x811c9dc5\n\n\tfor (let index = 0; index < input.length; index++) {\n\t\thash ^= input.charCodeAt(index)\n\t\thash = Math.imul(hash, 0x01000193)\n\t}\n\n\treturn (hash >>> 0).toString(16).padStart(8, '0')\n}\n","import type { RemoteAsset, RemoteAssetFetcher, RemoteValidators, RequestHeaders, ZipOptions } from './types'\n\nimport { MIME_TO_EXT } from '@format.dev/utils'\nimport { InvalidExtensionError, RemoteAssetFetchError } from './errors'\nimport { USER_AGENT } from './constants'\nimport { normalizePath, parsePath, joinPath, hash8 } from './path-utils'\n\ninterface RemoteRequestParams {\n\turl: string\n\theaders?: RequestHeaders\n\ttimeoutMs?: number\n}\n\ninterface ConditionalRemoteRequestParams extends RemoteRequestParams {\n\tvalidators: RemoteValidators\n}\n\n/**\n * Fetch a remote asset and return its bytes, parsed MIME type, and the\n * validators the server sent, so a caller holding the bytes can later ask\n * whether they changed with {@link fetchRemoteIfChanged}.\n *\n * Uses `fetch` + `arrayBuffer()` rather than a Node stream so the remote path\n * stays portable across Node, workers, and browsers.\n *\n * @throws {RemoteAssetFetchError} when the network itself fails (offline, DNS,\n * blocked egress, timeout). HTTP error statuses throw a plain Error — the\n * server was reachable, so it's a different problem.\n */\nexport async function fetchRemote(params: RemoteRequestParams): Promise<RemoteAsset> {\n\tconst response = await requestRemote(params)\n\n\treturn readRemoteResponse(response, params.url)\n}\n\n/**\n * Ask the server whether a remote asset changed since `validators` were\n * issued. Returns `null` on `304 Not Modified`, otherwise the full asset. A\n * server that sent no validators gets an ordinary request, so this always\n * downloads there.\n *\n * @throws {RemoteAssetFetchError} and plain HTTP errors, as {@link fetchRemote}.\n */\nexport async function fetchRemoteIfChanged(params: ConditionalRemoteRequestParams): Promise<RemoteAsset | null> {\n\tconst { validators } = params\n\n\tconst headers = new Headers(params.headers)\n\n\tif (validators.etag) {\n\t\theaders.set('If-None-Match', validators.etag)\n\t}\n\n\tif (validators.lastModified) {\n\t\theaders.set('If-Modified-Since', validators.lastModified)\n\t}\n\n\tconst response = await requestRemote({ ...params, headers })\n\n\tif (response.status === 304) {\n\t\treturn null\n\t}\n\n\treturn readRemoteResponse(response, params.url)\n}\n\nasync function requestRemote(params: RemoteRequestParams): Promise<Response> {\n\tconst { url, headers: requestHeaders, timeoutMs = 15_000 } = params\n\n\tconst signal = AbortSignal.timeout(timeoutMs)\n\tconst headers = new Headers(requestHeaders)\n\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', USER_AGENT)\n\t}\n\n\ttry {\n\t\treturn await fetch(url, { signal, redirect: 'follow', headers })\n\t} catch (cause) {\n\t\tthrow new RemoteAssetFetchError(url, cause)\n\t}\n}\n\nasync function readRemoteResponse(response: Response, url: string): Promise<RemoteAsset> {\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP ${response.status} for ${url}`)\n\t}\n\n\tconst bytes = new Uint8Array(await response.arrayBuffer())\n\tconst mimeType = parseContentType(response.headers.get('content-type') || undefined)\n\n\tconst etag = response.headers.get('etag') ?? undefined\n\tconst lastModified = response.headers.get('last-modified') ?? undefined\n\n\treturn { bytes, mimeType, validators: { etag, lastModified } }\n}\n\n/**\n * The fetcher every remote read in this package goes through: the caller's\n * `remoteAssets.fetch` when they supplied one, otherwise {@link fetchRemote}.\n * Binds the headers and timeout from the same options so a custom fetcher gets\n * the same request shape the built-in one would have used.\n */\nexport function remoteFetcher(options?: ZipOptions): (url: string) => ReturnType<RemoteAssetFetcher> {\n\tconst fetcher = options?.remoteAssets?.fetch ?? fetchRemote\n\n\treturn url =>\n\t\tfetcher({\n\t\t\turl,\n\t\t\theaders: options?.remoteAssets?.headers,\n\t\t\ttimeoutMs: options?.remoteAssets?.timeoutMs\n\t\t})\n}\n\n/**\n * Probe each remote URL and return the ones that can't be loaded — a failed\n * request or a non-OK status, the same \"broken\" definition `fetchRemote` uses.\n * Collects every failure rather than stopping at the first, so callers can report\n * the full set. Runs the probes concurrently.\n */\nexport async function findBrokenRemoteAssets(params: {\n\turls: string[]\n\theaders?: RequestHeaders\n\ttimeoutMs?: number\n\tfetch?: RemoteAssetFetcher\n}): Promise<string[]> {\n\tconst { urls, headers, timeoutMs, fetch: customFetch } = params\n\n\tconst probe = customFetch ?? fetchRemote\n\n\tconst results = await Promise.all(\n\t\turls.map(async url => {\n\t\t\ttry {\n\t\t\t\tawait probe({ url, headers, timeoutMs })\n\t\t\t\treturn null\n\t\t\t} catch {\n\t\t\t\treturn url\n\t\t\t}\n\t\t})\n\t)\n\n\treturn results.filter((url): url is string => url !== null)\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header?: string): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\n// note: for simplicity, we are ignoring protocol-relative URLs\nexport function isRemoteOrigin(href: string) {\n\ttry {\n\t\tconst url = new URL(href)\n\t\treturn url.protocol === 'http:' || url.protocol === 'https:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function isSameOrigin(href: string, base: string) {\n\ttry {\n\t\tconst url = new URL(href, base)\n\t\treturn url.origin === base\n\t} catch {\n\t\t// invalid url syntax\n\t\treturn false\n\t}\n}\n\n// A random, unguessable origin used to detect local (relative) references:\n// anything that resolves against it is local. `crypto.randomUUID` is a\n// web-standard global (browsers, workers, Node 18+); the fallback covers the\n// rare runtime without it. This is not security-sensitive.\nfunction randomLocalOrigin(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.()\n\n\tif (uuid) {\n\t\treturn `https://${uuid}`\n\t}\n\n\treturn `https://local-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`\n}\n\nconst LOCAL_ORIGIN_BASE = randomLocalOrigin()\nexport const isLocalOrigin = (href: string) => isSameOrigin(href, LOCAL_ORIGIN_BASE)\n\n// turn something like \"/a/../b///./c\" into \"b/c\" safely\nexport function normalizeDir(rawDir: string): string {\n\t// force an absolute base so \"..\" can't climb above root\n\t// and normalize to collapse \".\", \"..\", and duplicate slashes\n\tconst abs = normalizePath('/' + rawDir.replace(/^\\/+/, ''))\n\t// drop the leading \"/\" to make it relative again for zip entry joining\n\treturn abs === '/' ? '' : abs.slice(1)\n}\n\n// a deterministic, safe zip entry path for a remote URL\nexport function urlToZipName(url: string, mimeType?: string): string {\n\tconst u = new URL(url)\n\n\tif (u.protocol !== 'http:' && u.protocol !== 'https:') {\n\t\tthrow new Error(`Unsupported protocol: ${u.protocol}`)\n\t}\n\n\t// ensure a filename even for trailing slashes\n\tlet pathname = u.pathname\n\tif (pathname.endsWith('/')) {\n\t\tpathname += 'index'\n\t}\n\n\tlet { dir, name, ext } = parsePath(pathname)\n\n\tif (!ext && mimeType) {\n\t\text = MIME_TO_EXT[mimeType.toLowerCase()]\n\t}\n\n\tif (!ext) {\n\t\tthrow new InvalidExtensionError(url, mimeType)\n\t}\n\n\t// order-insensitive stable query hash\n\tconst qs = [...u.searchParams.entries()]\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([key, value]) => `${key}=${value}`)\n\t\t.join('&')\n\tconst queryHash = qs ? `__${hash8(qs)}` : ''\n\n\t// sanitize filename segment (replace any character that is not a word char, a dot, or a hyphen)\n\tconst hostname = u.hostname.toLowerCase()\n\tconst port = `_${u.port || (u.protocol === 'https:' ? '443' : '80')}`\n\tconst safeDir = normalizeDir(dir)\n\tconst safeName = `${name.replace(/[^\\w.-]/g, '_')}${queryHash}${ext}`\n\n\treturn joinPath('remote', `${hostname}${port}`, safeDir, safeName)\n}\n\nexport function resolveLocalUrl(href: string) {\n\tconst url = new URL(href, LOCAL_ORIGIN_BASE)\n\treturn url.pathname.replace('/', '')\n}\n\n/**\n * Resolve a local href to a safe, POSIX-style relative path for a zip entry.\n * - Strips query/hash\n * - Resolves dot-segments relative to baseRel\n * - Drops leading slashes\n * - Normalizes duplicate slashes\n *\n * Returns `null` for a ref that names no file to bundle: a bare fragment\n * (`#gradient`), a `data:` URL, or anything that resolves to the bundle root\n * itself. This is a pure path helper — what a null means (skip a fragment, or\n * report a broken `src`/`href`/`url()`) is the caller's policy, not this\n * function's.\n */\nexport function resolveLocalRef(href: string, baseRel = '.'): string | null {\n\t// a fragment points at an element already in the document, and a data: URL\n\t// carries its bytes inline — neither is a file on disk\n\tif (href.startsWith('#') || href.startsWith('data:')) {\n\t\treturn null\n\t}\n\n\t// build a base URL whose pathname reflects the referring file's location\n\t// e.g. baseRel = \"css/app/main.css\" -> base pathname \"/css/app/main.css\"\n\tconst base = new URL('/' + normalizePath(baseRel), LOCAL_ORIGIN_BASE)\n\tconst url = new URL(href, base)\n\n\t// get normalized pathname and make it relative (no leading slash)\n\tlet pathname = url.pathname.replace(/^\\/+/, '') // drop all leading slashes\n\tpathname = normalizePath(pathname) // collapse duplicate slashes, \".\", etc\n\n\t// normalizePath returns \".\" for an empty path, i.e. the ref resolved to the\n\t// bundle root — a directory, never a file to bundle\n\tif (pathname === '.') {\n\t\treturn null\n\t}\n\n\treturn pathname\n}\n","import type { AssetResolver, StoredRemoteAsset, ZipOptions } from './types'\n\nimport { strToU8, unzipSync, zipSync } from 'fflate'\nimport { parseCssRefs, parseHtmlRefs } from './parse'\nimport { isLocalOrigin, isRemoteOrigin, remoteFetcher, resolveLocalRef, urlToZipName } from './helpers'\nimport { MissingAssetError, RemoteAssetsDisabledError, UnresolvableRefError } from './errors'\nimport { MANIFEST_FILE_NAME, ZIP_EPOCH } from './constants'\n\nconst utf8 = new TextDecoder('utf-8')\n\ntype DeflateLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n\ninterface CssWalkContext {\n\tresolve: AssetResolver\n\tassetPaths: Set<string>\n\tvisitedCss: Set<string>\n\t/** Remote refs found while remoteAssets is disabled — collected to fail loudly after the walk. */\n\tskippedRemote: Set<string>\n\toptions?: ZipOptions\n}\n\n/**\n * Resolve a local ref to its bundle path, or surface it when it names no file to\n * bundle. A bare `#id` fragment is a same-document reference (an SVG paint\n * server, clip-path, mask, or filter), so it returns null and is skipped\n * silently. Anything else that resolves to nothing is a broken reference — an\n * empty `src`/`href`/`url(\"\")`, or one like `/` or `.` that points at the bundle\n * root — so it is reported rather than dropped: a warning when `skipMissing` is\n * set, an {@link UnresolvableRefError} otherwise.\n */\nfunction resolveLocalOrReport(ref: string, baseRel: string, options?: ZipOptions): string | null {\n\tconst local = resolveLocalRef(ref, baseRel)\n\tif (local) {\n\t\treturn local\n\t}\n\n\tif (ref.startsWith('#')) {\n\t\treturn null\n\t}\n\n\tif (options?.skipMissing) {\n\t\tconsole.warn(`[zip] Unresolvable asset reference, skipping: ${JSON.stringify(ref)}`)\n\t\treturn null\n\t}\n\n\tthrow new UnresolvableRefError(ref)\n}\n\n/**\n * Read a local CSS file through the resolver, record it, then walk its contents.\n */\nasync function processCssFile(cssRel: string, context: CssWalkContext) {\n\tif (context.visitedCss.has(cssRel)) {\n\t\treturn\n\t}\n\tcontext.visitedCss.add(cssRel)\n\n\tconst bytes = await context.resolve(cssRel)\n\n\tif (!bytes) {\n\t\tconsole.warn(`[zip] CSS file not found, skipping: ${cssRel}`)\n\t\treturn\n\t}\n\n\tcontext.assetPaths.add(cssRel)\n\n\tawait processCssContent(utf8.decode(bytes), cssRel, context)\n}\n\n/**\n * Fetch a remote CSS file, record its URL, then walk its contents.\n */\nasync function processRemoteCssFile(remoteUrl: string, context: CssWalkContext) {\n\tif (context.visitedCss.has(remoteUrl)) {\n\t\treturn\n\t}\n\tcontext.visitedCss.add(remoteUrl)\n\n\ttry {\n\t\tconst { bytes } = await remoteFetcher(context.options)(remoteUrl)\n\n\t\tcontext.assetPaths.add(remoteUrl)\n\n\t\tawait processCssContent(utf8.decode(bytes), '.', context, remoteUrl)\n\t} catch (error) {\n\t\tif (context.options?.skipMissing) {\n\t\t\tconsole.log(`[zip] Could not fetch remote CSS \"${remoteUrl}\". Continuing as skipMissing is set.`, error)\n\t\t\treturn\n\t\t}\n\n\t\tthrow error\n\t}\n}\n\n/**\n * Walk one CSS string: record every local/remote url() target and follow every\n * @import. `baseRel` is the referring file's path so relative refs resolve\n * correctly; `remoteBaseUrl` switches resolution into remote-URL space.\n */\nasync function processCssContent(cssText: string, baseRel: string, context: CssWalkContext, remoteBaseUrl?: string) {\n\tconst { assetPaths, options } = context\n\tconst allowRemote = options?.remoteAssets?.enabled === true\n\tconst { urls, imports } = parseCssRefs(cssText)\n\tconst importPromises: Promise<void>[] = []\n\n\tfor (const importPath of imports) {\n\t\tif (remoteBaseUrl) {\n\t\t\tif (!allowRemote) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst url = new URL(importPath, remoteBaseUrl).toString()\n\t\t\t\tif (isRemoteOrigin(url)) {\n\t\t\t\t\timportPromises.push(processRemoteCssFile(url, context))\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.warn(`[zip] Error parsing remote CSS @import (base: ${remoteBaseUrl}, path: ${importPath})`, error)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isLocalOrigin(importPath)) {\n\t\t\tconst local = resolveLocalOrReport(importPath, baseRel, options)\n\t\t\tif (local) {\n\t\t\t\timportPromises.push(processCssFile(local, context))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isRemoteOrigin(importPath)) {\n\t\t\tif (allowRemote) {\n\t\t\t\timportPromises.push(processRemoteCssFile(new URL(importPath).toString(), context))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.skippedRemote.add(importPath)\n\t\t}\n\t}\n\n\tfor (const ref of urls) {\n\t\tif (remoteBaseUrl) {\n\t\t\tif (!allowRemote) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst url = new URL(ref, remoteBaseUrl).toString()\n\t\t\t\tif (isRemoteOrigin(url)) {\n\t\t\t\t\tassetPaths.add(url)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.warn(`[zip] Error parsing remote CSS url() (base: ${remoteBaseUrl}, path: ${ref})`, error)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isLocalOrigin(ref)) {\n\t\t\tconst local = resolveLocalOrReport(ref, baseRel, options)\n\t\t\tif (local) {\n\t\t\t\tassetPaths.add(local)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif (isRemoteOrigin(ref)) {\n\t\t\tif (allowRemote) {\n\t\t\t\tassetPaths.add(new URL(ref).toString())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.skippedRemote.add(ref)\n\t\t}\n\t}\n\n\tawait Promise.all(importPromises)\n}\n\n/**\n * Collect every asset path referenced by `html`: `<img src>`, inline-SVG\n * `<image>`/`<use>` hrefs, `<link rel=stylesheet>` (following nested @import\n * chains via the resolver), and `url(...)` in `<style>` blocks and style\n * attributes. Local refs come back as bundle-root relative paths; remote URLs\n * are included only when `options.remoteAssets.enabled` is set.\n *\n * @throws {RemoteAssetsDisabledError} when remote refs are found and\n * `remoteAssets` is not enabled — a zip without them produces a broken PDF.\n */\nexport async function collectAssetPaths(\n\thtml: string,\n\tresolve: AssetResolver,\n\toptions?: ZipOptions\n): Promise<Set<string>> {\n\tconst { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parseHtmlRefs(html)\n\tconst assetPaths = new Set<string>()\n\tconst allowRemote = options?.remoteAssets?.enabled === true\n\tconst context: CssWalkContext = { resolve, assetPaths, visitedCss: new Set(), skippedRemote: new Set(), options }\n\n\tconst addElementRef = (ref: string) => {\n\t\tif (isLocalOrigin(ref)) {\n\t\t\tconst local = resolveLocalOrReport(ref, '.', options)\n\t\t\tif (local) {\n\t\t\t\tassetPaths.add(local)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif (!isRemoteOrigin(ref)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (allowRemote) {\n\t\t\tassetPaths.add(ref)\n\t\t\treturn\n\t\t}\n\n\t\tcontext.skippedRemote.add(ref)\n\t}\n\n\tfor (const src of imgSrcs) {\n\t\taddElementRef(src)\n\t}\n\n\tfor (const href of svgHrefs) {\n\t\taddElementRef(href)\n\t}\n\n\tconst handleError = (error: unknown) => {\n\t\tif (options?.skipMissing) {\n\t\t\tconsole.warn('[zip] Error processing CSS content. Continuing as skipMissing is set.')\n\t\t\treturn\n\t\t}\n\n\t\tthrow error\n\t}\n\n\tconst cssPromises: Promise<void>[] = []\n\n\tfor (const href of linkHrefs) {\n\t\tif (isLocalOrigin(href)) {\n\t\t\tconst local = resolveLocalOrReport(href, '.', options)\n\t\t\tif (local) {\n\t\t\t\tcssPromises.push(processCssFile(local, context).catch(handleError))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!isRemoteOrigin(href)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (allowRemote) {\n\t\t\tcssPromises.push(processRemoteCssFile(href, context).catch(handleError))\n\t\t\tcontinue\n\t\t}\n\n\t\tcontext.skippedRemote.add(href)\n\t}\n\n\tfor (const cssText of inlineCss) {\n\t\tcssPromises.push(processCssContent(cssText, '.', context).catch(handleError))\n\t}\n\n\tawait Promise.all(cssPromises)\n\n\tif (!allowRemote && context.skippedRemote.size > 0) {\n\t\tthrow new RemoteAssetsDisabledError([...context.skippedRemote].sort())\n\t}\n\n\treturn assetPaths\n}\n\n/**\n * Resolve every collected asset to its bytes, keyed by zip entry name. Local\n * paths go through the resolver; remote URLs (internal) are fetched and renamed\n * deterministically, with a manifest mapping original URLs to entries.\n */\nasync function buildFileMap(\n\tassetPaths: Set<string>,\n\tresolve: AssetResolver,\n\toptions?: ZipOptions\n): Promise<Record<string, Uint8Array>> {\n\tconst files: Record<string, Uint8Array> = {}\n\tconst allowRemote = options?.remoteAssets?.enabled ?? false\n\n\tconst localPaths = [...assetPaths].filter(isLocalOrigin)\n\tconst localEntries = await Promise.all(localPaths.map(async name => ({ name, bytes: await resolve(name) })))\n\n\tfor (const { name, bytes } of localEntries) {\n\t\tif (bytes) {\n\t\t\tfiles[name] = bytes\n\t\t\tcontinue\n\t\t}\n\n\t\tif (options?.skipMissing) {\n\t\t\tconsole.warn(`[zip] Missing local asset, skipping: ${name}`)\n\t\t\tcontinue\n\t\t}\n\n\t\tthrow new MissingAssetError(name)\n\t}\n\n\tif (!allowRemote) {\n\t\treturn files\n\t}\n\n\tconst remotePaths = [...assetPaths].filter(isRemoteOrigin)\n\tconst manifest: Record<string, string> = {}\n\tconst fetchOne = remoteFetcher(options)\n\n\tconst remoteEntries = await Promise.all(\n\t\tremotePaths.map(async url => {\n\t\t\ttry {\n\t\t\t\tconst { bytes, mimeType } = await fetchOne(url)\n\t\t\t\treturn { url, name: urlToZipName(url, mimeType), bytes }\n\t\t\t} catch (error) {\n\t\t\t\tif (options?.skipMissing) {\n\t\t\t\t\tconsole.warn(`[zip] Missing remote asset, skipping: ${url}`)\n\t\t\t\t\treturn null\n\t\t\t\t}\n\n\t\t\t\tconsole.error(`[zip] Failed to fetch external asset: ${url}`, error)\n\t\t\t\tthrow new MissingAssetError(url)\n\t\t\t}\n\t\t})\n\t)\n\n\tfor (const entry of remoteEntries) {\n\t\tif (!entry) {\n\t\t\tcontinue\n\t\t}\n\n\t\tmanifest[entry.url] = entry.name\n\t\tfiles[entry.name] = entry.bytes\n\t}\n\n\tfiles[MANIFEST_FILE_NAME] = strToU8(JSON.stringify({ remoteAssets: manifest }))\n\n\treturn files\n}\n\n/** Entry names of an existing archive. A static-mode zip's entries are the document's known-asset set. */\nexport function listZipEntries(bytes: Uint8Array): string[] {\n\treturn Object.keys(unzipSync(bytes)).sort()\n}\n\n/**\n * The remote assets an archive already holds, from the manifest\n * {@link mergeRemoteAssets} writes, sorted by URL. Empty when the archive has\n * no manifest. Lets a caller compare what was bundled with what the server\n * serves now.\n */\nexport function readRemoteAssets(bytes: Uint8Array): StoredRemoteAsset[] {\n\tconst entries = unzipSync(bytes)\n\tconst manifestEntry = entries[MANIFEST_FILE_NAME]\n\n\tif (!manifestEntry) {\n\t\treturn []\n\t}\n\n\ttry {\n\t\tconst { remoteAssets = {} } = JSON.parse(utf8.decode(manifestEntry)) as { remoteAssets?: Record<string, string> }\n\n\t\treturn Object.entries(remoteAssets)\n\t\t\t.filter(([, name]) => entries[name] !== undefined)\n\t\t\t.map(([url, name]) => ({ url, bytes: entries[name]! }))\n\t\t\t.sort((a, b) => a.url.localeCompare(b.url))\n\t} catch {\n\t\treturn []\n\t}\n}\n\ninterface MergeRemoteAssetsArgs {\n\thtml: string\n\t/** Existing archive to merge into, or undefined to start fresh. */\n\tzip?: Uint8Array\n\toptions?: ZipOptions\n}\n\n/**\n * Fetch every remote (http/https) asset `html` references and merge it into an\n * existing archive, alongside a manifest mapping each URL to its zip entry.\n * Remote stylesheets are walked too, so a remote CSS file's fonts and images\n * come along with it. Local CSS already inside the archive is also walked for\n * remote references.\n *\n * URLs already present in the archive's manifest are not fetched again, so\n * calling this repeatedly over the same archive is idempotent and cheap.\n *\n * @returns the merged archive bytes; the input `zip` unchanged when `html`\n * references nothing remote that isn't already bundled; or `undefined` when\n * there is no input archive and nothing remote to fetch.\n * @throws {RemoteAssetFetchError} when the network itself is unreachable.\n */\nexport async function mergeRemoteAssets(args: MergeRemoteAssetsArgs): Promise<Uint8Array | undefined> {\n\tconst { html, zip: existingZip, options } = args\n\n\tconst entries: Record<string, Uint8Array> = existingZip ? unzipSync(existingZip) : {}\n\n\tconst manifest: Record<string, string> = {}\n\tconst manifestEntry = entries[MANIFEST_FILE_NAME]\n\n\tif (manifestEntry) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(utf8.decode(manifestEntry)) as { remoteAssets?: Record<string, string> }\n\t\t\tObject.assign(manifest, parsed.remoteAssets)\n\t\t} catch {\n\t\t\tconsole.warn(`[zip] Could not parse existing ${MANIFEST_FILE_NAME}, rebuilding the remote manifest`)\n\t\t}\n\t}\n\n\tconst resolveFromZip: AssetResolver = async relPath => entries[relPath] ?? null\n\n\tconst remoteOptions: ZipOptions = {\n\t\t...options,\n\t\tremoteAssets: { ...options?.remoteAssets, enabled: true }\n\t}\n\n\tconst assetPaths = await collectAssetPaths(html, resolveFromZip, remoteOptions)\n\tconst remoteUrls = [...assetPaths].filter(isRemoteOrigin).filter(url => !(url in manifest))\n\n\tif (remoteUrls.length === 0) {\n\t\treturn existingZip\n\t}\n\n\tconst fetchOne = remoteFetcher(options)\n\n\tconst fetched = await Promise.all(\n\t\tremoteUrls.map(async url => {\n\t\t\tconst { bytes, mimeType } = await fetchOne(url)\n\t\t\treturn { url, name: urlToZipName(url, mimeType), bytes }\n\t\t})\n\t)\n\n\tfor (const { url, name, bytes } of fetched) {\n\t\tmanifest[url] = name\n\t\tentries[name] = bytes\n\t}\n\n\tentries[MANIFEST_FILE_NAME] = strToU8(JSON.stringify({ remoteAssets: manifest }))\n\n\treturn zipSync(entries, { level: deflateLevel(options), mtime: ZIP_EPOCH })\n}\n\nexport function deflateLevel(options?: ZipOptions): DeflateLevel {\n\tconst level = options?.zlib?.level\n\tconst isValidLevel = typeof level === 'number' && level >= 0 && level <= 9\n\treturn (isValidLevel ? level : 6) as DeflateLevel\n}\n\n/**\n * Build a ZIP archive of every asset `html` references, resolving bytes through\n * `resolve`. Runs in Node, workers, and browsers (node-html-parser scans the\n * HTML).\n *\n * @returns the archive bytes, or `undefined` when `html` references no assets.\n * @throws {MissingAssetError} when `skipMissing` is unset and the resolver\n * returns `null` for a referenced asset.\n * @throws {UnresolvableRefError} when `skipMissing` is unset and a local ref\n * names no file — an empty `src`/`href`/`url(\"\")`, or one like `/` or `.` that\n * resolves to the bundle root.\n * @throws {RemoteAssetsDisabledError} when `html` references remote (http/https)\n * assets and `remoteAssets` is not enabled — they would be missing from the\n * archive and the PDF.\n */\nexport async function zip(html: string, resolve: AssetResolver, options?: ZipOptions): Promise<Uint8Array | undefined> {\n\tconst assetPaths = await collectAssetPaths(html, resolve, options)\n\n\tif (assetPaths.size === 0) {\n\t\treturn undefined\n\t}\n\n\tconst files = await buildFileMap(assetPaths, resolve, options)\n\n\treturn zipSync(files, { level: deflateLevel(options), mtime: ZIP_EPOCH })\n}\n","import type { AssetResolver } from './types'\n\nimport { join, resolve, sep } from 'node:path'\nimport { readFile } from 'node:fs/promises'\n\n/**\n * Node-only resolver that reads asset paths from a filesystem directory.\n * Returns `null` for any path that does not resolve to a readable file, or that\n * resolves outside the directory (path-traversal guard).\n *\n * This is what the Node `zip(html, dir)` overload uses under the hood, and the\n * compile-time resolver. It pulls in `node:fs`, so it lives in its own module\n * and is never reachable from the `@format.dev/zip/web` entry.\n */\nexport function dirResolver(dir: string): AssetResolver {\n\tconst root = resolve(dir)\n\n\treturn async relPath => {\n\t\tconst target = resolve(join(root, relPath))\n\t\tconst escapesRoot = target !== root && !target.startsWith(root + sep)\n\n\t\tif (escapesRoot) {\n\t\t\treturn null\n\t\t}\n\n\t\ttry {\n\t\t\treturn new Uint8Array(await readFile(target))\n\t\t} catch (error) {\n\t\t\t// missing (ENOENT), a directory (EISDIR), or a non-directory in the\n\t\t\t// path (ENOTDIR) all mean the ref names no readable file here\n\t\t\tconst code = (error as NodeJS.ErrnoException).code\n\t\t\tif (code === 'ENOENT' || code === 'EISDIR' || code === 'ENOTDIR') {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tthrow error\n\t\t}\n\t}\n}\n","// Metadata files the major operating systems scatter into folders: macOS Finder\n// state, Windows thumbnail caches and folder settings, Linux trash and lock\n// files. None are real assets, so we never list, hash, or bundle them.\n\nconst EXACT_JUNK_NAMES = new Set([\n\t'.DS_Store', // macOS Finder\n\t'.Spotlight-V100', // macOS Spotlight index\n\t'.DocumentRevisions-V100', // macOS versioning\n\t'.fseventsd', // macOS file events\n\t'.TemporaryItems', // macOS\n\t'.Trashes', // macOS volume trash\n\t'.VolumeIcon.icns', // macOS custom volume icon\n\t'.apdisk', // macOS disk image metadata\n\t'.directory' // Linux (KDE Dolphin folder settings)\n])\n\n// Windows filenames are case-insensitive, so match these regardless of case.\nconst CASE_INSENSITIVE_JUNK_NAMES = new Set(['thumbs.db', 'ehthumbs.db', 'ehthumbs_vista.db', 'desktop.ini'])\n\n/**\n * True when `name` (a single path segment, not a full path) is OS-generated\n * junk rather than a real file. Used to keep these out of asset listings,\n * archives, and cache hashes.\n */\nexport function isSystemJunkFile(name: string): boolean {\n\tif (EXACT_JUNK_NAMES.has(name)) {\n\t\treturn true\n\t}\n\n\tif (CASE_INSENSITIVE_JUNK_NAMES.has(name.toLowerCase())) {\n\t\treturn true\n\t}\n\n\tconst isAppleDoubleFork = name.startsWith('._') // macOS resource forks\n\tconst isLinuxTrash = name.startsWith('.Trash-') // Linux per-user trash\n\tconst isNfsLock = name.startsWith('.nfs') // Linux NFS silly-rename locks\n\n\treturn isAppleDoubleFork || isLinuxTrash || isNfsLock\n}\n","import type { ZipOptions } from './types'\n\nimport { readdir, readFile } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\nimport { zipSync } from 'fflate'\nimport { deflateLevel } from './zip'\nimport { isSystemJunkFile } from './junk-files'\nimport { ZIP_EPOCH } from './constants'\n\n/**\n * Zip the entire contents of a directory, preserving relative paths as entry\n * names ('/'-separated). No HTML scanning — this is the static-asset-mode\n * builder: every known asset ships, so any render works. Only OS-generated\n * junk (`.DS_Store`, `Thumbs.db`, and friends) is skipped.\n *\n * Node-only (reads the filesystem).\n *\n * @returns the archive bytes, or `undefined` when the directory is missing or\n * empty — callers write no zip at all for asset-less documents.\n */\nexport async function zipDir(dir: string, options?: ZipOptions): Promise<Uint8Array | undefined> {\n\tconst entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => [])\n\n\tconst files: Record<string, Uint8Array> = {}\n\n\tfor (const entry of entries) {\n\t\tif (!entry.isFile() || isSystemJunkFile(entry.name)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst absolute = join(entry.parentPath, entry.name)\n\t\tconst entryName = relative(dir, absolute).split('\\\\').join('/')\n\n\t\tfiles[entryName] = new Uint8Array(await readFile(absolute))\n\t}\n\n\tif (Object.keys(files).length === 0) {\n\t\treturn undefined\n\t}\n\n\t// Sort entries so output is independent of filesystem readdir order.\n\tconst ordered: Record<string, Uint8Array> = {}\n\tfor (const name of Object.keys(files).sort()) {\n\t\tordered[name] = files[name]\n\t}\n\n\treturn zipSync(ordered, { level: deflateLevel(options), mtime: ZIP_EPOCH })\n}\n","import type { AssetResolver } from './types'\n\n/**\n * Web-standard resolver that maps asset paths to URLs and fetches them. This is\n * the dynamic-mode runtime resolver: the compiled wrapper bakes in the\n * `{ relPath: url }` map and fetches only the bytes a given render references.\n * Returns `null` for unmapped paths. Portable — uses only `fetch`.\n */\nexport function urlResolver(urlMap: Record<string, string>): AssetResolver {\n\treturn async relPath => {\n\t\tconst url = urlMap[relPath]\n\n\t\tif (!url) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst res = await fetch(url)\n\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`Failed to fetch asset \"${relPath}\" from ${url}: HTTP ${res.status}`)\n\t\t}\n\n\t\treturn new Uint8Array(await res.arrayBuffer())\n\t}\n}\n","import { isLocalOrigin, resolveLocalRef, isRemoteOrigin } from './helpers'\n\n/** Raw url() targets and @import targets pulled from a CSS string, before any resolution. */\nexport interface CssRefs {\n\turls: string[]\n\timports: string[]\n}\n\n/** Raw asset references found directly in an HTML string, before resolution. */\nexport interface HtmlRefs {\n\timgSrcs: string[]\n\tsvgHrefs: string[]\n\tlinkHrefs: string[]\n\tinlineCss: string[]\n}\n\n/**\n * The parser pair `makeScanAssetRefs` is built on. `scanAssetRefs` binds the\n * dependency-free regex parsers (scan-lite) so the wrapper runtime check stays\n * lean; `zip()` collection binds the node-html-parser parsers (parse.ts). The\n * parity tests pin the two implementations to the same contract.\n */\nexport interface RefParsers {\n\tparseHtmlRefs(html: string): HtmlRefs\n\tparseCssRefs(cssText: string): CssRefs\n}\n\n/**\n * Build a `scanAssetRefs(html)` from a parser pair: every local asset reference\n * in the HTML itself, as bundle-root relative paths. Pure and IO-free — it\n * does not follow external stylesheets (that needs a resolver, in `zip()`).\n * Remote (http/https) references are ignored.\n */\nexport function makeScanAssetRefs(parsers: RefParsers): (html: string) => string[] {\n\treturn html => {\n\t\tconst { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html)\n\t\tconst refs = new Set<string>()\n\n\t\tconst addLocal = (ref: string) => {\n\t\t\tif (!isLocalOrigin(ref)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst local = resolveLocalRef(ref)\n\t\t\tif (local) {\n\t\t\t\trefs.add(local)\n\t\t\t}\n\t\t}\n\n\t\tfor (const src of imgSrcs) {\n\t\t\taddLocal(src)\n\t\t}\n\n\t\tfor (const href of svgHrefs) {\n\t\t\taddLocal(href)\n\t\t}\n\n\t\tfor (const href of linkHrefs) {\n\t\t\taddLocal(href)\n\t\t}\n\n\t\tfor (const cssText of inlineCss) {\n\t\t\tconst { urls, imports } = parsers.parseCssRefs(cssText)\n\n\t\t\tfor (const url of urls) {\n\t\t\t\taddLocal(url)\n\t\t\t}\n\n\t\t\tfor (const target of imports) {\n\t\t\t\taddLocal(target)\n\t\t\t}\n\t\t}\n\n\t\treturn [...refs]\n\t}\n}\n\n/**\n * Build a `scanRemoteRefs(html)` from a parser pair: every remote (http/https)\n * asset reference in the HTML itself. The mirror of `makeScanAssetRefs` for\n * remote URLs, so the lean (scan-lite) and parser-backed (parse.ts) scanners\n * stay in step. Pure and IO-free — it does not fetch anything.\n */\nexport function makeScanRemoteRefs(parsers: RefParsers): (html: string) => string[] {\n\treturn html => {\n\t\tconst { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html)\n\t\tconst refs = new Set<string>()\n\n\t\tconst addRemote = (ref: string) => {\n\t\t\tif (isRemoteOrigin(ref)) {\n\t\t\t\trefs.add(ref)\n\t\t\t}\n\t\t}\n\n\t\tfor (const src of imgSrcs) {\n\t\t\taddRemote(src)\n\t\t}\n\n\t\tfor (const href of svgHrefs) {\n\t\t\taddRemote(href)\n\t\t}\n\n\t\tfor (const href of linkHrefs) {\n\t\t\taddRemote(href)\n\t\t}\n\n\t\tfor (const cssText of inlineCss) {\n\t\t\tconst { urls, imports } = parsers.parseCssRefs(cssText)\n\n\t\t\tfor (const url of urls) {\n\t\t\t\taddRemote(url)\n\t\t\t}\n\n\t\t\tfor (const target of imports) {\n\t\t\t\taddRemote(target)\n\t\t\t}\n\t\t}\n\n\t\treturn [...refs].sort()\n\t}\n}\n","import type { HtmlRefs } from './scan-core'\n\nimport { makeScanAssetRefs, makeScanRemoteRefs } from './scan-core'\nimport { parseCssRefs } from './parse-css'\n\n// The lightweight scanner behind `scanAssetRefs` — the cheap known-asset check\n// the compiled wrapper runs at render time. Regex over well-formed,\n// quote-attributed HTML (what the Format engine renders), with no parser\n// dependency, so static-mode bundles that import only `scanAssetRefs` stay\n// lean. zip()'s heavier collection uses node-html-parser (see parse.ts); both\n// share one CSS tokenizer (parse-css) and are kept in step by the parity tests.\n\nconst IMG_SRC_RE = /<img\\b[^>]*?\\ssrc\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\nconst SVG_REF_TAG_RE = /<(?:image|use)\\b[^>]*?\\s(?:xlink:)?href\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\nconst LINK_TAG_RE = /<link\\b[^>]*>/gi\nconst HREF_RE = /\\shref\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/i\nconst REL_STYLESHEET_RE = /\\srel\\s*=\\s*(?:\"stylesheet\"|'stylesheet')/i\nconst STYLE_BLOCK_RE = /<style\\b[^>]*>([\\s\\S]*?)<\\/style>/gi\nconst STYLE_ATTR_RE = /\\sstyle\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\n\nconst ENTITIES: Record<string, string> = {\n\t'&': '&',\n\t'"': '\"',\n\t''': \"'\",\n\t'<': '<',\n\t'>': '>'\n}\n\n// Attribute values come out of the markup entity-encoded; node-html-parser\n// decodes them, so the regex scanner must match.\nfunction decodeEntities(value: string): string {\n\treturn value.replace(/&(?:amp|quot|#39|lt|gt);/g, entity => ENTITIES[entity] ?? entity)\n}\n\nfunction matchAll(input: string, pattern: RegExp): string[] {\n\tconst out: string[] = []\n\n\tfor (const match of input.matchAll(pattern)) {\n\t\tconst value = match[1] ?? match[2]\n\n\t\t// keep an empty value (src=\"\") — an empty ref is dropped downstream, not\n\t\t// here, so both parsers extract the same set (see parse.ts)\n\t\tif (value != null) {\n\t\t\tout.push(decodeEntities(value))\n\t\t}\n\t}\n\n\treturn out\n}\n\n/** Regex equivalent of parse.ts's `parseHtmlRefs`. Pure and IO-free. */\nfunction parseHtmlRefs(html: string): HtmlRefs {\n\tconst imgSrcs = matchAll(html, IMG_SRC_RE)\n\n\tconst svgHrefs = matchAll(html, SVG_REF_TAG_RE).filter(href => !href.startsWith('#'))\n\n\tconst linkHrefs: string[] = []\n\tfor (const tagMatch of html.matchAll(LINK_TAG_RE)) {\n\t\tconst tag = tagMatch[0]\n\n\t\tif (!REL_STYLESHEET_RE.test(tag)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst href = HREF_RE.exec(tag)\n\t\tconst value = href?.[1] ?? href?.[2]\n\n\t\t// keep an empty href=\"\" (reported downstream); skip only when there is no\n\t\t// href match at all\n\t\tif (value != null) {\n\t\t\tlinkHrefs.push(decodeEntities(value))\n\t\t}\n\t}\n\n\tconst styleBlocks = [...html.matchAll(STYLE_BLOCK_RE)].map(match => match[1] ?? '')\n\tconst styleAttrs = matchAll(html, STYLE_ATTR_RE)\n\n\treturn { imgSrcs, svgHrefs, linkHrefs, inlineCss: [...styleBlocks, ...styleAttrs] }\n}\n\n/**\n * Scan an HTML string for the local asset references it carries, returning each\n * as a bundle-root relative path. Dependency-free implementation for browser,\n * worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.\n */\nexport const scanAssetRefs = makeScanAssetRefs({ parseHtmlRefs, parseCssRefs })\n\n/**\n * Scan an HTML string for the remote (http/https) asset references it carries.\n * Dependency-free counterpart to scan-remote.ts's `scanRemoteRefs`, so the\n * static-mode wrapper can list remote refs without pulling in node-html-parser.\n */\nexport const scanRemoteRefs = makeScanRemoteRefs({ parseHtmlRefs, parseCssRefs })\n","import { parseCssRefs, parseHtmlRefs } from './parse'\nimport { makeScanRemoteRefs } from './scan-core'\n\n/**\n * Every remote (http/https) asset reference in an HTML string: `<img src>`,\n * inline-SVG `<image>`/`<use>` hrefs, `<link rel=stylesheet>` hrefs, and\n * `url()`/`@import` targets in `<style>` blocks and style attributes.\n *\n * Parser-backed (node-html-parser) counterpart to scan-lite's regex\n * `scanRemoteRefs`; both are built from `makeScanRemoteRefs`, so they stay in\n * step. Pure and IO-free — it does not fetch anything. PDF rendering never\n * fetches remote references, so anything this returns will be missing from the\n * output unless it's bundled (see `mergeRemoteAssets`) or removed.\n */\nexport const scanRemoteRefs = makeScanRemoteRefs({ parseHtmlRefs, parseCssRefs })\n","// Node entry (the package default): everything the web entry has, plus\n// filesystem support. `zip()` additionally accepts a directory string, so\n// `zip(html, dir)` reads assets from disk with no extra wiring.\n\nimport type { AssetResolver, ZipOptions } from './types'\n\nimport { zip as zipWithResolver } from './zip'\nimport { dirResolver } from './dir-resolver'\n\n/**\n * Build a ZIP of every asset `html` references.\n *\n * `source` is either a directory path (read from disk via {@link dirResolver})\n * or a custom {@link AssetResolver}. For browser, worker, and edge runtimes,\n * import from `@format.dev/zip/web` instead — that entry takes a resolver only and\n * carries no `node:*` dependencies.\n *\n * @param html - The rendered Format HTML to scan for asset references.\n * @param source - A directory path (Node) or an {@link AssetResolver} returning the bytes for each referenced path.\n * @param options - {@link ZipOptions}: remote-asset fetching, compression level, and missing-asset handling.\n * @returns the archive bytes, or `undefined` when `html` references no assets.\n */\nexport function zip(\n\thtml: string,\n\tsource: string | AssetResolver,\n\toptions?: ZipOptions\n): Promise<Uint8Array | undefined> {\n\tconst resolve = typeof source === 'string' ? dirResolver(source) : source\n\treturn zipWithResolver(html, resolve, options)\n}\n\nexport { listZipEntries, readRemoteAssets, mergeRemoteAssets } from './zip'\nexport { zipDir } from './zip-dir'\nexport { isSystemJunkFile } from './junk-files'\nexport { dirResolver } from './dir-resolver'\nexport { urlResolver } from './url-resolver'\nexport { fetchRemote, fetchRemoteIfChanged, findBrokenRemoteAssets } from './helpers'\nexport { scanAssetRefs } from './scan-lite'\nexport { scanRemoteRefs } from './scan-remote'\nexport {\n\tFormatZipError,\n\tMissingAssetError,\n\tUnresolvableRefError,\n\tInvalidExtensionError,\n\tAssetMismatchError,\n\tRemoteAssetFetchError,\n\tRemoteAssetsDisabledError\n} from './errors'\nexport type {\n\tAssetResolver,\n\tRemoteAsset,\n\tRemoteAssetFetcher,\n\tRemoteValidators,\n\tStoredRemoteAsset,\n\tZipOptions\n} from './types'\nexport type { AssetMismatchDetail, FormatZipErrorCode } from './errors'\n"],"mappings":";;;;;;;AAQA,MAAM,iBAAiB;AACvB,MAAM,aAAa;AACnB,MAAM,gBAAgB;AAEtB,SAASA,WAAS,OAAe,SAA2B;CAC3D,MAAMC,MAAgB,EAAE;AAExB,MAAK,MAAM,SAAS,MAAM,SAAS,QAAQ,EAAE;EAC5C,MAAM,QAAQ,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM;AAIpE,MAAI,SAAS,KACZ,KAAI,KAAK,MAAM,MAAM,CAAC;;AAIxB,QAAO;;;;;;;AAQR,SAAgB,aAAa,SAA0B;CACtD,MAAM,kBAAkB,QAAQ,QAAQ,gBAAgB,GAAG;CAC3D,MAAM,UAAUD,WAAS,iBAAiB,cAAc;AAUxD,QAAO;EAAE,MAFIA,WAJU,gBAAgB,QAAQ,eAAe,GAAG,EAI3B,WAAW,CAAC,QAAO,QAAO,CAAC,IAAI,WAAW,IAAI,CAAC;EAEtE;EAAS;;;;;;;;;AC7BzB,SAAgB,cAAc,MAAwB;CACrD,MAAM,OAAO,MAAM,KAAK;CAMxB,MAAM,UAAU,KACd,iBAAiB,WAAW,CAC5B,KAAI,YAAW,QAAQ,aAAa,MAAM,CAAC,CAC3C,QAAQ,QAA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CAAe;CAAc,CAAC;;;;;;AAO/E,MAAaC,mBAAiB,mBAAmB;CAAE;CAAe;CAAc,CAAC;;;;;;;;;;;;;;;AC9EjF,MAAa,iBAAiB,mBAAmB;CAAE;CAAe;CAAc,CAAC;;;;;;;;;;;;;;;;;ACQjF,SAAgB,IACf,MACA,QACA,SACkC;AAElC,QAAOC,MAAgB,MADP,OAAO,WAAW,WAAW,YAAY,OAAO,GAAG,QAC7B,QAAQ"}
|
package/dist/scan.d.mts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//#region src/scan-lite.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Scan an HTML string for the local asset references it carries, returning each
|
|
4
|
+
* as a bundle-root relative path. Dependency-free implementation for browser,
|
|
5
|
+
* worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.
|
|
6
|
+
*/
|
|
7
|
+
declare const scanAssetRefs: (html: string) => string[];
|
|
8
|
+
/**
|
|
9
|
+
* Scan an HTML string for the remote (http/https) asset references it carries.
|
|
10
|
+
* Dependency-free counterpart to scan-remote.ts's `scanRemoteRefs`, so the
|
|
11
|
+
* static-mode wrapper can list remote refs without pulling in node-html-parser.
|
|
12
|
+
*/
|
|
13
|
+
declare const scanRemoteRefs: (html: string) => string[];
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/errors.d.ts
|
|
16
|
+
/**
|
|
17
|
+
* Every error thrown by `@format.dev/zip` (and by compiled documents while building
|
|
18
|
+
* their assets zip) extends this class. The umbrella check lets callers branch
|
|
19
|
+
* once on "this is a zip-side failure", then narrow further by `code`.
|
|
20
|
+
*
|
|
21
|
+
* Mirrors `FormatError` from `@format.dev/client`: a single class to catch, a
|
|
22
|
+
* `code` field to dispatch on.
|
|
23
|
+
*/
|
|
24
|
+
type FormatZipErrorCode = 'MISSING_ASSET' | 'UNRESOLVABLE_REF' | 'ASSET_MISMATCH' | 'INVALID_EXTENSION' | 'REMOTE_ASSETS_DISABLED' | 'REMOTE_ASSET_FETCH';
|
|
25
|
+
declare class FormatZipError extends Error {
|
|
26
|
+
readonly code: FormatZipErrorCode;
|
|
27
|
+
constructor(code: FormatZipErrorCode, message: string, options?: ErrorOptions);
|
|
28
|
+
}
|
|
29
|
+
interface AssetMismatchDetail {
|
|
30
|
+
documentName: string;
|
|
31
|
+
mode: 'static' | 'dynamic';
|
|
32
|
+
missing: string[];
|
|
33
|
+
known: string[];
|
|
34
|
+
/**
|
|
35
|
+
* Remote (http/https) URLs the HTML references. The render-time check attaches
|
|
36
|
+
* these so a later step can find broken remotes even when local assets are
|
|
37
|
+
* already missing — they are referenced, not yet known to be unreachable.
|
|
38
|
+
*/
|
|
39
|
+
remoteRefs?: string[];
|
|
40
|
+
/** Remote URLs that could not be loaded, filled in once they have been probed. */
|
|
41
|
+
brokenRemote?: string[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Thrown by a compiled document wrapper when rendered HTML references assets
|
|
45
|
+
* the bundle cannot supply: local files not in its known-asset set, or remote
|
|
46
|
+
* URLs that could not be loaded. Carries enough context for the consumer to fix
|
|
47
|
+
* the source: add the file to the shared assets folder or the document's
|
|
48
|
+
* `./assets/` folder, switch asset mode, or make the remote URL reachable.
|
|
49
|
+
*/
|
|
50
|
+
declare class AssetMismatchError extends FormatZipError {
|
|
51
|
+
documentName: string;
|
|
52
|
+
mode: 'static' | 'dynamic';
|
|
53
|
+
missing: string[];
|
|
54
|
+
known: string[];
|
|
55
|
+
remoteRefs: string[];
|
|
56
|
+
brokenRemote: string[];
|
|
57
|
+
constructor(detail: AssetMismatchDetail);
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
export { type AssetMismatchDetail, AssetMismatchError, scanAssetRefs, scanRemoteRefs };
|
|
61
|
+
//# sourceMappingURL=scan.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scan.d.mts","names":[],"sources":["../src/scan-lite.ts","../src/errors.ts"],"sourcesContent":[],"mappings":";;AAqFA;AAOA;;;cAPa;AC7Eb;AAQA;;;;AAAoC,cD4EvB,cC5EuB,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,GAAA,MAAA,EAAA;;;;ADqEpC;AAOA;;;;ACpFA;AAQA;AAEwB,KAVZ,kBAAA,GAUY,eAAA,GAAA,kBAAA,GAAA,gBAAA,GAAA,mBAAA,GAAA,wBAAA,GAAA,oBAAA;AAAA,cAFX,cAAA,SAAuB,KAAA,CAEZ;EAEZ,SAAA,IAAA,EAFY,kBAEZ;EAJwB,WAAA,CAAA,IAAA,EAEZ,kBAFY,EAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EAIxB,YAJwB;;UA+BnB,mBAAA;;;;;;;;;;;;;;;;;;;;;cA6DJ,kBAAA,SAA2B,cAAA;;;;;;;sBAQnB"}
|
package/dist/scan.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
var FormatZipError = class extends Error {
|
|
3
|
+
constructor(code, message, options) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.code = code;
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
const toBullets = (items) => items.map((item) => `- ${item}`).join("\n");
|
|
9
|
+
function buildAssetMismatchMessage(detail) {
|
|
10
|
+
const { documentName, mode, missing, known, brokenRemote = [] } = detail;
|
|
11
|
+
const sections = [`Missing assets for document "${documentName}"`];
|
|
12
|
+
if (missing.length) sections.push(`Missing local assets:\n${toBullets(missing)}`);
|
|
13
|
+
if (brokenRemote.length) sections.push(`Unreachable remote assets:\n${toBullets(brokenRemote)}`);
|
|
14
|
+
if (known.length) sections.push(`Known assets:\n${toBullets(known)}`);
|
|
15
|
+
if (missing.length) {
|
|
16
|
+
const placement = "Add the missing files to your shared assets folder (`sharedAssetsDir`) or the document's `assets` folder";
|
|
17
|
+
sections.push(mode === "dynamic" ? `${placement}.` : `${placement}, or consider using dynamic assets. Check the CLI options for \`--assets\`.`);
|
|
18
|
+
}
|
|
19
|
+
if (brokenRemote.length) sections.push("Make sure the remote assets are reachable when the document is built.");
|
|
20
|
+
return sections.join("\n\n");
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Thrown by a compiled document wrapper when rendered HTML references assets
|
|
24
|
+
* the bundle cannot supply: local files not in its known-asset set, or remote
|
|
25
|
+
* URLs that could not be loaded. Carries enough context for the consumer to fix
|
|
26
|
+
* the source: add the file to the shared assets folder or the document's
|
|
27
|
+
* `./assets/` folder, switch asset mode, or make the remote URL reachable.
|
|
28
|
+
*/
|
|
29
|
+
var AssetMismatchError = class extends FormatZipError {
|
|
30
|
+
documentName;
|
|
31
|
+
mode;
|
|
32
|
+
missing;
|
|
33
|
+
known;
|
|
34
|
+
remoteRefs;
|
|
35
|
+
brokenRemote;
|
|
36
|
+
constructor(detail) {
|
|
37
|
+
super("ASSET_MISMATCH", buildAssetMismatchMessage(detail));
|
|
38
|
+
this.name = "AssetMismatchError";
|
|
39
|
+
this.documentName = detail.documentName;
|
|
40
|
+
this.mode = detail.mode;
|
|
41
|
+
this.missing = detail.missing;
|
|
42
|
+
this.known = detail.known;
|
|
43
|
+
this.remoteRefs = detail.remoteRefs ?? [];
|
|
44
|
+
this.brokenRemote = detail.brokenRemote ?? [];
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/path-utils.ts
|
|
50
|
+
/** Collapse '.', '..', and duplicate slashes, mirroring `path.posix.normalize`. */
|
|
51
|
+
function normalizePath(input) {
|
|
52
|
+
const isAbsolute = input.startsWith("/");
|
|
53
|
+
const out = [];
|
|
54
|
+
for (const segment of input.split("/")) {
|
|
55
|
+
if (segment === "" || segment === ".") continue;
|
|
56
|
+
if (segment === "..") {
|
|
57
|
+
if (out.length > 0 && out[out.length - 1] !== "..") out.pop();
|
|
58
|
+
else if (!isAbsolute) out.push("..");
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
out.push(segment);
|
|
62
|
+
}
|
|
63
|
+
const joined = out.join("/");
|
|
64
|
+
if (isAbsolute) return "/" + joined;
|
|
65
|
+
return joined || ".";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/helpers.ts
|
|
70
|
+
function isRemoteOrigin(href) {
|
|
71
|
+
try {
|
|
72
|
+
const url = new URL(href);
|
|
73
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
74
|
+
} catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function isSameOrigin(href, base) {
|
|
79
|
+
try {
|
|
80
|
+
return new URL(href, base).origin === base;
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function randomLocalOrigin() {
|
|
86
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
87
|
+
if (uuid) return `https://${uuid}`;
|
|
88
|
+
return `https://local-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;
|
|
89
|
+
}
|
|
90
|
+
const LOCAL_ORIGIN_BASE = randomLocalOrigin();
|
|
91
|
+
const isLocalOrigin = (href) => isSameOrigin(href, LOCAL_ORIGIN_BASE);
|
|
92
|
+
/**
|
|
93
|
+
* Resolve a local href to a safe, POSIX-style relative path for a zip entry.
|
|
94
|
+
* - Strips query/hash
|
|
95
|
+
* - Resolves dot-segments relative to baseRel
|
|
96
|
+
* - Drops leading slashes
|
|
97
|
+
* - Normalizes duplicate slashes
|
|
98
|
+
*
|
|
99
|
+
* Returns `null` for a ref that names no file to bundle: a bare fragment
|
|
100
|
+
* (`#gradient`), a `data:` URL, or anything that resolves to the bundle root
|
|
101
|
+
* itself. This is a pure path helper — what a null means (skip a fragment, or
|
|
102
|
+
* report a broken `src`/`href`/`url()`) is the caller's policy, not this
|
|
103
|
+
* function's.
|
|
104
|
+
*/
|
|
105
|
+
function resolveLocalRef(href, baseRel = ".") {
|
|
106
|
+
if (href.startsWith("#") || href.startsWith("data:")) return null;
|
|
107
|
+
const base = new URL("/" + normalizePath(baseRel), LOCAL_ORIGIN_BASE);
|
|
108
|
+
let pathname = new URL(href, base).pathname.replace(/^\/+/, "");
|
|
109
|
+
pathname = normalizePath(pathname);
|
|
110
|
+
if (pathname === ".") return null;
|
|
111
|
+
return pathname;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
//#endregion
|
|
115
|
+
//#region src/scan-core.ts
|
|
116
|
+
/**
|
|
117
|
+
* Build a `scanAssetRefs(html)` from a parser pair: every local asset reference
|
|
118
|
+
* in the HTML itself, as bundle-root relative paths. Pure and IO-free — it
|
|
119
|
+
* does not follow external stylesheets (that needs a resolver, in `zip()`).
|
|
120
|
+
* Remote (http/https) references are ignored.
|
|
121
|
+
*/
|
|
122
|
+
function makeScanAssetRefs(parsers) {
|
|
123
|
+
return (html) => {
|
|
124
|
+
const { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html);
|
|
125
|
+
const refs = /* @__PURE__ */ new Set();
|
|
126
|
+
const addLocal = (ref) => {
|
|
127
|
+
if (!isLocalOrigin(ref)) return;
|
|
128
|
+
const local = resolveLocalRef(ref);
|
|
129
|
+
if (local) refs.add(local);
|
|
130
|
+
};
|
|
131
|
+
for (const src of imgSrcs) addLocal(src);
|
|
132
|
+
for (const href of svgHrefs) addLocal(href);
|
|
133
|
+
for (const href of linkHrefs) addLocal(href);
|
|
134
|
+
for (const cssText of inlineCss) {
|
|
135
|
+
const { urls, imports } = parsers.parseCssRefs(cssText);
|
|
136
|
+
for (const url of urls) addLocal(url);
|
|
137
|
+
for (const target of imports) addLocal(target);
|
|
138
|
+
}
|
|
139
|
+
return [...refs];
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Build a `scanRemoteRefs(html)` from a parser pair: every remote (http/https)
|
|
144
|
+
* asset reference in the HTML itself. The mirror of `makeScanAssetRefs` for
|
|
145
|
+
* remote URLs, so the lean (scan-lite) and parser-backed (parse.ts) scanners
|
|
146
|
+
* stay in step. Pure and IO-free — it does not fetch anything.
|
|
147
|
+
*/
|
|
148
|
+
function makeScanRemoteRefs(parsers) {
|
|
149
|
+
return (html) => {
|
|
150
|
+
const { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html);
|
|
151
|
+
const refs = /* @__PURE__ */ new Set();
|
|
152
|
+
const addRemote = (ref) => {
|
|
153
|
+
if (isRemoteOrigin(ref)) refs.add(ref);
|
|
154
|
+
};
|
|
155
|
+
for (const src of imgSrcs) addRemote(src);
|
|
156
|
+
for (const href of svgHrefs) addRemote(href);
|
|
157
|
+
for (const href of linkHrefs) addRemote(href);
|
|
158
|
+
for (const cssText of inlineCss) {
|
|
159
|
+
const { urls, imports } = parsers.parseCssRefs(cssText);
|
|
160
|
+
for (const url of urls) addRemote(url);
|
|
161
|
+
for (const target of imports) addRemote(target);
|
|
162
|
+
}
|
|
163
|
+
return [...refs].sort();
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/parse-css.ts
|
|
169
|
+
const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
|
|
170
|
+
const CSS_URL_RE = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s][^)]*?))\s*\)/gi;
|
|
171
|
+
const CSS_IMPORT_RE = /@import\s+(?:url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"]+?))\s*\)|"([^"]*)"|'([^']*)')/gi;
|
|
172
|
+
function matchAll$1(input, pattern) {
|
|
173
|
+
const out = [];
|
|
174
|
+
for (const match of input.matchAll(pattern)) {
|
|
175
|
+
const value = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5];
|
|
176
|
+
if (value != null) out.push(value.trim());
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Pull every `url(...)` target and every `@import` target out of a CSS string.
|
|
182
|
+
* Comments are stripped first so a commented-out reference is never collected.
|
|
183
|
+
* Pure and IO-free.
|
|
184
|
+
*/
|
|
185
|
+
function parseCssRefs(cssText) {
|
|
186
|
+
const withoutComments = cssText.replace(CSS_COMMENT_RE, "");
|
|
187
|
+
const imports = matchAll$1(withoutComments, CSS_IMPORT_RE);
|
|
188
|
+
return {
|
|
189
|
+
urls: matchAll$1(withoutComments.replace(CSS_IMPORT_RE, ""), CSS_URL_RE).filter((ref) => !ref.startsWith("#")),
|
|
190
|
+
imports
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/scan-lite.ts
|
|
196
|
+
const IMG_SRC_RE = /<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
197
|
+
const SVG_REF_TAG_RE = /<(?:image|use)\b[^>]*?\s(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
198
|
+
const LINK_TAG_RE = /<link\b[^>]*>/gi;
|
|
199
|
+
const HREF_RE = /\shref\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
|
|
200
|
+
const REL_STYLESHEET_RE = /\srel\s*=\s*(?:"stylesheet"|'stylesheet')/i;
|
|
201
|
+
const STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
|
|
202
|
+
const STYLE_ATTR_RE = /\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
203
|
+
const ENTITIES = {
|
|
204
|
+
"&": "&",
|
|
205
|
+
""": "\"",
|
|
206
|
+
"'": "'",
|
|
207
|
+
"<": "<",
|
|
208
|
+
">": ">"
|
|
209
|
+
};
|
|
210
|
+
function decodeEntities(value) {
|
|
211
|
+
return value.replace(/&(?:amp|quot|#39|lt|gt);/g, (entity) => ENTITIES[entity] ?? entity);
|
|
212
|
+
}
|
|
213
|
+
function matchAll(input, pattern) {
|
|
214
|
+
const out = [];
|
|
215
|
+
for (const match of input.matchAll(pattern)) {
|
|
216
|
+
const value = match[1] ?? match[2];
|
|
217
|
+
if (value != null) out.push(decodeEntities(value));
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
/** Regex equivalent of parse.ts's `parseHtmlRefs`. Pure and IO-free. */
|
|
222
|
+
function parseHtmlRefs(html) {
|
|
223
|
+
const imgSrcs = matchAll(html, IMG_SRC_RE);
|
|
224
|
+
const svgHrefs = matchAll(html, SVG_REF_TAG_RE).filter((href) => !href.startsWith("#"));
|
|
225
|
+
const linkHrefs = [];
|
|
226
|
+
for (const tagMatch of html.matchAll(LINK_TAG_RE)) {
|
|
227
|
+
const tag = tagMatch[0];
|
|
228
|
+
if (!REL_STYLESHEET_RE.test(tag)) continue;
|
|
229
|
+
const href = HREF_RE.exec(tag);
|
|
230
|
+
const value = href?.[1] ?? href?.[2];
|
|
231
|
+
if (value != null) linkHrefs.push(decodeEntities(value));
|
|
232
|
+
}
|
|
233
|
+
const styleBlocks = [...html.matchAll(STYLE_BLOCK_RE)].map((match) => match[1] ?? "");
|
|
234
|
+
const styleAttrs = matchAll(html, STYLE_ATTR_RE);
|
|
235
|
+
return {
|
|
236
|
+
imgSrcs,
|
|
237
|
+
svgHrefs,
|
|
238
|
+
linkHrefs,
|
|
239
|
+
inlineCss: [...styleBlocks, ...styleAttrs]
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Scan an HTML string for the local asset references it carries, returning each
|
|
244
|
+
* as a bundle-root relative path. Dependency-free implementation for browser,
|
|
245
|
+
* worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.
|
|
246
|
+
*/
|
|
247
|
+
const scanAssetRefs = makeScanAssetRefs({
|
|
248
|
+
parseHtmlRefs,
|
|
249
|
+
parseCssRefs
|
|
250
|
+
});
|
|
251
|
+
/**
|
|
252
|
+
* Scan an HTML string for the remote (http/https) asset references it carries.
|
|
253
|
+
* Dependency-free counterpart to scan-remote.ts's `scanRemoteRefs`, so the
|
|
254
|
+
* static-mode wrapper can list remote refs without pulling in node-html-parser.
|
|
255
|
+
*/
|
|
256
|
+
const scanRemoteRefs = makeScanRemoteRefs({
|
|
257
|
+
parseHtmlRefs,
|
|
258
|
+
parseCssRefs
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
//#endregion
|
|
262
|
+
export { AssetMismatchError, scanAssetRefs, scanRemoteRefs };
|
|
263
|
+
//# sourceMappingURL=scan.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scan.mjs","names":["code: FormatZipErrorCode","out: string[]","matchAll","out: string[]","ENTITIES: Record<string, string>","out: string[]","linkHrefs: string[]"],"sources":["../src/errors.ts","../src/path-utils.ts","../src/helpers.ts","../src/scan-core.ts","../src/parse-css.ts","../src/scan-lite.ts"],"sourcesContent":["/**\n * Every error thrown by `@format.dev/zip` (and by compiled documents while building\n * their assets zip) extends this class. The umbrella check lets callers branch\n * once on \"this is a zip-side failure\", then narrow further by `code`.\n *\n * Mirrors `FormatError` from `@format.dev/client`: a single class to catch, a\n * `code` field to dispatch on.\n */\nexport type FormatZipErrorCode =\n\t| 'MISSING_ASSET'\n\t| 'UNRESOLVABLE_REF'\n\t| 'ASSET_MISMATCH'\n\t| 'INVALID_EXTENSION'\n\t| 'REMOTE_ASSETS_DISABLED'\n\t| 'REMOTE_ASSET_FETCH'\n\nexport class FormatZipError extends Error {\n\tconstructor(\n\t\tpublic readonly code: FormatZipErrorCode,\n\t\tmessage: string,\n\t\toptions?: ErrorOptions\n\t) {\n\t\tsuper(message, options)\n\t}\n}\n\nexport class MissingAssetError extends FormatZipError {\n\tconstructor(public relPath: string) {\n\t\tsuper('MISSING_ASSET', `Asset not found: ${relPath}`)\n\t}\n}\n\n/**\n * Thrown by `zip()` when the HTML references a local asset that resolves to no\n * file: an empty `src`/`href`/`url(\"\")`, or one like `/`, `.`, or `..` that\n * points at the bundle root (a directory) rather than a file. A same-document\n * fragment (`url(#gradient)`) is not this: it names an element already in the\n * document and is skipped silently. Reported with a warning instead of thrown\n * when `skipMissing` is set.\n */\nexport class UnresolvableRefError extends FormatZipError {\n\tconstructor(public ref: string) {\n\t\tconst reason = ref.trim() === '' ? 'it is empty' : 'it resolves to the bundle root, not a file'\n\t\tsuper('UNRESOLVABLE_REF', `Unresolvable asset reference ${JSON.stringify(ref)}: ${reason}`)\n\t}\n}\n\nexport interface AssetMismatchDetail {\n\tdocumentName: string\n\tmode: 'static' | 'dynamic'\n\tmissing: string[]\n\tknown: string[]\n\t/**\n\t * Remote (http/https) URLs the HTML references. The render-time check attaches\n\t * these so a later step can find broken remotes even when local assets are\n\t * already missing — they are referenced, not yet known to be unreachable.\n\t */\n\tremoteRefs?: string[]\n\t/** Remote URLs that could not be loaded, filled in once they have been probed. */\n\tbrokenRemote?: string[]\n}\n\nconst toBullets = (items: string[]) => items.map(item => `- ${item}`).join('\\n')\n\nfunction buildAssetMismatchMessage(detail: AssetMismatchDetail): string {\n\tconst { documentName, mode, missing, known, brokenRemote = [] } = detail\n\n\tconst sections = [`Missing assets for document \"${documentName}\"`]\n\n\tif (missing.length) {\n\t\tsections.push(`Missing local assets:\\n${toBullets(missing)}`)\n\t}\n\n\tif (brokenRemote.length) {\n\t\tsections.push(`Unreachable remote assets:\\n${toBullets(brokenRemote)}`)\n\t}\n\n\tif (known.length) {\n\t\tsections.push(`Known assets:\\n${toBullets(known)}`)\n\t}\n\n\tif (missing.length) {\n\t\t// In dynamic mode the asset is genuinely absent, so the static-only escape\n\t\t// hatch (switching to dynamic) does not apply — only suggest it for static.\n\t\tconst placement =\n\t\t\t\"Add the missing files to your shared assets folder (`sharedAssetsDir`) or the document's `assets` folder\"\n\n\t\tsections.push(\n\t\t\tmode === 'dynamic'\n\t\t\t\t? `${placement}.`\n\t\t\t\t: `${placement}, or consider using dynamic assets. Check the CLI options for \\`--assets\\`.`\n\t\t)\n\t}\n\n\tif (brokenRemote.length) {\n\t\tsections.push('Make sure the remote assets are reachable when the document is built.')\n\t}\n\n\treturn sections.join('\\n\\n')\n}\n\n/**\n * Thrown by a compiled document wrapper when rendered HTML references assets\n * the bundle cannot supply: local files not in its known-asset set, or remote\n * URLs that could not be loaded. Carries enough context for the consumer to fix\n * the source: add the file to the shared assets folder or the document's\n * `./assets/` folder, switch asset mode, or make the remote URL reachable.\n */\nexport class AssetMismatchError extends FormatZipError {\n\tpublic documentName: string\n\tpublic mode: 'static' | 'dynamic'\n\tpublic missing: string[]\n\tpublic known: string[]\n\tpublic remoteRefs: string[]\n\tpublic brokenRemote: string[]\n\n\tconstructor(detail: AssetMismatchDetail) {\n\t\tsuper('ASSET_MISMATCH', buildAssetMismatchMessage(detail))\n\n\t\tthis.name = 'AssetMismatchError'\n\t\tthis.documentName = detail.documentName\n\t\tthis.mode = detail.mode\n\t\tthis.missing = detail.missing\n\t\tthis.known = detail.known\n\t\tthis.remoteRefs = detail.remoteRefs ?? []\n\t\tthis.brokenRemote = detail.brokenRemote ?? []\n\t}\n}\n\nexport class InvalidExtensionError extends FormatZipError {\n\tconstructor(\n\t\tpublic url: string,\n\t\tpublic mimeType?: string\n\t) {\n\t\tsuper('INVALID_EXTENSION', `Cannot infer asset extension from URL and MIME type: ${url} (${mimeType})`)\n\t}\n}\n\n/**\n * Thrown by `zip()` when the HTML references remote (http/https) assets and\n * `remoteAssets` is not enabled. PDF generation never fetches remote\n * references at render time, so a zip built without them produces a broken\n * PDF — failing loudly here makes the gap visible at the source.\n */\nexport class RemoteAssetsDisabledError extends FormatZipError {\n\tconstructor(public urls: string[]) {\n\t\tsuper(\n\t\t\t'REMOTE_ASSETS_DISABLED',\n\t\t\t`Cannot fetch remote assets.\\n\\n` +\n\t\t\t\t`Your HTML references the following remote assets:\\n${toBullets(urls)}\\n\\n` +\n\t\t\t\t`Use \\`remoteAssets.enabled\\` to fetch assets, or use local assets (recommended).`\n\t\t)\n\t}\n}\n\n/**\n * Thrown when a remote asset cannot be fetched because the network itself\n * failed (offline machine, DNS failure, blocked egress, timeout) — as opposed\n * to the server answering with an error status. The message is written for the\n * common trap: a CI runner with no outbound network access.\n */\nexport class RemoteAssetFetchError extends FormatZipError {\n\tconstructor(\n\t\tpublic url: string,\n\t\tcause?: unknown\n\t) {\n\t\tsuper(\n\t\t\t'REMOTE_ASSET_FETCH',\n\t\t\t`Could not fetch remote asset \"${url}\". The machine running this build needs network access to that host`,\n\t\t\t{ cause }\n\t\t)\n\t}\n}\n","// Minimal POSIX-style path helpers, dependency-free and runtime-portable.\n// `node:path` is unavailable in browsers and workers, so the shared zip core\n// can't reach for it. These cover only what the pipeline needs: normalize,\n// parse, and join, all operating on '/'-separated paths.\n\n/** Collapse '.', '..', and duplicate slashes, mirroring `path.posix.normalize`. */\nexport function normalizePath(input: string): string {\n\tconst isAbsolute = input.startsWith('/')\n\tconst out: string[] = []\n\n\tfor (const segment of input.split('/')) {\n\t\tif (segment === '' || segment === '.') {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (segment === '..') {\n\t\t\tconst canPop = out.length > 0 && out[out.length - 1] !== '..'\n\n\t\t\tif (canPop) {\n\t\t\t\tout.pop()\n\t\t\t} else if (!isAbsolute) {\n\t\t\t\tout.push('..')\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tout.push(segment)\n\t}\n\n\tconst joined = out.join('/')\n\n\tif (isAbsolute) {\n\t\treturn '/' + joined\n\t}\n\n\treturn joined || '.'\n}\n\n/** Split a path into dir/name/ext, mirroring `path.posix.parse`. */\nexport function parsePath(input: string): { dir: string; name: string; ext: string } {\n\tconst lastSlash = input.lastIndexOf('/')\n\tconst dir = lastSlash >= 0 ? input.slice(0, lastSlash) : ''\n\tconst base = lastSlash >= 0 ? input.slice(lastSlash + 1) : input\n\n\tconst lastDot = base.lastIndexOf('.')\n\n\t// A leading dot is part of the name (e.g. '.env'), so ignore dot at index 0.\n\tif (lastDot <= 0) {\n\t\treturn { dir, name: base, ext: '' }\n\t}\n\n\treturn { dir, name: base.slice(0, lastDot), ext: base.slice(lastDot) }\n}\n\n/** Join and normalize '/'-separated segments, mirroring `path.posix.join`. */\nexport function joinPath(...segments: string[]): string {\n\treturn normalizePath(segments.filter(Boolean).join('/'))\n}\n\n/**\n * Small, fast, non-cryptographic hash (FNV-1a, 32-bit) rendered as 8 hex chars.\n * Used only to give a remote asset's query string a stable, collision-resistant\n * filename suffix — it is not security-sensitive.\n */\nexport function hash8(input: string): string {\n\tlet hash = 0x811c9dc5\n\n\tfor (let index = 0; index < input.length; index++) {\n\t\thash ^= input.charCodeAt(index)\n\t\thash = Math.imul(hash, 0x01000193)\n\t}\n\n\treturn (hash >>> 0).toString(16).padStart(8, '0')\n}\n","import type { RemoteAsset, RemoteAssetFetcher, RemoteValidators, RequestHeaders, ZipOptions } from './types'\n\nimport { MIME_TO_EXT } from '@format.dev/utils'\nimport { InvalidExtensionError, RemoteAssetFetchError } from './errors'\nimport { USER_AGENT } from './constants'\nimport { normalizePath, parsePath, joinPath, hash8 } from './path-utils'\n\ninterface RemoteRequestParams {\n\turl: string\n\theaders?: RequestHeaders\n\ttimeoutMs?: number\n}\n\ninterface ConditionalRemoteRequestParams extends RemoteRequestParams {\n\tvalidators: RemoteValidators\n}\n\n/**\n * Fetch a remote asset and return its bytes, parsed MIME type, and the\n * validators the server sent, so a caller holding the bytes can later ask\n * whether they changed with {@link fetchRemoteIfChanged}.\n *\n * Uses `fetch` + `arrayBuffer()` rather than a Node stream so the remote path\n * stays portable across Node, workers, and browsers.\n *\n * @throws {RemoteAssetFetchError} when the network itself fails (offline, DNS,\n * blocked egress, timeout). HTTP error statuses throw a plain Error — the\n * server was reachable, so it's a different problem.\n */\nexport async function fetchRemote(params: RemoteRequestParams): Promise<RemoteAsset> {\n\tconst response = await requestRemote(params)\n\n\treturn readRemoteResponse(response, params.url)\n}\n\n/**\n * Ask the server whether a remote asset changed since `validators` were\n * issued. Returns `null` on `304 Not Modified`, otherwise the full asset. A\n * server that sent no validators gets an ordinary request, so this always\n * downloads there.\n *\n * @throws {RemoteAssetFetchError} and plain HTTP errors, as {@link fetchRemote}.\n */\nexport async function fetchRemoteIfChanged(params: ConditionalRemoteRequestParams): Promise<RemoteAsset | null> {\n\tconst { validators } = params\n\n\tconst headers = new Headers(params.headers)\n\n\tif (validators.etag) {\n\t\theaders.set('If-None-Match', validators.etag)\n\t}\n\n\tif (validators.lastModified) {\n\t\theaders.set('If-Modified-Since', validators.lastModified)\n\t}\n\n\tconst response = await requestRemote({ ...params, headers })\n\n\tif (response.status === 304) {\n\t\treturn null\n\t}\n\n\treturn readRemoteResponse(response, params.url)\n}\n\nasync function requestRemote(params: RemoteRequestParams): Promise<Response> {\n\tconst { url, headers: requestHeaders, timeoutMs = 15_000 } = params\n\n\tconst signal = AbortSignal.timeout(timeoutMs)\n\tconst headers = new Headers(requestHeaders)\n\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', USER_AGENT)\n\t}\n\n\ttry {\n\t\treturn await fetch(url, { signal, redirect: 'follow', headers })\n\t} catch (cause) {\n\t\tthrow new RemoteAssetFetchError(url, cause)\n\t}\n}\n\nasync function readRemoteResponse(response: Response, url: string): Promise<RemoteAsset> {\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP ${response.status} for ${url}`)\n\t}\n\n\tconst bytes = new Uint8Array(await response.arrayBuffer())\n\tconst mimeType = parseContentType(response.headers.get('content-type') || undefined)\n\n\tconst etag = response.headers.get('etag') ?? undefined\n\tconst lastModified = response.headers.get('last-modified') ?? undefined\n\n\treturn { bytes, mimeType, validators: { etag, lastModified } }\n}\n\n/**\n * The fetcher every remote read in this package goes through: the caller's\n * `remoteAssets.fetch` when they supplied one, otherwise {@link fetchRemote}.\n * Binds the headers and timeout from the same options so a custom fetcher gets\n * the same request shape the built-in one would have used.\n */\nexport function remoteFetcher(options?: ZipOptions): (url: string) => ReturnType<RemoteAssetFetcher> {\n\tconst fetcher = options?.remoteAssets?.fetch ?? fetchRemote\n\n\treturn url =>\n\t\tfetcher({\n\t\t\turl,\n\t\t\theaders: options?.remoteAssets?.headers,\n\t\t\ttimeoutMs: options?.remoteAssets?.timeoutMs\n\t\t})\n}\n\n/**\n * Probe each remote URL and return the ones that can't be loaded — a failed\n * request or a non-OK status, the same \"broken\" definition `fetchRemote` uses.\n * Collects every failure rather than stopping at the first, so callers can report\n * the full set. Runs the probes concurrently.\n */\nexport async function findBrokenRemoteAssets(params: {\n\turls: string[]\n\theaders?: RequestHeaders\n\ttimeoutMs?: number\n\tfetch?: RemoteAssetFetcher\n}): Promise<string[]> {\n\tconst { urls, headers, timeoutMs, fetch: customFetch } = params\n\n\tconst probe = customFetch ?? fetchRemote\n\n\tconst results = await Promise.all(\n\t\turls.map(async url => {\n\t\t\ttry {\n\t\t\t\tawait probe({ url, headers, timeoutMs })\n\t\t\t\treturn null\n\t\t\t} catch {\n\t\t\t\treturn url\n\t\t\t}\n\t\t})\n\t)\n\n\treturn results.filter((url): url is string => url !== null)\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header?: string): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\n// note: for simplicity, we are ignoring protocol-relative URLs\nexport function isRemoteOrigin(href: string) {\n\ttry {\n\t\tconst url = new URL(href)\n\t\treturn url.protocol === 'http:' || url.protocol === 'https:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function isSameOrigin(href: string, base: string) {\n\ttry {\n\t\tconst url = new URL(href, base)\n\t\treturn url.origin === base\n\t} catch {\n\t\t// invalid url syntax\n\t\treturn false\n\t}\n}\n\n// A random, unguessable origin used to detect local (relative) references:\n// anything that resolves against it is local. `crypto.randomUUID` is a\n// web-standard global (browsers, workers, Node 18+); the fallback covers the\n// rare runtime without it. This is not security-sensitive.\nfunction randomLocalOrigin(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.()\n\n\tif (uuid) {\n\t\treturn `https://${uuid}`\n\t}\n\n\treturn `https://local-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`\n}\n\nconst LOCAL_ORIGIN_BASE = randomLocalOrigin()\nexport const isLocalOrigin = (href: string) => isSameOrigin(href, LOCAL_ORIGIN_BASE)\n\n// turn something like \"/a/../b///./c\" into \"b/c\" safely\nexport function normalizeDir(rawDir: string): string {\n\t// force an absolute base so \"..\" can't climb above root\n\t// and normalize to collapse \".\", \"..\", and duplicate slashes\n\tconst abs = normalizePath('/' + rawDir.replace(/^\\/+/, ''))\n\t// drop the leading \"/\" to make it relative again for zip entry joining\n\treturn abs === '/' ? '' : abs.slice(1)\n}\n\n// a deterministic, safe zip entry path for a remote URL\nexport function urlToZipName(url: string, mimeType?: string): string {\n\tconst u = new URL(url)\n\n\tif (u.protocol !== 'http:' && u.protocol !== 'https:') {\n\t\tthrow new Error(`Unsupported protocol: ${u.protocol}`)\n\t}\n\n\t// ensure a filename even for trailing slashes\n\tlet pathname = u.pathname\n\tif (pathname.endsWith('/')) {\n\t\tpathname += 'index'\n\t}\n\n\tlet { dir, name, ext } = parsePath(pathname)\n\n\tif (!ext && mimeType) {\n\t\text = MIME_TO_EXT[mimeType.toLowerCase()]\n\t}\n\n\tif (!ext) {\n\t\tthrow new InvalidExtensionError(url, mimeType)\n\t}\n\n\t// order-insensitive stable query hash\n\tconst qs = [...u.searchParams.entries()]\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([key, value]) => `${key}=${value}`)\n\t\t.join('&')\n\tconst queryHash = qs ? `__${hash8(qs)}` : ''\n\n\t// sanitize filename segment (replace any character that is not a word char, a dot, or a hyphen)\n\tconst hostname = u.hostname.toLowerCase()\n\tconst port = `_${u.port || (u.protocol === 'https:' ? '443' : '80')}`\n\tconst safeDir = normalizeDir(dir)\n\tconst safeName = `${name.replace(/[^\\w.-]/g, '_')}${queryHash}${ext}`\n\n\treturn joinPath('remote', `${hostname}${port}`, safeDir, safeName)\n}\n\nexport function resolveLocalUrl(href: string) {\n\tconst url = new URL(href, LOCAL_ORIGIN_BASE)\n\treturn url.pathname.replace('/', '')\n}\n\n/**\n * Resolve a local href to a safe, POSIX-style relative path for a zip entry.\n * - Strips query/hash\n * - Resolves dot-segments relative to baseRel\n * - Drops leading slashes\n * - Normalizes duplicate slashes\n *\n * Returns `null` for a ref that names no file to bundle: a bare fragment\n * (`#gradient`), a `data:` URL, or anything that resolves to the bundle root\n * itself. This is a pure path helper — what a null means (skip a fragment, or\n * report a broken `src`/`href`/`url()`) is the caller's policy, not this\n * function's.\n */\nexport function resolveLocalRef(href: string, baseRel = '.'): string | null {\n\t// a fragment points at an element already in the document, and a data: URL\n\t// carries its bytes inline — neither is a file on disk\n\tif (href.startsWith('#') || href.startsWith('data:')) {\n\t\treturn null\n\t}\n\n\t// build a base URL whose pathname reflects the referring file's location\n\t// e.g. baseRel = \"css/app/main.css\" -> base pathname \"/css/app/main.css\"\n\tconst base = new URL('/' + normalizePath(baseRel), LOCAL_ORIGIN_BASE)\n\tconst url = new URL(href, base)\n\n\t// get normalized pathname and make it relative (no leading slash)\n\tlet pathname = url.pathname.replace(/^\\/+/, '') // drop all leading slashes\n\tpathname = normalizePath(pathname) // collapse duplicate slashes, \".\", etc\n\n\t// normalizePath returns \".\" for an empty path, i.e. the ref resolved to the\n\t// bundle root — a directory, never a file to bundle\n\tif (pathname === '.') {\n\t\treturn null\n\t}\n\n\treturn pathname\n}\n","import { isLocalOrigin, resolveLocalRef, isRemoteOrigin } from './helpers'\n\n/** Raw url() targets and @import targets pulled from a CSS string, before any resolution. */\nexport interface CssRefs {\n\turls: string[]\n\timports: string[]\n}\n\n/** Raw asset references found directly in an HTML string, before resolution. */\nexport interface HtmlRefs {\n\timgSrcs: string[]\n\tsvgHrefs: string[]\n\tlinkHrefs: string[]\n\tinlineCss: string[]\n}\n\n/**\n * The parser pair `makeScanAssetRefs` is built on. `scanAssetRefs` binds the\n * dependency-free regex parsers (scan-lite) so the wrapper runtime check stays\n * lean; `zip()` collection binds the node-html-parser parsers (parse.ts). The\n * parity tests pin the two implementations to the same contract.\n */\nexport interface RefParsers {\n\tparseHtmlRefs(html: string): HtmlRefs\n\tparseCssRefs(cssText: string): CssRefs\n}\n\n/**\n * Build a `scanAssetRefs(html)` from a parser pair: every local asset reference\n * in the HTML itself, as bundle-root relative paths. Pure and IO-free — it\n * does not follow external stylesheets (that needs a resolver, in `zip()`).\n * Remote (http/https) references are ignored.\n */\nexport function makeScanAssetRefs(parsers: RefParsers): (html: string) => string[] {\n\treturn html => {\n\t\tconst { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html)\n\t\tconst refs = new Set<string>()\n\n\t\tconst addLocal = (ref: string) => {\n\t\t\tif (!isLocalOrigin(ref)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst local = resolveLocalRef(ref)\n\t\t\tif (local) {\n\t\t\t\trefs.add(local)\n\t\t\t}\n\t\t}\n\n\t\tfor (const src of imgSrcs) {\n\t\t\taddLocal(src)\n\t\t}\n\n\t\tfor (const href of svgHrefs) {\n\t\t\taddLocal(href)\n\t\t}\n\n\t\tfor (const href of linkHrefs) {\n\t\t\taddLocal(href)\n\t\t}\n\n\t\tfor (const cssText of inlineCss) {\n\t\t\tconst { urls, imports } = parsers.parseCssRefs(cssText)\n\n\t\t\tfor (const url of urls) {\n\t\t\t\taddLocal(url)\n\t\t\t}\n\n\t\t\tfor (const target of imports) {\n\t\t\t\taddLocal(target)\n\t\t\t}\n\t\t}\n\n\t\treturn [...refs]\n\t}\n}\n\n/**\n * Build a `scanRemoteRefs(html)` from a parser pair: every remote (http/https)\n * asset reference in the HTML itself. The mirror of `makeScanAssetRefs` for\n * remote URLs, so the lean (scan-lite) and parser-backed (parse.ts) scanners\n * stay in step. Pure and IO-free — it does not fetch anything.\n */\nexport function makeScanRemoteRefs(parsers: RefParsers): (html: string) => string[] {\n\treturn html => {\n\t\tconst { imgSrcs, svgHrefs, linkHrefs, inlineCss } = parsers.parseHtmlRefs(html)\n\t\tconst refs = new Set<string>()\n\n\t\tconst addRemote = (ref: string) => {\n\t\t\tif (isRemoteOrigin(ref)) {\n\t\t\t\trefs.add(ref)\n\t\t\t}\n\t\t}\n\n\t\tfor (const src of imgSrcs) {\n\t\t\taddRemote(src)\n\t\t}\n\n\t\tfor (const href of svgHrefs) {\n\t\t\taddRemote(href)\n\t\t}\n\n\t\tfor (const href of linkHrefs) {\n\t\t\taddRemote(href)\n\t\t}\n\n\t\tfor (const cssText of inlineCss) {\n\t\t\tconst { urls, imports } = parsers.parseCssRefs(cssText)\n\n\t\t\tfor (const url of urls) {\n\t\t\t\taddRemote(url)\n\t\t\t}\n\n\t\t\tfor (const target of imports) {\n\t\t\t\taddRemote(target)\n\t\t\t}\n\t\t}\n\n\t\treturn [...refs].sort()\n\t}\n}\n","import type { CssRefs } from './scan-core'\n\n// CSS needs only url() and @import targets — narrow enough that a small,\n// comment-stripped tokenizer beats pulling in postcss. Zero dependencies, so\n// both the node-html-parser path (parse.ts, used by zip()) and the regex\n// scanner (scan-lite.ts, used by the cheap static check) share this one CSS\n// implementation without either dragging in the other's HTML parser.\n\nconst CSS_COMMENT_RE = /\\/\\*[\\s\\S]*?\\*\\//g\nconst CSS_URL_RE = /url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)'\"\\s][^)]*?))\\s*\\)/gi\nconst CSS_IMPORT_RE = /@import\\s+(?:url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^)'\"]+?))\\s*\\)|\"([^\"]*)\"|'([^']*)')/gi\n\nfunction matchAll(input: string, pattern: RegExp): string[] {\n\tconst out: string[] = []\n\n\tfor (const match of input.matchAll(pattern)) {\n\t\tconst value = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5]\n\n\t\t// keep an empty value (url(\"\")) — the collector reports it as a broken ref;\n\t\t// only skip when no capture group matched at all\n\t\tif (value != null) {\n\t\t\tout.push(value.trim())\n\t\t}\n\t}\n\n\treturn out\n}\n\n/**\n * Pull every `url(...)` target and every `@import` target out of a CSS string.\n * Comments are stripped first so a commented-out reference is never collected.\n * Pure and IO-free.\n */\nexport function parseCssRefs(cssText: string): CssRefs {\n\tconst withoutComments = cssText.replace(CSS_COMMENT_RE, '')\n\tconst imports = matchAll(withoutComments, CSS_IMPORT_RE)\n\n\t// strip @import statements before scanning url() so an @import url() form\n\t// isn't counted twice (the full parser separated these by rule type)\n\tconst withoutImports = withoutComments.replace(CSS_IMPORT_RE, '')\n\t// a bare fragment like url(#gradient) points at an element already in the\n\t// document (an SVG paint server, clip-path, mask, or filter) so there is no\n\t// file to bundle\n\tconst urls = matchAll(withoutImports, CSS_URL_RE).filter(ref => !ref.startsWith('#'))\n\n\treturn { urls, imports }\n}\n","import type { HtmlRefs } from './scan-core'\n\nimport { makeScanAssetRefs, makeScanRemoteRefs } from './scan-core'\nimport { parseCssRefs } from './parse-css'\n\n// The lightweight scanner behind `scanAssetRefs` — the cheap known-asset check\n// the compiled wrapper runs at render time. Regex over well-formed,\n// quote-attributed HTML (what the Format engine renders), with no parser\n// dependency, so static-mode bundles that import only `scanAssetRefs` stay\n// lean. zip()'s heavier collection uses node-html-parser (see parse.ts); both\n// share one CSS tokenizer (parse-css) and are kept in step by the parity tests.\n\nconst IMG_SRC_RE = /<img\\b[^>]*?\\ssrc\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\nconst SVG_REF_TAG_RE = /<(?:image|use)\\b[^>]*?\\s(?:xlink:)?href\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\nconst LINK_TAG_RE = /<link\\b[^>]*>/gi\nconst HREF_RE = /\\shref\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/i\nconst REL_STYLESHEET_RE = /\\srel\\s*=\\s*(?:\"stylesheet\"|'stylesheet')/i\nconst STYLE_BLOCK_RE = /<style\\b[^>]*>([\\s\\S]*?)<\\/style>/gi\nconst STYLE_ATTR_RE = /\\sstyle\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/gi\n\nconst ENTITIES: Record<string, string> = {\n\t'&': '&',\n\t'"': '\"',\n\t''': \"'\",\n\t'<': '<',\n\t'>': '>'\n}\n\n// Attribute values come out of the markup entity-encoded; node-html-parser\n// decodes them, so the regex scanner must match.\nfunction decodeEntities(value: string): string {\n\treturn value.replace(/&(?:amp|quot|#39|lt|gt);/g, entity => ENTITIES[entity] ?? entity)\n}\n\nfunction matchAll(input: string, pattern: RegExp): string[] {\n\tconst out: string[] = []\n\n\tfor (const match of input.matchAll(pattern)) {\n\t\tconst value = match[1] ?? match[2]\n\n\t\t// keep an empty value (src=\"\") — an empty ref is dropped downstream, not\n\t\t// here, so both parsers extract the same set (see parse.ts)\n\t\tif (value != null) {\n\t\t\tout.push(decodeEntities(value))\n\t\t}\n\t}\n\n\treturn out\n}\n\n/** Regex equivalent of parse.ts's `parseHtmlRefs`. Pure and IO-free. */\nfunction parseHtmlRefs(html: string): HtmlRefs {\n\tconst imgSrcs = matchAll(html, IMG_SRC_RE)\n\n\tconst svgHrefs = matchAll(html, SVG_REF_TAG_RE).filter(href => !href.startsWith('#'))\n\n\tconst linkHrefs: string[] = []\n\tfor (const tagMatch of html.matchAll(LINK_TAG_RE)) {\n\t\tconst tag = tagMatch[0]\n\n\t\tif (!REL_STYLESHEET_RE.test(tag)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst href = HREF_RE.exec(tag)\n\t\tconst value = href?.[1] ?? href?.[2]\n\n\t\t// keep an empty href=\"\" (reported downstream); skip only when there is no\n\t\t// href match at all\n\t\tif (value != null) {\n\t\t\tlinkHrefs.push(decodeEntities(value))\n\t\t}\n\t}\n\n\tconst styleBlocks = [...html.matchAll(STYLE_BLOCK_RE)].map(match => match[1] ?? '')\n\tconst styleAttrs = matchAll(html, STYLE_ATTR_RE)\n\n\treturn { imgSrcs, svgHrefs, linkHrefs, inlineCss: [...styleBlocks, ...styleAttrs] }\n}\n\n/**\n * Scan an HTML string for the local asset references it carries, returning each\n * as a bundle-root relative path. Dependency-free implementation for browser,\n * worker, and edge bundles — same contract as scan.ts's `scanAssetRefs`.\n */\nexport const scanAssetRefs = makeScanAssetRefs({ parseHtmlRefs, parseCssRefs })\n\n/**\n * Scan an HTML string for the remote (http/https) asset references it carries.\n * Dependency-free counterpart to scan-remote.ts's `scanRemoteRefs`, so the\n * static-mode wrapper can list remote refs without pulling in node-html-parser.\n */\nexport const scanRemoteRefs = makeScanRemoteRefs({ parseHtmlRefs, parseCssRefs })\n"],"mappings":";AAgBA,IAAa,iBAAb,cAAoC,MAAM;CACzC,YACC,AAAgBA,MAChB,SACA,SACC;AACD,QAAM,SAAS,QAAQ;EAJP;;;AA4ClB,MAAM,aAAa,UAAoB,MAAM,KAAI,SAAQ,KAAK,OAAO,CAAC,KAAK,KAAK;AAEhF,SAAS,0BAA0B,QAAqC;CACvE,MAAM,EAAE,cAAc,MAAM,SAAS,OAAO,eAAe,EAAE,KAAK;CAElE,MAAM,WAAW,CAAC,gCAAgC,aAAa,GAAG;AAElE,KAAI,QAAQ,OACX,UAAS,KAAK,0BAA0B,UAAU,QAAQ,GAAG;AAG9D,KAAI,aAAa,OAChB,UAAS,KAAK,+BAA+B,UAAU,aAAa,GAAG;AAGxE,KAAI,MAAM,OACT,UAAS,KAAK,kBAAkB,UAAU,MAAM,GAAG;AAGpD,KAAI,QAAQ,QAAQ;EAGnB,MAAM,YACL;AAED,WAAS,KACR,SAAS,YACN,GAAG,UAAU,KACb,GAAG,UAAU,6EAChB;;AAGF,KAAI,aAAa,OAChB,UAAS,KAAK,wEAAwE;AAGvF,QAAO,SAAS,KAAK,OAAO;;;;;;;;;AAU7B,IAAa,qBAAb,cAAwC,eAAe;CACtD,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,YAAY,QAA6B;AACxC,QAAM,kBAAkB,0BAA0B,OAAO,CAAC;AAE1D,OAAK,OAAO;AACZ,OAAK,eAAe,OAAO;AAC3B,OAAK,OAAO,OAAO;AACnB,OAAK,UA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