clean-jsdoc-theme 5.2.1 → 5.3.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"publish.mjs","names":["resolvePath","joinPath","resolve"],"sources":["../../../node_modules/.pnpm/tsdown@0.22.14_tsx@4.22.3_typescript@5.9.3_unrun@0.3.1/node_modules/tsdown/esm-shims.js","../src/write-output-files.ts","../src/publish.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","'use strict';\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { OutputFile } from '@clean-jsdoc-theme/dwar';\n\nexport async function writeOutputFiles(\n destination: string,\n files: readonly OutputFile[]\n): Promise<void> {\n for (const file of files) {\n const target = join(destination, file.path);\n await mkdir(dirname(target), { recursive: true });\n const contents = typeof file.contents === 'string' ? file.contents : Buffer.from(file.contents);\n await writeFile(target, contents);\n }\n}\n","'use strict';\n\n// JSDoc 4 → setu → dwar bridge. `publish(taffyData, opts, tutorials)` is the\n// entry JSDoc invokes; everything below orchestrates the four phase packages.\n\nimport { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { basename, dirname, extname, join as joinPath, resolve as resolvePath } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type {\n CopyPageAction,\n CopyPageConfig,\n PageNavConfig,\n MetaTag,\n OutputFile,\n SiteLogo,\n SiteManifest,\n SiteName,\n ThemeColors,\n ThemeConfig,\n} from '@clean-jsdoc-theme/dwar';\nimport type {\n DocInput,\n MenuItem,\n PlaygroundSiteConfig,\n SourceFileInput,\n TutorialInput,\n} from '@clean-jsdoc-theme/setu';\nimport type { PlaygroundProvider } from '@clean-jsdoc-theme/utils';\nimport { writeOutputFiles } from './write-output-files';\n\n// JSDoc's tutorial source-type enum (jsdoc/lib/jsdoc/tutorial.js): HTML = 1,\n// MARKDOWN = 2. A tutorial's `.content` is the RAW source; `.type` says how to\n// read it.\nconst JSDOC_TUTORIAL_TYPE_MARKDOWN = 2;\n\n// Absolute path of the running module. `__filename` is native in the CJS build\n// and injected into the ESM build by tsdown's `shims` option (from\n// import.meta.url), so this resolves in both without an eval/`new Function` shim.\nfunction anchorPath(): string {\n if (typeof __filename === 'string') return __filename;\n throw new Error(\n 'clean-jsdoc-theme: could not determine the running module path (__filename is unavailable).'\n );\n}\n\nfunction resolvePackageDir(name: string): string {\n const start = anchorPath();\n let dir = dirname(start);\n let prev = '';\n while (dir !== prev) {\n const candidate = resolvePath(dir, 'node_modules', name);\n try {\n readFileSync(resolvePath(candidate, 'package.json'), 'utf8');\n return candidate;\n } catch {\n // not here — go up.\n }\n prev = dir;\n dir = dirname(dir);\n }\n throw new Error(`clean-jsdoc-theme: could not locate '${name}' on disk starting from ${start}.`);\n}\n\ninterface MinimalPkgJson {\n main?: string;\n module?: string;\n exports?: string | Record<string, unknown>;\n}\n\n/**\n * Resolve an `exports` condition subtree (a string target, or a conditions\n * object like `{ import, require, default, types }`) to an absolute path,\n * preferring the ESM condition (`import`, then a bare `default`). Recurses for\n * nested conditions (`import: { default: \"…\" }`). Returns `undefined` when no\n * usable target is present.\n */\nfunction resolveExportTarget(node: unknown, pkgRoot: string): string | undefined {\n if (typeof node === 'string') return resolvePath(pkgRoot, node);\n if (!node || typeof node !== 'object') return undefined;\n const o = node as Record<string, unknown>;\n const imp = resolveExportTarget(o.import, pkgRoot);\n if (imp) return imp;\n if (typeof o.default === 'string') return resolvePath(pkgRoot, o.default);\n return undefined;\n}\n\nfunction resolveEsmEntry(name: string): string {\n const pkgRoot = resolvePackageDir(name);\n const pkg = JSON.parse(\n readFileSync(resolvePath(pkgRoot, 'package.json'), 'utf8')\n ) as MinimalPkgJson;\n\n const exp = pkg.exports;\n if (typeof exp === 'string') return resolvePath(pkgRoot, exp);\n if (exp && typeof exp === 'object') {\n // Either a `.` subpath (`{ \".\": … }`) or top-level conditions with no\n // subpaths (`{ import, default, types }`, as ora ships). Resolve whichever.\n const dot = (exp as Record<string, unknown>)['.'];\n const target = resolveExportTarget(dot !== undefined ? dot : exp, pkgRoot);\n if (target) return target;\n }\n if (typeof pkg.module === 'string') return resolvePath(pkgRoot, pkg.module);\n if (typeof pkg.main === 'string') return resolvePath(pkgRoot, pkg.main);\n\n throw new Error(\n `clean-jsdoc-theme: could not determine ESM entry file for '${name}' (no exports/module/main).`\n );\n}\n\n// setu and dwar are ESM-only; JSDoc 4 loads this theme via `require()`, so the\n// CJS bundle here can't `require()` them. Dynamic-import a `file://` URL\n// instead. The specifier is funneled through a variable so the bundler don't\n// rewrite the dynamic import into a static `require()` during CJS bundling.\nasync function loadDep<T>(name: string, requiredExports: readonly string[]): Promise<T> {\n const entry = resolveEsmEntry(name);\n const id = pathToFileURL(entry).href;\n const mod = (await import(id)) as Record<string, unknown>;\n for (const key of requiredExports) {\n if (typeof mod[key] !== 'function') {\n throw new Error(\n `clean-jsdoc-theme: '${name}' did not export a '${key}' function ` +\n `(resolved from ${entry}; got keys: ${Object.keys(mod).join(', ') || '(none)'}).`\n );\n }\n }\n return mod as T;\n}\nconst loadSetu = (): Promise<typeof import('@clean-jsdoc-theme/setu')> =>\n loadDep('@clean-jsdoc-theme/setu', ['generateSite', 'stampSite']);\nconst loadDwar = (): Promise<typeof import('@clean-jsdoc-theme/dwar')> =>\n loadDep('@clean-jsdoc-theme/dwar', ['render']);\nconst loadUtils = (): Promise<typeof import('@clean-jsdoc-theme/utils')> =>\n loadDep('@clean-jsdoc-theme/utils', [\n 'validateThemeOpts',\n 'createGoogleFontResolver',\n 'formatDiagnostics',\n 'warningsOnly',\n 'formatBuildReport',\n 'formatRenderError',\n 'normalizeBasePath',\n 'withBase',\n 'toExtractManifest',\n 'normalizeCollapsibleSidebarSections',\n 'unmatchedCollapsibleSections',\n 'topLevelSectionLabels',\n 'normalizeScrollbar',\n ]);\n\n/** The `ora` spinner factory (its default export). */\ntype OraFactory = typeof import('ora').default;\n\n/**\n * Load `ora` (ESM-only) the same way as the other deps — via a resolved\n * `file://` URL so the CJS bundle doesn't `require()` it. Returns `null` if\n * `ora` can't be loaded, so progress degrades to silent rather than failing\n * the build.\n */\nconst loadOra = async (): Promise<OraFactory | null> => {\n try {\n const mod = await loadDep<typeof import('ora')>('ora', ['default']);\n return mod.default;\n } catch {\n return null;\n }\n};\n\n/**\n * JSDoc's own standard `opts` keys (`jsdoc/lib/jsdoc/opts/argparser.js` +\n * `conf` schema). These share the flat `opts` namespace with the theme's\n * options, so they must never be flagged as unknown theme keys — even by a\n * near-miss typo distance. Theme keys (`docs`, `docGroups`, …) live in\n * `THEME_OPT_KEYS`, NOT here.\n */\nconst JSDOC_OWN_OPTS: ReadonlySet<string> = new Set([\n 'destination',\n 'template',\n 'encoding',\n 'recurse',\n 'readme',\n 'package',\n 'tutorials',\n 'query',\n 'private',\n 'access',\n 'explain',\n 'debug',\n 'verbose',\n 'pedantic',\n 'match',\n 'nocolor',\n 'templates',\n]);\n\ninterface JSDocOpts {\n destination?: string;\n package?: string;\n /**\n * Site identity from `jsdoc.json` (`\"opts\": { \"siteName\": ... }`). Either a\n * string (shown in the header/footer and appended to each page's `<title>`),\n * or a logo image set `{ default, dark, light, alt }`. Local image paths are\n * copied into the output; `http(s)://` and `data:` values pass through. The\n * `alt` text (or `pkg.name`) is used for the `<title>` suffix and image alt.\n */\n siteName?: string | SiteLogo;\n /**\n * Font overrides from `jsdoc.json` (`\"opts\": { \"fonts\": { ... } }`). Values\n * are Google Fonts family names for `heading`/`body`; `mono` is a CSS stack.\n */\n fonts?: { heading?: string; body?: string; mono?: string };\n /**\n * Light-mode color overrides from `jsdoc.json` (`\"opts\": { \"colors\": { ... } }`).\n * Any subset of `bg`, `bgMuted`, `fg`, `fgMuted`, `accent`, `accentFg`, `border`;\n * each value is any CSS color string (the theme ships oklch). Omitted keys keep\n * the default palette.\n */\n colors?: unknown;\n /**\n * Dark-mode color overrides (`\"opts\": { \"darkColors\": { ... } }`). Same keys as\n * {@link JSDocOpts.colors}; emitted under `[data-theme=\"dark\"]`. Omitted keys\n * keep the default dark palette.\n */\n darkColors?: unknown;\n /**\n * Project README as HTML. JSDoc renders the Markdown README (`-R`/`opts.readme`\n * or one found in the source paths) and replaces this with the resulting HTML\n * before calling `publish`. Rendered as the site home page.\n */\n readme?: string;\n /** Path to the tutorials directory (`-u`/`opts.tutorials`); resolved tree arrives as the 3rd `publish` arg. */\n tutorials?: string;\n /**\n * Path to a docs content directory (`jsdoc.json` `\"opts\": { \"docs\": \"docs/\" }`),\n * resolved relative to the cwd. The bridge walks it recursively; each\n * `*.md`/`*.markdown` (and `*.html`) file becomes a prose page at its clean,\n * unprefixed slug (the relative path), grouped by frontmatter/directory. A root\n * `index.md` becomes the home page. Unset → no docs site (today's behavior).\n */\n docs?: unknown;\n /**\n * Top-level doc-group display order (`jsdoc.json` `\"opts\": { \"docGroups\": [...] }`).\n * An ordered list of doc-group labels controlling how the doc-group sidebar\n * sections render (after the API sections). Omit for the default order.\n */\n docGroups?: unknown;\n /**\n * Group label assigned to a doc page that carries no frontmatter/directory\n * group (`jsdoc.json` `\"opts\": { \"defaultDocGroup\": \"Docs\" }`). Omit to leave\n * such pages ungrouped.\n */\n defaultDocGroup?: unknown;\n /**\n * Sidebar section order from `jsdoc.json` (`\"opts\": { \"sectionOrder\": [...] }`).\n * An ordered list of section labels (e.g. `[\"Classes\", \"Tutorials\"]`) that both\n * filters and orders the sidebar sections; \"Home\" and \"Source Files\" are always\n * shown regardless. Omit (or leave empty) for the default order.\n */\n sectionOrder?: unknown;\n /**\n * Full sidebar menu from `jsdoc.json` (`\"opts\": { \"menu\": [...] }`). An ordered\n * list of `{ id, title, href, icon }` entries. When present it takes precedence\n * over `sectionOrder` and controls the entire sidebar (built-ins, sections, and\n * external links). See setu's {@link MenuItem}.\n */\n menu?: unknown;\n /**\n * Club related sidebar entries into prefix-grouped subtrees (`jsdoc.json`\n * `\"opts\": { \"clubSidebarItems\": true }`). Groups entries within each section\n * by the path segment before the first `/` (e.g. `queue/*` under a `queue`\n * parent); a prefix with a single entry is left flat. Off by default.\n */\n clubSidebarItems?: unknown;\n /**\n * Which top-level sidebar sections collapse (`jsdoc.json`\n * `\"opts\": { \"collapsibleSidebarSections\": true | [\"Classes\",\"Namespaces\"] }`).\n * `true`/absent → all; `false` → none; array → only those exact labels\n * (case-sensitive). Unmatched labels warn. See utils `resolveCollapsibleSections`.\n */\n collapsibleSidebarSections?: unknown;\n /**\n * Custom prompt for the copy-page button's \"Open in ChatGPT/Claude/Perplexity\"\n * actions (`jsdoc.json` `\"opts\": { \"aiPrompt\": \"…\" }`). `{siteName}`, `{url}`,\n * and `{mdUrl}` (the page's raw Markdown link) placeholders are substituted at\n * click time. Only the prompt + links are sent (the AI fetches `{mdUrl}`), so\n * the query stays short for long docs. Omit for a sensible default.\n */\n aiPrompt?: unknown;\n /**\n * Copy-page button config (`jsdoc.json` `\"opts\": { \"copyPage\": … }`). Either a\n * boolean (`false` hides the button) or an object `{ enabled?, actions? }`,\n * where `actions` is an ordered subset of\n * `[\"copy\",\"view\",\"claude\",\"chatgpt\",\"perplexity\"]` (`[]` shows just the\n * primary copy button). Defaults to enabled with all actions.\n */\n copyPage?: unknown;\n /**\n * Previous/next page pager config (`jsdoc.json` `\"opts\": { \"pageNav\": … }`).\n * Either a boolean (`false` hides the pager) or an object `{ enabled? }`. The\n * pager links each content page to its neighbors in sidebar reading order.\n * Defaults to enabled.\n */\n pageNav?: unknown;\n /**\n * Scrollbar presentation (`jsdoc.json` `\"opts\": { \"scrollbar\": \"native\" }`).\n * `\"styled\"` (default) = overlay bar that hides at rest; `\"visible\"` = themed\n * bar always shown; `\"native\"` = the browser's own scrollbar. See #281.\n */\n scrollbar?: unknown;\n /**\n * Code-playground config (`jsdoc.json` `\"opts\": { \"playground\": … }`). Either\n * a boolean (`true` turns it on with defaults; absent/`false` = off) or an\n * object `{ enableForAllExamples?, providers?, codepen?, jsfiddle?,\n * codesandbox? }`. `providers` picks which of CodePen/JSFiddle/CodeSandbox an\n * `@example` (or prose code block) can be opened in; the per-provider records\n * hold their site-wide runtime options. When set, `@playground` tags are\n * honored; when off, they're ignored (byte-identical output).\n */\n playground?: unknown;\n /**\n * Custom site footer (`jsdoc.json` `\"opts\": { \"footer\": … }`). Either an\n * inline HTML string (v4 parity) or `{ \"file\": \"./footer.html\" }` (read from\n * disk by the bridge). Rendered into rang's footer slot in place of the\n * default footer on every page; style it with `customCss`/`customCssFile`.\n * Omit for the default footer.\n */\n footer?: unknown;\n /**\n * Site public base URL (`jsdoc.json` `\"opts\": { \"siteUrl\": \"https://example.com\" }`).\n * When set, the build emits a `sitemap.xml` at the output root listing every\n * non-hidden page's canonical URL. Only the URL's origin is used — the deploy\n * sub-path comes from `basePath` — so a bare origin or a full URL whose path\n * equals `basePath` both work. Omit it for no sitemap.\n */\n siteUrl?: unknown;\n /**\n * Emit an llmstxt.org index (`jsdoc.json` `\"opts\": { \"llmsTxt\": true }`) —\n * `llms.txt` at the output root, plus `llms-full.txt` (every page concatenated)\n * unless `full: false`. Accepts `true` (⇒ `{ full: true, api: true }`) or\n * `{ full?: boolean, api?: boolean | 'index' }`, where `api: 'index'` lists API\n * pages without descriptions and omits their bodies from `llms-full.txt`, and\n * `api: false` omits API pages entirely. **Requires `siteUrl`** — the file is\n * fetched standalone, so its links must be absolute; without it the build warns\n * and emits nothing.\n */\n llmsTxt?: unknown;\n /**\n * Favicon (`jsdoc.json` `\"opts\": { \"favicon\": \"./icon.svg\" }`). A path to an\n * image file (`.svg`/`.png`/`.ico`/…), relative to the working dir. The bridge\n * copies it to a content-hashed `_assets/` asset and emits a `<link rel=\"icon\">`\n * in every page's `<head>`. Needed for an SVG favicon (browsers only\n * auto-discover a root `favicon.ico`). Omit for none.\n */\n favicon?: unknown;\n /**\n * Site-wide custom `<meta>` tags (`jsdoc.json` `\"opts\": { \"meta\": [...] }`). An\n * array of attribute maps — each object's key/value pairs become one `<meta>`\n * tag in `<head>` (`{ name, content }`, `{ property, content }`, …). dwar\n * escapes values, drops invalid attribute names, and de-dupes against its own\n * head defaults (an author `name: \"description\"` replaces the auto one).\n */\n meta?: unknown;\n /**\n * Inline custom CSS (`jsdoc.json` `\"opts\": { \"customCss\": \"…\" }`), injected as\n * a `<style>` after the theme stylesheet so it can override.\n */\n customCss?: unknown;\n /**\n * Path(s) to custom CSS file(s) (`\"opts\": { \"customCssFile\": \"a.css\" }` or an\n * array). Each file is copied AS-IS (its own bytes) to\n * `_assets/<name>.<hash>.css` and linked after the theme stylesheet. The\n * `<hash>` is a content hash (see `hashCustomAssets`), so an unchanged file\n * keeps a stable, cacheable URL.\n */\n customCssFile?: unknown;\n /**\n * Inline custom JS (`\"opts\": { \"customJs\": \"…\" }`), injected as a classic\n * `<script>` before `</body>`, after the theme's own scripts.\n */\n customJs?: unknown;\n /**\n * Path(s) to custom JS file(s) (`\"opts\": { \"customJsFile\": \"a.js\" }` or an\n * array). Each file is copied AS-IS to `_assets/<name>.<hash>.js` and\n * referenced before `</body>`. See `hashCustomAssets`.\n */\n customJsFile?: unknown;\n /**\n * Whether to append a content hash to copied `customCssFile`/`customJsFile`\n * asset names (`_assets/<name>.<hash>.css`). Defaults to `true` — the hash is\n * derived from the file's content (NOT random), so an unchanged file yields\n * the same URL across builds (cache-friendly) and a changed file cache-busts.\n * Set `false` to copy with the original `<name>.css`/`.js` (no hash).\n */\n hashCustomAssets?: unknown;\n /**\n * Build-stage progress output (`jsdoc.json` `\"opts\": { \"progress\": false }`).\n * The setu→dwar pipeline does noticeably more than a bare jsdoc run (per-page\n * MDX compile, per-island esbuild bundling, the island cache), so by default\n * the bridge narrates each stage with its elapsed time. Set `false` to silence\n * the stage lines (the build report still prints).\n */\n progress?: unknown;\n /**\n * JSDoc's default-template source options, read from `conf.templates.default`\n * (or, as a fallback, nested under `opts.templates`):\n * - `outputSourceFiles` — defaults to `true`; set `false` to suppress the\n * per-file source viewer pages and the `Source: file:line` member links.\n * - `sourceLinkToComment` — defaults to `false`. By default a `Source:`\n * link lands on the first line of the declaration; set `true` to point it\n * at the doclet's doc-comment line instead (the pre-v5 behavior).\n * - `cleanOutputDir` — defaults to `true`; set `false` to keep existing files\n * in the destination instead of emptying it before each build.\n */\n templates?: {\n default?: {\n outputSourceFiles?: unknown;\n sourceLinkToComment?: unknown;\n cleanOutputDir?: unknown;\n /**\n * JSDoc's standard static-file passthrough\n * (`templates.default.staticFiles`): `{ include, exclude, includePattern,\n * excludePattern }`. Files matched by `include` are copied verbatim into\n * the output (an include dir's contents land at the output root, JSDoc's\n * mapping) AND their dirs become fallback search roots for image\n * resolution, so a bare/relative reference to a static image resolves.\n */\n staticFiles?: unknown;\n };\n };\n [key: string]: unknown;\n}\n\nconst defaultTheme: ThemeConfig = {\n tokens: {\n // Light palette (oklch). bg #fdfdf7 · fg #3e3e3e · border #eeeeee;\n // muted/accent derived to harmonize.\n colors: {\n bg: 'oklch(0.9924 0.0079 106.54)',\n bgMuted: 'oklch(0.9595 0.0079 106.55)',\n fg: 'oklch(0.3639 0 0)',\n fgMuted: 'oklch(0.5278 0 0)',\n accent: 'oklch(0 0 0)',\n accentFg: 'oklch(1 0 0)',\n border: 'oklch(0.9561 0 0)',\n },\n // Dark palette (oklch). bg #09090b · fg #9e9e9e · border #141416;\n // muted/accent derived to harmonize.\n darkColors: {\n bg: 'oklch(0.1408 0.0044 285.82)',\n bgMuted: 'oklch(0.2103 0.0059 285.89)',\n fg: 'oklch(0.6993 0 0)',\n fgMuted: 'oklch(0.5382 0 0)',\n accent: 'oklch(1 0 0)',\n accentFg: 'oklch(0 0 0)',\n border: 'oklch(0.2321 0.004 286.02)',\n },\n fonts: {\n heading: 'Source Serif 4',\n body: 'Roboto',\n mono: 'ui-monospace, SFMono-Regular, Menlo, monospace',\n },\n shiki: { light: 'github-light', dark: 'github-dark' },\n },\n basePath: '/',\n};\n\n/** One font triple — any subset of `{ heading, body, mono }`. */\ninterface FontSet {\n heading?: string;\n body?: string;\n mono?: string;\n}\n\n/**\n * The shape validated font overrides take: base `{ heading, body, mono }` plus\n * optional per-locale overrides (from `<code>:heading`-style opts). Mirrors\n * utils' `ValidatedFonts`.\n */\ninterface ValidatedFonts extends FontSet {\n locales?: Record<string, FontSet>;\n}\n\n/**\n * Resolve the font triple for the active `locale`: a per-locale override wins,\n * then the base font, then the theme default — per slot. With no locale (a\n * normal, non-localized build) only the base + default apply, so the result is\n * byte-identical to before per-locale fonts existed.\n */\nfunction resolveFontSet(fonts: ValidatedFonts, locale: string | undefined) {\n const base = defaultTheme.tokens.fonts;\n const override = (locale && fonts.locales?.[locale]) || {};\n return {\n heading: override.heading ?? fonts.heading ?? base.heading,\n body: override.body ?? fonts.body ?? base.body,\n mono: override.mono ?? fonts.mono ?? base.mono,\n };\n}\n\n/**\n * Merge validated user overrides from `jsdoc.json` (`siteName`, `fonts`) over\n * the defaults. Only the keys the user supplies are overridden; everything else\n * keeps the default theme. `siteName` is pre-resolved/validated and its local\n * logos copied by `prepareSiteName`; `fonts` is the validated subset (any\n * family flagged `fonts/not-google` is dropped upstream so the default applies).\n * `locale` (set in build mode) selects per-locale font overrides.\n */\nfunction resolveTheme(\n opts: JSDocOpts,\n siteName: SiteName | undefined,\n fonts: ValidatedFonts,\n basePath: string,\n locale?: string\n): ThemeConfig {\n const aiPrompt =\n typeof opts.aiPrompt === 'string' && opts.aiPrompt.trim() ? opts.aiPrompt.trim() : undefined;\n const copyPage = normalizeCopyPage(opts.copyPage);\n const pageNav = normalizePageNav(opts.pageNav);\n // Only the runtime (per-provider options) slice belongs in the theme; the\n // enablement slice goes to setu (see the siteOptions assembly).\n const playground = normalizePlayground(opts.playground);\n\n // Color overrides merge per-key over the default palettes, so supplying only\n // `colors.bg` keeps every other default color. `darkColors` layers over the\n // default dark palette the same way.\n const colors = normalizeColors(opts.colors);\n const darkColors = normalizeColors(opts.darkColors);\n\n return {\n ...defaultTheme,\n basePath,\n ...(aiPrompt ? { aiPrompt } : {}),\n ...(copyPage ? { copyPage } : {}),\n ...(pageNav ? { pageNav } : {}),\n ...(playground ? { playground: playground.theme } : {}),\n tokens: {\n ...defaultTheme.tokens,\n colors: { ...defaultTheme.tokens.colors, ...(colors ?? {}) },\n darkColors: { ...defaultTheme.tokens.darkColors, ...(darkColors ?? {}) },\n fonts: resolveFontSet(fonts, locale),\n ...(siteName ? { siteName } : {}),\n },\n };\n}\n\n/** Trim a value to a non-empty string, or `undefined`. */\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined;\n}\n\n/**\n * Short, deterministic content hash for cache-stable custom-asset filenames.\n * Derived from the file's bytes (NOT random), so an unchanged file produces the\n * same name across builds (browser cache hit) and a changed file cache-busts.\n */\nfunction contentHash(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex').slice(0, 8);\n}\n\n/**\n * Copy custom CSS/JS file(s) (a path or array, relative to the working dir) to\n * served `_assets` files and return their hrefs. Each file is copied AS-IS (its\n * own bytes — never concatenated). The asset name is `<base>.<hash>.<ext>` when\n * `hash` is on (the hash is content-derived → stable URL for unchanged files),\n * else the bare `<base><ext>`. A file that can't be read is skipped with a\n * warning (resilient, like `prepareSiteName`); an identical served name is\n * emitted once.\n */\nasync function copyCustomFiles(\n raw: unknown,\n ext: '.css' | '.js',\n hash: boolean,\n label: string,\n hrefForServed: (servedPath: string) => string\n): Promise<{ links: string[]; files: OutputFile[] }> {\n const paths = (Array.isArray(raw) ? raw : [raw]).filter(\n (p): p is string => typeof p === 'string' && p.trim().length > 0\n );\n const links: string[] = [];\n const files: OutputFile[] = [];\n const seen = new Set<string>();\n for (const p of paths) {\n const trimmed = p.trim();\n let bytes: Buffer;\n try {\n bytes = await readFile(resolvePath(trimmed));\n } catch {\n console.warn(`clean-jsdoc-theme: could not read ${label} ('${trimmed}'); skipping it.`);\n continue;\n }\n const base = basename(trimmed, extname(trimmed)) || 'custom';\n const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;\n const servedPath = `_assets/${name}`;\n if (seen.has(servedPath)) continue;\n seen.add(servedPath);\n files.push({ path: servedPath, contents: bytes });\n // The OutputFile `path` stays relative (no leading slash); only the served\n // href gets the base-path prefix (`/` when unset → unchanged).\n links.push(hrefForServed(servedPath));\n }\n return { links, files };\n}\n\n/**\n * Resolve the custom CSS/JS injection options into render-ready `ThemeConfig`\n * fields plus the asset files to write. Inline strings (`customCss`/`customJs`)\n * pass through; file options (`customCssFile`/`customJsFile`) are read + copied\n * to content-hashed assets here — the bridge is the I/O layer, so dwar's\n * `render()` stays pure and just links the resulting hrefs. `hashCustomAssets`\n * (default `true`) toggles the content-hash suffix.\n */\nasync function resolveCustomAssets(\n opts: JSDocOpts,\n hrefForServed: (servedPath: string) => string\n): Promise<{\n theme: {\n customCss?: string;\n customCssLinks?: string[];\n customJs?: string;\n customJsLinks?: string[];\n };\n files: OutputFile[];\n}> {\n const hash = opts.hashCustomAssets !== false; // content-hashed by default\n const [cssAssets, jsAssets] = await Promise.all([\n copyCustomFiles(opts.customCssFile, '.css', hash, 'customCssFile', hrefForServed),\n copyCustomFiles(opts.customJsFile, '.js', hash, 'customJsFile', hrefForServed),\n ]);\n const customCss = nonEmptyString(opts.customCss)?.trim();\n const customJs = nonEmptyString(opts.customJs)?.trim();\n return {\n theme: {\n ...(customCss ? { customCss } : {}),\n ...(cssAssets.links.length > 0 ? { customCssLinks: cssAssets.links } : {}),\n ...(customJs ? { customJs } : {}),\n ...(jsAssets.links.length > 0 ? { customJsLinks: jsAssets.links } : {}),\n },\n files: [...cssAssets.files, ...jsAssets.files],\n };\n}\n\n/**\n * Resolve `opts.footer` (inline HTML `string` | `{ file }`) into the single\n * `ThemeConfig.footer` string. The `{ file }` form is read from disk HERE — the\n * bridge is the I/O layer, so dwar's `render()` only ever sees the resolved\n * string. A missing/unreadable file is warned about and dropped (resilient,\n * like the logo/custom-asset paths), and an empty value yields `undefined` so\n * the default footer renders. Exported for testing.\n */\nexport async function resolveFooter(raw: unknown): Promise<string | undefined> {\n if (typeof raw === 'string') {\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n if (raw && typeof raw === 'object' && typeof (raw as { file?: unknown }).file === 'string') {\n const file = (raw as { file: string }).file.trim();\n if (!file) return undefined;\n try {\n const html = await readFile(resolvePath(file), 'utf8');\n return html.trim().length > 0 ? html : undefined;\n } catch {\n console.warn(\n `clean-jsdoc-theme: could not read footer file ('${file}'); omitting the custom footer.`\n );\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Resolve `opts.favicon` (a file path) into a served `_assets/` href + the file\n * to write — the bridge is the I/O layer, so dwar only sees the final URL and\n * `render()` stays pure. The asset name is content-hashed (cache-busted) unless\n * `hash` is off, and the source extension is preserved so dwar can derive the\n * `<link>` `type`. A missing/unreadable file is warned about and dropped\n * (resilient, like the logo/custom-asset paths). Exported for testing.\n */\nexport async function resolveFavicon(\n raw: unknown,\n hash: boolean,\n hrefForServed: (servedPath: string) => string\n): Promise<{ href: string; files: OutputFile[] } | undefined> {\n if (typeof raw !== 'string' || raw.trim().length === 0) return undefined;\n const trimmed = raw.trim();\n let bytes: Buffer;\n try {\n bytes = await readFile(resolvePath(trimmed));\n } catch {\n console.warn(`clean-jsdoc-theme: could not read favicon ('${trimmed}'); omitting it.`);\n return undefined;\n }\n const ext = extname(trimmed) || '.ico';\n const base = basename(trimmed, extname(trimmed)) || 'favicon';\n const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;\n const servedPath = `_assets/${name}`;\n // The OutputFile `path` stays relative; only the served href gets the prefix.\n return { href: hrefForServed(servedPath), files: [{ path: servedPath, contents: bytes }] };\n}\n\n/** Attributes that identify a `<meta>` tag (so an entry must carry at least one). */\nconst META_IDENTITY_ATTRS = ['name', 'property', 'http-equiv', 'charset', 'itemprop'] as const;\n\n/**\n * Validate `opts.meta` into a clean `MetaTag[]` (attribute maps), or `undefined`\n * when there's nothing usable. Accepts only an array of objects; within each,\n * keeps string→string pairs (trimming the value, coercing finite numbers to\n * strings for convenience) and drops the rest. An entry with no recognized\n * identifying attribute (`name`/`property`/`http-equiv`/`charset`/`itemprop`) is\n * dropped with a warning — dwar does the final escaping + key validation.\n */\nexport function normalizeMeta(raw: unknown): MetaTag[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: MetaTag[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;\n const o = entry as Record<string, unknown>;\n const tag: MetaTag = {};\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n const t = v.trim();\n if (t.length > 0) tag[k] = t;\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n tag[k] = String(v);\n }\n }\n const hasIdentity = META_IDENTITY_ATTRS.some((a) => typeof tag[a] === 'string');\n if (!hasIdentity || Object.keys(tag).length === 0) {\n console.warn(\n `clean-jsdoc-theme: skipping a meta entry with no usable name/property/http-equiv/charset attribute (${JSON.stringify(entry)}).`\n );\n continue;\n }\n out.push(tag);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/** A logo value that's already a servable URL/URI needs no copying. */\nfunction isServableUrl(value: string): boolean {\n return /^(https?:)?\\/\\//i.test(value) || /^data:/i.test(value);\n}\n\n/**\n * Resolve `opts.siteName` into a render-ready value plus any image files to\n * write. A string passes through (trimmed). For a logo set, each local image\n * path is read and emitted as a content-hashed output asset\n * (`_assets/logo-<key>.<hash><ext>`, cache-busted like the custom assets) with\n * its value rewritten to the served path; `http(s)://` / `data:` values pass\n * through untouched, and the `alt` label is preserved. A path that can't be\n * read is left verbatim with a warning rather than aborting the build.\n */\nasync function prepareSiteName(\n raw: string | SiteLogo | undefined,\n hrefForServed: (servedPath: string) => string\n): Promise<{ siteName: SiteName | undefined; files: OutputFile[] }> {\n if (typeof raw === 'string') {\n const trimmed = raw.trim();\n return { siteName: trimmed.length > 0 ? trimmed : undefined, files: [] };\n }\n if (!raw || typeof raw !== 'object') return { siteName: undefined, files: [] };\n\n const files: OutputFile[] = [];\n const out: SiteLogo = {};\n if (typeof raw.alt === 'string' && raw.alt.trim().length > 0) out.alt = raw.alt.trim();\n\n for (const key of ['default', 'dark', 'light'] as const) {\n const value = raw[key];\n if (typeof value !== 'string' || value.trim().length === 0) continue;\n const v = value.trim();\n\n if (isServableUrl(v)) {\n out[key] = v;\n continue;\n }\n\n try {\n const abs = resolvePath(v);\n const buf = await readFile(abs);\n const served = `_assets/logo-${key}.${contentHash(buf)}${extname(abs)}`;\n files.push({ path: served, contents: buf });\n // OutputFile `path` stays relative; only the served href gets the prefix.\n out[key] = hrefForServed(served);\n } catch {\n console.warn(\n `clean-jsdoc-theme: could not read logo image for siteName.${key} ('${v}'); using it verbatim.`\n );\n out[key] = v;\n }\n }\n\n const hasContent = out.default || out.dark || out.light || out.alt;\n return { siteName: hasContent ? out : undefined, files };\n}\n\n// Priority: opts.package file → taffy `kind:'package'` doclet → undefined.\nasync function resolvePkg(\n data: unknown,\n opts: JSDocOpts\n): Promise<SiteManifest['pkg'] | undefined> {\n if (typeof opts.package === 'string' && opts.package.length > 0) {\n try {\n const json = await readFile(opts.package, 'utf8');\n const parsed = JSON.parse(json) as Record<string, unknown>;\n return pickPkgFields(parsed);\n } catch {\n // fall through — try the taffy collection instead.\n }\n }\n\n // Probe the taffy collection for a `kind: 'package'` doclet without\n // taking a hard dependency on the salty API surface here.\n if (typeof data === 'function') {\n try {\n const pkgDoclets = (data as (q: unknown) => { get(): unknown[] })({ kind: 'package' }).get();\n if (Array.isArray(pkgDoclets) && pkgDoclets.length > 0) {\n return pickPkgFields(pkgDoclets[0] as Record<string, unknown>);\n }\n } catch {\n // ignore — collection isn't a salty DB or has no package doclet.\n }\n }\n\n return undefined;\n}\n\nfunction pickPkgFields(raw: Record<string, unknown>): SiteManifest['pkg'] {\n const pkg: SiteManifest['pkg'] = {};\n if (typeof raw.name === 'string') pkg.name = raw.name;\n if (typeof raw.version === 'string') pkg.version = raw.version;\n if (typeof raw.description === 'string') pkg.description = raw.description;\n if (typeof raw.homepage === 'string') pkg.homepage = raw.homepage;\n // `repository` may be a string or { url }; normalize to a string.\n if (typeof raw.repository === 'string') {\n pkg.repository = raw.repository;\n } else if (\n raw.repository &&\n typeof raw.repository === 'object' &&\n typeof (raw.repository as { url?: unknown }).url === 'string'\n ) {\n pkg.repository = (raw.repository as { url: string }).url;\n }\n return pkg;\n}\n\n/** Minimal view of JSDoc's `Tutorial` (jsdoc/lib/jsdoc/tutorial.js). */\ninterface JSDocTutorial {\n name?: unknown;\n title?: unknown;\n content?: unknown;\n type?: unknown;\n children?: unknown;\n}\n\n/**\n * Normalize JSDoc's tutorial resolver tree (the `tutorials` arg to `publish`)\n * into setu's plain {@link TutorialInput} shape. The root's `children` are the\n * top-level tutorials; each child carries its own `children`, so a depth-first\n * walk preserves the resolved hierarchy. Content is taken raw (`.content`);\n * `.type === 2` (MARKDOWN) is markdown, everything else is treated as HTML.\n */\nfunction normalizeTutorials(root: unknown): TutorialInput[] {\n const walk = (node: JSDocTutorial): TutorialInput | null => {\n const name = typeof node.name === 'string' ? node.name : '';\n if (!name) return null;\n const title = typeof node.title === 'string' && node.title.length > 0 ? node.title : name;\n const content = typeof node.content === 'string' ? node.content : '';\n const type = node.type === JSDOC_TUTORIAL_TYPE_MARKDOWN ? 'markdown' : 'html';\n const children = Array.isArray(node.children)\n ? (node.children as JSDocTutorial[]).map(walk).filter((t): t is TutorialInput => t !== null)\n : [];\n return { name, title, content, type, children };\n };\n\n const children = (root as JSDocTutorial | undefined)?.children;\n if (!Array.isArray(children)) return [];\n return (children as JSDocTutorial[]).map(walk).filter((t): t is TutorialInput => t !== null);\n}\n\n/**\n * Resolve JSDoc's `templates.default.outputSourceFiles` flag. The `opts` arg\n * `publish` receives is `env.opts` — the `opts` block — which does NOT carry the\n * root-level `templates` block, so we probe in priority order and default ON:\n * 1. `require('jsdoc/env').conf.templates.default.outputSourceFiles` (the\n * canonical location at runtime; wrapped in try/catch so a missing\n * `jsdoc/env` — e.g. in unit tests — never throws the build).\n * 2. `opts.templates.default.outputSourceFiles` (in case a user nests it\n * under `opts`).\n * Resolves to `false` ONLY when one of those is exactly `=== false`; otherwise\n * `true` (matching JSDoc's default-template default).\n */\nexport function outputSourceFilesEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { outputSourceFiles?: unknown } } };\n };\n if (env?.conf?.templates?.default?.outputSourceFiles === false) return false;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.outputSourceFiles === false) return false;\n return true;\n}\n\n/**\n * Resolve `templates.default.sourceLinkToComment`. Probed in the same priority\n * order as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a\n * nested `opts.templates` fallback). Resolves to `true` ONLY when one of those\n * is exactly `=== true`; otherwise `false` (the default: links jump to code).\n */\nexport function sourceLinkToCommentEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { sourceLinkToComment?: unknown } } };\n };\n if (env?.conf?.templates?.default?.sourceLinkToComment === true) return true;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.sourceLinkToComment === true) return true;\n return false;\n}\n\n/**\n * Resolve `templates.default.cleanOutputDir`. Probed in the same priority order\n * as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a nested\n * `opts.templates` fallback). Defaults to `true` — the build empties its\n * destination first so a page removed or renamed between runs (e.g. a deleted\n * class, or a stale content-hashed `styles.<hash>.css`) doesn't linger in the\n * served site. Resolves to `false` ONLY when one is exactly `=== false`.\n */\nexport function cleanOutputDirEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { cleanOutputDir?: unknown } } };\n };\n if (env?.conf?.templates?.default?.cleanOutputDir === false) return false;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.cleanOutputDir === false) return false;\n return true;\n}\n\n/**\n * Whether a JSDoc `conf.plugins` list enables the bundled `plugins/markdown`\n * plugin. The theme relies on it: JSDoc runs `plugins/markdown` to convert the\n * Markdown in doclet descriptions/tags to HTML *before* `publish` ever sees the\n * doclets, so without it descriptions arrive as raw Markdown and render wrong.\n * Pure + exported for testing — accepts the `plugins` array (module specifiers,\n * e.g. `\"plugins/markdown\"`; tolerant of a `.js` suffix or path separators).\n */\nexport function hasMarkdownPlugin(plugins: unknown): boolean {\n if (!Array.isArray(plugins)) return false;\n return plugins.some((p) => typeof p === 'string' && /(^|[\\\\/])markdown(\\.js)?$/i.test(p.trim()));\n}\n\n/**\n * Hard-require JSDoc's `plugins/markdown` plugin (see {@link hasMarkdownPlugin}).\n * Reads the merged config from `require('jsdoc/env').conf.plugins` — the\n * canonical location at runtime — and throws if the plugin is absent so the\n * build stops early with an actionable message. When `jsdoc/env` can't be\n * resolved (e.g. unit tests, or a non-JSDoc caller) the check is skipped: the\n * plugin list is unknowable there, so it can't be enforced.\n */\nfunction assertMarkdownPlugin(): void {\n let conf: { plugins?: unknown } | undefined;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n conf = (require('jsdoc/env') as { conf?: { plugins?: unknown } }).conf;\n } catch {\n return; // `jsdoc/env` isn't resolvable here — can't verify, so don't enforce.\n }\n if (!conf) return;\n if (!hasMarkdownPlugin(conf.plugins)) {\n throw new Error(\n 'clean-jsdoc-theme requires JSDoc\\'s \"plugins/markdown\" plugin, which ' +\n 'renders Markdown in doclet descriptions to HTML. Add it to your ' +\n 'jsdoc.json:\\n\\n \"plugins\": [\"plugins/markdown\"]\\n'\n );\n }\n}\n\n/**\n * Validate `opts.sectionOrder` into a clean `string[]`, or `undefined` to fall\n * back to setu's default order. Accepts only an array; trims string entries and\n * drops non-strings/empties. An array that yields no usable labels → `undefined`.\n */\nexport function normalizeSectionOrder(raw: unknown): string[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out = raw\n .filter((s): s is string => typeof s === 'string')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Validate `opts.menu` into a clean `MenuItem[]`, or `undefined` when there's no\n * usable menu. Accepts only an array of objects; trims string fields. The link\n * URL is read from `link` (preferred) or `href`. Keeps only actionable entries —\n * a built-in (`id`) or an external link (`link`/`href`).\n */\nexport function normalizeMenu(raw: unknown): MenuItem[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: MenuItem[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object') continue;\n const o = entry as Record<string, unknown>;\n const item: MenuItem = {};\n if (typeof o.id === 'string' && o.id.trim()) item.id = o.id.trim();\n if (typeof o.title === 'string' && o.title.trim()) item.title = o.title.trim();\n const link =\n typeof o.link === 'string' && o.link.trim()\n ? o.link.trim()\n : typeof o.href === 'string' && o.href.trim()\n ? o.href.trim()\n : undefined;\n if (link) item.link = link;\n if (typeof o.icon === 'string' && o.icon.trim()) item.icon = o.icon.trim();\n if (typeof o.target === 'string' && o.target.trim()) item.target = o.target.trim();\n if (typeof o.class === 'string' && o.class.trim()) item.class = o.class.trim();\n if (item.id || item.link) out.push(item);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/** Valid copy-page dropdown actions (mirrors setu/dwar's `CopyPageAction`). */\nconst COPY_PAGE_ACTIONS: readonly CopyPageAction[] = [\n 'copy',\n 'view',\n 'claude',\n 'chatgpt',\n 'perplexity',\n];\n\n/**\n * Validate `opts.copyPage` into a {@link CopyPageConfig}, or `undefined` to use\n * the defaults (enabled, all actions). Accepts a boolean shorthand (`false`\n * hides the button) or an object: `enabled` is read if boolean; `actions`, if an\n * array, is filtered to the known action ids (preserving order, dropping\n * unknowns/dupes) — an empty/all-invalid array still yields `[]` (primary button\n * only), which is meaningful and kept.\n */\nexport function normalizeCopyPage(raw: unknown): CopyPageConfig | undefined {\n if (raw === false) return { enabled: false };\n if (raw === true || raw == null) return undefined;\n if (typeof raw !== 'object') return undefined;\n\n const o = raw as Record<string, unknown>;\n const config: CopyPageConfig = {};\n if (typeof o.enabled === 'boolean') config.enabled = o.enabled;\n if (Array.isArray(o.actions)) {\n const seen = new Set<CopyPageAction>();\n for (const a of o.actions) {\n if (typeof a === 'string' && (COPY_PAGE_ACTIONS as readonly string[]).includes(a)) {\n seen.add(a as CopyPageAction);\n }\n }\n config.actions = COPY_PAGE_ACTIONS.filter((a) => seen.has(a));\n }\n return Object.keys(config).length > 0 ? config : undefined;\n}\n\n/**\n * Validate `opts.pageNav` into a {@link PageNavConfig}, or `undefined` to use the\n * default (enabled). Accepts a boolean shorthand (`false` hides the pager) or an\n * object whose `enabled` is read when boolean.\n */\nexport function normalizePageNav(raw: unknown): PageNavConfig | undefined {\n if (raw === false) return { enabled: false };\n if (raw === true || raw == null) return undefined;\n if (typeof raw !== 'object') return undefined;\n const enabled = (raw as Record<string, unknown>).enabled;\n return typeof enabled === 'boolean' ? { enabled } : undefined;\n}\n\n/** Valid code-playground providers (mirrors utils' `PlaygroundProvider`). */\nconst PLAYGROUND_PROVIDERS: readonly PlaygroundProvider[] = ['codepen', 'jsfiddle', 'codesandbox'];\n\n/** A site-wide per-provider options record, or `undefined` for a non-object. */\nfunction playgroundOptionRecord(raw: unknown): Record<string, unknown> | undefined {\n return raw && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Validate `opts.playground` into its two consumer slices, or `undefined` when\n * the feature is off (absent or `false`). `playground: true` / `{}` turns it on\n * with defaults — every provider available, opt-in per `@playground`. The\n * **`site`** slice feeds setu's `@playground` resolver (enablement + provider\n * selection); the **`theme`** slice becomes `ThemeConfig.playground` (the\n * site-wide per-provider runtime options dwar hands the browser island). Unknown\n * providers/keys are dropped (lenient, like {@link normalizeCopyPage}). setu\n * gates on the `site` slice's presence, so returning `undefined` keeps output\n * byte-identical.\n */\nexport function normalizePlayground(\n raw: unknown\n): { site: PlaygroundSiteConfig; theme: NonNullable<ThemeConfig['playground']> } | undefined {\n if (raw == null || raw === false) return undefined;\n const o = raw === true ? {} : raw;\n if (typeof o !== 'object' || Array.isArray(o)) return undefined;\n const obj = o as Record<string, unknown>;\n\n const site: PlaygroundSiteConfig = {};\n if (obj.enableForAllExamples === true) site.enableForAllExamples = true;\n if (Array.isArray(obj.providers)) {\n const providers: PlaygroundProvider[] = [];\n for (const p of obj.providers) {\n if (\n typeof p === 'string' &&\n (PLAYGROUND_PROVIDERS as readonly string[]).includes(p) &&\n !providers.includes(p as PlaygroundProvider)\n ) {\n providers.push(p as PlaygroundProvider);\n }\n }\n if (providers.length > 0) site.providers = providers;\n }\n\n const theme: NonNullable<ThemeConfig['playground']> = { enabled: true };\n const codepen = playgroundOptionRecord(obj.codepen);\n const jsfiddle = playgroundOptionRecord(obj.jsfiddle);\n const codesandbox = playgroundOptionRecord(obj.codesandbox);\n if (codepen) theme.codepen = codepen;\n if (jsfiddle) theme.jsfiddle = jsfiddle;\n if (codesandbox) theme.codesandbox = codesandbox;\n\n return { site, theme };\n}\n\n/** The palette keys a user may override under `opts.colors` / `opts.darkColors`. */\nconst COLOR_KEYS = [\n 'bg',\n 'bgMuted',\n 'fg',\n 'fgMuted',\n 'accent',\n 'accentFg',\n 'border',\n 'codeHeaderBg',\n 'codeHeaderFg',\n 'codeHighlightBg',\n] as const;\n\n/**\n * Validate a user `colors`/`darkColors` object from `jsdoc.json` into a clean\n * `Partial<ThemeColors>`: keeps only the known palette keys whose value is a\n * non-empty string, dropping everything else. Returns `undefined` when the input\n * is not an object or yields no usable keys, so callers can fall back cleanly.\n * Values are passed through verbatim (any CSS color is valid).\n */\nexport function normalizeColors(raw: unknown): Partial<ThemeColors> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const src = raw as Record<string, unknown>;\n const out: Partial<ThemeColors> = {};\n for (const key of COLOR_KEYS) {\n const v = src[key];\n if (typeof v === 'string' && v.trim().length > 0) out[key] = v.trim();\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Extensions we treat as \"source\" worth emitting a viewer page for. */\nconst SOURCE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']);\n\n/**\n * Compute project-relative paths for a set of absolute source paths by stripping\n * their longest common directory prefix. Returns a `Map<absPath, relPath>` with\n * `relPath` normalized to forward slashes. Pure + exported for testing.\n *\n * Windows-aware: paths are split on both `/` and `\\\\`, and segment comparison is\n * case-insensitive (NTFS is case-insensitive, and JSDoc's `meta.path` casing can\n * differ from disk). The single-file case yields just its basename. If the paths\n * share no common leading segment (e.g. different drives / UNC vs. drive), each\n * file falls back to its basename so the index stays sane.\n */\nexport function computeRelPaths(absPaths: readonly string[]): Map<string, string> {\n const out = new Map<string, string>();\n if (absPaths.length === 0) return out;\n\n const split = (p: string): string[] => p.split(/[\\\\/]+/).filter((s) => s.length > 0);\n const segLists = absPaths.map(split);\n\n // Longest common directory prefix (exclude the basename from the prefix so a\n // single file resolves to its own name, not the empty string).\n let common = segLists[0].slice(0, -1);\n for (let i = 1; i < segLists.length && common.length > 0; i++) {\n const segs = segLists[i];\n let j = 0;\n const max = Math.min(common.length, segs.length - 1);\n while (j < max && common[j].toLowerCase() === segs[j].toLowerCase()) j++;\n common = common.slice(0, j);\n }\n\n for (let i = 0; i < absPaths.length; i++) {\n const segs = segLists[i];\n const rel =\n common.length > 0 && segs.length > common.length\n ? segs.slice(common.length).join('/')\n : (segs[segs.length - 1] ?? absPaths[i]);\n out.set(absPaths[i], rel);\n }\n return out;\n}\n\n/**\n * Collect every source file referenced by a doclet's `meta` and read its\n * contents, ready to hand to setu as {@link SourceFileInput}s. `absPath` is the\n * exact `resolve(meta.path, meta.filename)` so setu's `Source: file:line`\n * matching (which joins the same fields) lines up. Files that can't be read are\n * warned about and skipped — never fatal. Returns sorted-by-`relPath` for\n * stable output.\n */\nasync function collectSourceFiles(data: unknown): Promise<SourceFileInput[]> {\n // Mirror resolvePkg's safe probe, but query ALL doclets (empty query).\n let doclets: unknown[] = [];\n if (typeof data === 'function') {\n try {\n doclets = (data as (q: unknown) => { get(): unknown[] })({}).get();\n } catch {\n try {\n doclets = (data as () => { get(): unknown[] })().get();\n } catch {\n doclets = [];\n }\n }\n }\n if (!Array.isArray(doclets) || doclets.length === 0) return [];\n\n // Unique absolute paths from doclet meta.\n const absSet = new Set<string>();\n for (const d of doclets) {\n const meta = (d as { meta?: { path?: unknown; filename?: unknown } } | undefined)?.meta;\n if (!meta || typeof meta.path !== 'string' || typeof meta.filename !== 'string') continue;\n const filename = meta.filename;\n // Skip obvious non-source by extension, but stay permissive (no ext → keep).\n const ext = extname(filename).toLowerCase();\n if (ext.length > 0 && !SOURCE_EXTENSIONS.has(ext)) continue;\n absSet.add(resolvePath(meta.path, filename));\n }\n if (absSet.size === 0) return [];\n\n const absPaths = [...absSet];\n const relPaths = computeRelPaths(absPaths);\n\n const inputs: SourceFileInput[] = [];\n for (const abs of absPaths) {\n try {\n const content = await readFile(abs, 'utf8');\n inputs.push({ absPath: abs, relPath: relPaths.get(abs) ?? abs, content });\n } catch (err) {\n console.warn(\n `clean-jsdoc-theme: could not read source file '${abs}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n\n inputs.sort((a, b) => a.relPath.localeCompare(b.relPath));\n return inputs;\n}\n\n/** Doc-file extensions → `DocInput.type`. Markdown is the priority; html maps to 'html'. */\nconst DOC_EXTENSIONS = new Map<string, DocInput['type']>([\n ['.md', 'markdown'],\n ['.markdown', 'markdown'],\n ['.html', 'html'],\n ['.htm', 'html'],\n]);\n\n/** Directory names skipped while walking a docs tree (build/vcs noise). */\nconst DOC_DIR_SKIP = new Set(['node_modules', '.git', '.svn', '.hg']);\n\n/**\n * Recursively walk a docs directory and read each Markdown/HTML file into a\n * {@link DocInput} for setu's docs front-end. Mirrors {@link collectSourceFiles}'s\n * safe-probe style:\n *\n * - `path` is the file path relative to `dir`, POSIX-normalized (forward slashes)\n * with the extension stripped (`<dir>/guides/advanced.md` → `'guides/advanced'`,\n * `<dir>/index.md` → `'index'`).\n * - `content` is the raw UTF-8 text (frontmatter stays embedded — setu parses it).\n * - `type` is `'markdown'` for `.md`/`.markdown`, `'html'` for `.html`/`.htm`.\n *\n * Resilient by design: a missing/unreadable directory yields `[]` (never throws);\n * dotfiles/dot-dirs and `node_modules`-like noise are skipped; a single\n * unreadable file is warned about and skipped. Results are sorted by `path` so\n * the output is stable build-to-build. Setu does no I/O — this is the only place\n * the docs tree is read.\n */\nexport async function collectDocs(dir: string): Promise<DocInput[]> {\n if (typeof dir !== 'string' || dir.trim().length === 0) return [];\n const root = resolvePath(dir);\n const docs: DocInput[] = [];\n\n const walk = async (absDir: string, relPrefix: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n // Missing/unreadable directory — skip leniently (root miss → []).\n return;\n }\n\n for (const entry of entries) {\n const name = entry.name;\n // Skip dotfiles/dot-dirs and known build/vcs noise.\n if (name.startsWith('.')) continue;\n if (entry.isDirectory()) {\n if (DOC_DIR_SKIP.has(name)) continue;\n await walk(joinPath(absDir, name), relPrefix ? `${relPrefix}/${name}` : name);\n continue;\n }\n if (!entry.isFile()) continue;\n\n const ext = extname(name).toLowerCase();\n const type = DOC_EXTENSIONS.get(ext);\n if (!type) continue;\n\n const abs = joinPath(absDir, name);\n const stem = name.slice(0, name.length - ext.length);\n const relPath = relPrefix ? `${relPrefix}/${stem}` : stem;\n try {\n const content = await readFile(abs, 'utf8');\n docs.push({ path: relPath, content, type });\n } catch (err) {\n console.warn(\n `clean-jsdoc-theme: could not read doc file '${abs}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n };\n\n await walk(root, '');\n\n // Deterministic order so the manifest is stable build-to-build.\n docs.sort((a, b) => a.path.localeCompare(b.path));\n return docs;\n}\n\n/** Markdown image: captures `![alt](`, the src, an optional `\"title\"`, and `)`. */\nconst DOC_IMAGE_RE = /(!\\[[^\\]]*\\]\\()([^)\\s]+)((?:\\s+\"[^\"]*\")?\\))/g;\n\n/**\n * HTML image: captures the `<img …src=` prefix (through the opening quote), the\n * quote char, the src value, and the closing quote (a backreference to the\n * opener). JSDoc's `plugins/markdown` renders a comment's `![alt](src)` to\n * `<img src=\"…\" alt=\"…\">`, and prose can embed raw `<img>`; this matches both\n * quote styles wherever `src` sits in the tag.\n */\nconst HTML_IMAGE_RE = /(<img\\b[^>]*?\\bsrc\\s*=\\s*([\"']))([^\"']*)(\\2)/gi;\n\n/**\n * A reusable local-image asset pipeline shared by every prose source (docs,\n * tutorials, README, doclet comments). `resolve(src, baseDir)` copies a local\n * image to `_assets/<base>.<hash><ext>` (content-hashed → cache-busted, deduped\n * across all sources via the shared caches) and returns the root-relative\n * `/_assets/…` href. It accumulates each copied file on `files`, each SVG's\n * markup on `inlineSvgs` (keyed by the rewritten href, so the renderer can inline\n * it — its `[data-theme]` styles then track the toggle), and the absolute source\n * path of every copied image on `consumed` (so the static-file passthrough can\n * skip re-copying an image it already served from `_assets/`).\n *\n * Resolution tries, in order: the doc-relative path (or project root for a\n * `/`-rooted src), then — for the JSDoc `staticFiles` convention — each\n * `staticDirs` root joined with the reference's output-relative name. So a bare\n * `![x](classes-io.png)` whose file lives in a declared `staticFiles` dir still\n * resolves and is hashed. External (`http(s):`, `data:`), `#`-anchor, and\n * fully-unresolvable srcs yield `null` (the last warned once) so callers leave\n * them untouched.\n */\nexport interface ImageCollector {\n resolve(rawSrc: string, baseDir: string): Promise<string | null>;\n readonly files: OutputFile[];\n readonly inlineSvgs: Record<string, string>;\n readonly consumed: Set<string>;\n}\n\nexport function createImageCollector(staticDirs: readonly string[] = []): ImageCollector {\n const files: OutputFile[] = [];\n const inlineSvgs: Record<string, string> = {};\n const consumed = new Set<string>();\n const seenServed = new Set<string>();\n // abs path → rewritten src (root-relative `/_assets/…`), or null if unreadable.\n const cache = new Map<string, string | null>();\n const warnedMisses = new Set<string>();\n\n const resolve = async (rawSrc: string, baseDir: string): Promise<string | null> => {\n const src = rawSrc.trim();\n if (!src || isServableUrl(src) || src.startsWith('#') || src.startsWith('data:')) return null;\n // Candidate absolute paths in priority order: the doc-relative / project-root\n // location first, then each staticFiles dir joined with the output-relative\n // name (leading slash stripped) as a fallback.\n const primary = src.startsWith('/') ? resolvePath(src.slice(1)) : resolvePath(baseDir, src);\n const candidates = [primary];\n if (staticDirs.length > 0) {\n const outName = src.replace(/^\\/+/, '');\n if (outName) for (const dir of staticDirs) candidates.push(resolvePath(dir, outName));\n }\n\n for (const abs of candidates) {\n const cached = cache.get(abs);\n if (cached !== undefined) {\n if (cached) return cached; // already copied\n continue; // known miss — try the next candidate\n }\n let bytes: Buffer;\n try {\n bytes = await readFile(abs);\n } catch {\n cache.set(abs, null);\n continue;\n }\n const ext = extname(abs);\n const served = `_assets/${basename(abs, ext) || 'asset'}.${contentHash(bytes)}${ext}`;\n if (!seenServed.has(served)) {\n seenServed.add(served);\n files.push({ path: served, contents: bytes });\n }\n const href = '/' + served;\n // SVGs are ALSO inlined: the renderer drops the markup into the page so its\n // `[data-theme=\"dark\"]` styles track the theme toggle (an `<img>`-loaded SVG\n // only sees the OS color scheme). A responsive sizing style is injected onto\n // the `<svg>` root; the `_assets/` copy still backs the companion `.md` link.\n if (ext.toLowerCase() === '.svg') {\n inlineSvgs[href] = bytes\n .toString('utf8')\n .replace(/<svg\\b/, '<svg style=\"max-width:100%;height:auto;display:block\"');\n }\n cache.set(abs, href);\n consumed.add(abs);\n return href;\n }\n\n if (!warnedMisses.has(src)) {\n warnedMisses.add(src);\n console.warn(\n `clean-jsdoc-theme: could not read image '${src}' (looked in: ${candidates.join(', ')}); leaving it as-is.`\n );\n }\n return null;\n };\n\n return { resolve, files, inlineSvgs, consumed };\n}\n\n/**\n * Rewrite the local image references in `content` to their content-hashed\n * `/_assets/…` paths, routing each through `collector`. Handles BOTH Markdown\n * `![alt](src)` and raw HTML `<img src=\"…\">` (JSDoc renders comment/tutorial\n * images to the latter), so prose in either form is covered. Relative srcs\n * resolve against `baseDir`, `/`-rooted srcs against the project root, and\n * external/`data:`/anchor srcs are left untouched. Returns the original string\n * unchanged when nothing was rewritten.\n */\n/**\n * Char ranges of Markdown/HTML **code** regions — fenced blocks (` ``` `/`~~~`),\n * HTML `<pre>`/`<code>`, and inline backtick spans. Image references inside these\n * are literal example syntax an author is *documenting*, not real images, so the\n * rewriter skips them (no spurious copy/rewrite, no \"could not read\" warning).\n * Order matters: the multi-line block forms come before the inline span so a\n * fence isn't chopped at its first inner backtick.\n */\nconst CODE_REGION_RE =\n /```[\\s\\S]*?```|~~~[\\s\\S]*?~~~|<pre[\\s\\S]*?<\\/pre>|<code[^>]*>[\\s\\S]*?<\\/code>|`[^`\\n]+`/gi;\n\n/** Collect the [start, end) char ranges of code regions in `content`. */\nfunction codeRanges(content: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n for (const m of content.matchAll(CODE_REGION_RE)) {\n if (m.index !== undefined) ranges.push([m.index, m.index + m[0].length]);\n }\n return ranges;\n}\n\n/** Whether char offset `idx` falls inside any of the (sorted-ish) code ranges. */\nfunction indexInCode(idx: number, ranges: ReadonlyArray<[number, number]>): boolean {\n for (const [s, e] of ranges) if (idx >= s && idx < e) return true;\n return false;\n}\n\nasync function rewriteImageRefs(\n content: string,\n baseDir: string,\n collector: ImageCollector\n): Promise<string> {\n if (!content) return content;\n const ranges = codeRanges(content);\n const map = new Map<string, string>();\n const collect = async (re: RegExp, srcGroup: number): Promise<void> => {\n for (const m of content.matchAll(re)) {\n if (m.index !== undefined && indexInCode(m.index, ranges)) continue; // example syntax\n const src = m[srcGroup];\n if (map.has(src)) continue;\n const href = await collector.resolve(src, baseDir);\n if (href) map.set(src, href);\n }\n };\n await collect(DOC_IMAGE_RE, 2);\n await collect(HTML_IMAGE_RE, 3);\n if (map.size === 0) return content;\n return content\n .replace(DOC_IMAGE_RE, (full, pre, src, post, offset: number) =>\n !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${post}` : full\n )\n .replace(HTML_IMAGE_RE, (full, pre, _quote, src, close, offset: number) =>\n !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${close}` : full\n );\n}\n\n/**\n * Resolve the local images a doc references and route them through the shared\n * content-hashed `_assets/` pipeline (see {@link createImageCollector}). Each\n * `![alt](src)` / `<img src>` whose `src` points to a file on disk is copied and\n * its `src` rewritten to the root-relative `/_assets/<base>.<hash><ext>` (rang's\n * `MdxImg` adds the base path, like it does for links), resolved relative to the\n * project root when it starts with `/`, else relative to the doc's own directory.\n * Returns the docs with rewritten content plus the asset files to write. The\n * bridge is the I/O layer here, so setu/dwar only ever see the final `_assets/`\n * paths.\n */\nexport async function resolveDocImages(\n docs: DocInput[],\n docsDir: string,\n collector: ImageCollector = createImageCollector()\n): Promise<{ docs: DocInput[]; files: OutputFile[]; inlineSvgs: Record<string, string> }> {\n if (docs.length === 0) return { docs, files: collector.files, inlineSvgs: collector.inlineSvgs };\n const root = resolvePath(docsDir);\n const out: DocInput[] = [];\n for (const doc of docs) {\n const docDir = dirname(resolvePath(root, doc.path));\n const content = await rewriteImageRefs(doc.content, docDir, collector);\n out.push(content === doc.content ? doc : { ...doc, content });\n }\n return { docs: out, files: collector.files, inlineSvgs: collector.inlineSvgs };\n}\n\n/**\n * Resolve the local images referenced by tutorial content, routing them through\n * the shared `collector` (the same content-hashed `_assets/` pipeline as docs).\n * JSDoc reads every tutorial from a single directory, so each tutorial's relative\n * srcs (`![x](../img/x.png)`, `<img src>`) resolve against `tutorialsDir`. Walks\n * the resolved tree (sub-tutorials included), rewriting each node's content —\n * Markdown or HTML; the tree shape is preserved. Returns a new tree (the input is\n * left untouched). Exported for testing.\n */\nexport async function resolveTutorialImages(\n tree: TutorialInput[],\n tutorialsDir: string,\n collector: ImageCollector\n): Promise<TutorialInput[]> {\n const base = resolvePath(tutorialsDir);\n const walk = async (node: TutorialInput): Promise<TutorialInput> => {\n const content = await rewriteImageRefs(node.content, base, collector);\n const children: TutorialInput[] = [];\n for (const child of node.children ?? []) children.push(await walk(child));\n return { ...node, content, children };\n };\n const out: TutorialInput[] = [];\n for (const node of tree) out.push(await walk(node));\n return out;\n}\n\n/**\n * Doclet keys whose string values are raw source/code/meta, NOT rendered prose —\n * never scanned for images (a stray `<img`/`![` there must not be rewritten).\n */\nconst DOCLET_IMAGE_SKIP_KEYS = new Set([\n 'meta',\n 'comment',\n 'examples',\n 'tags',\n '___id',\n '___s',\n]);\n\n/**\n * Recursively rewrite the `<img>`/`![]()` image srcs in every prose string\n * reachable from a doclet object, resolving against `baseDir`. Only strings that\n * actually carry an image marker (`<img` or `![`) are touched — a cheap guard so\n * names/identifiers/code are never scanned — and raw/code keys\n * ({@link DOCLET_IMAGE_SKIP_KEYS}) are skipped entirely. Recurses into nested\n * objects/arrays (e.g. `params[].description`). Mutates `node` in place.\n */\nasync function rewriteDocletStrings(\n node: Record<string, unknown>,\n baseDir: string,\n collector: ImageCollector\n): Promise<void> {\n for (const [key, value] of Object.entries(node)) {\n if (DOCLET_IMAGE_SKIP_KEYS.has(key)) continue;\n if (typeof value === 'string') {\n if (value.includes('<img') || value.includes('![')) {\n const rewritten = await rewriteImageRefs(value, baseDir, collector);\n if (rewritten !== value) node[key] = rewritten;\n }\n } else if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n if (typeof item === 'string') {\n if (item.includes('<img') || item.includes('![')) {\n const rewritten = await rewriteImageRefs(item, baseDir, collector);\n if (rewritten !== item) value[i] = rewritten;\n }\n } else if (item && typeof item === 'object') {\n await rewriteDocletStrings(item as Record<string, unknown>, baseDir, collector);\n }\n }\n } else if (value && typeof value === 'object') {\n await rewriteDocletStrings(value as Record<string, unknown>, baseDir, collector);\n }\n }\n}\n\n/**\n * Resolve the local images referenced inside JSDoc-comment prose (doclet\n * descriptions, `@classdesc`, nested `@param`/`@property`/`@returns`\n * descriptions, …) and route them through the shared `collector`. JSDoc's\n * `plugins/markdown` has already turned a comment's `![alt](../img/x.png)` into\n * an HTML `<img src=\"../img/x.png\">` by the time `publish` runs, so each src is\n * resolved **relative to that doclet's own source file** (`meta.path` — the\n * directory of the file the comment lives in). Doclets are mutated IN PLACE:\n * salty's `get()` hands out live object references, so the rewrite is visible\n * when setu later reads the same collection. Resilient — a non-collection `data`\n * or unreadable image is skipped (the latter warned), never fatal.\n */\nexport async function resolveDocletImages(\n data: unknown,\n collector: ImageCollector\n): Promise<void> {\n if (typeof data !== 'function') return;\n let doclets: unknown[] = [];\n try {\n doclets = (data as (q: unknown) => { get(): unknown[] })({}).get();\n } catch {\n try {\n doclets = (data as () => { get(): unknown[] })().get();\n } catch {\n return;\n }\n }\n if (!Array.isArray(doclets)) return;\n\n for (const d of doclets) {\n if (!d || typeof d !== 'object') continue;\n const meta = (d as { meta?: { path?: unknown } }).meta;\n // Without the source file's directory there's no base to resolve a relative\n // src against, so skip (synthetic/global doclets often carry no meta.path).\n if (!meta || typeof meta.path !== 'string' || meta.path.length === 0) continue;\n await rewriteDocletStrings(d as Record<string, unknown>, meta.path, collector);\n }\n}\n\n// ─── JSDoc `templates.default.staticFiles` passthrough ──────────────────────\n//\n// JSDoc's default template copies arbitrary files into the output via\n// `templates.default.staticFiles` (an include dir's CONTENTS land at the output\n// root). The theme honors that contract: matched files are copied verbatim\n// (covering non-image assets and references the image pipeline doesn't scan),\n// and the include dirs additionally become fallback search roots so a bare image\n// reference like `![x](classes-io.png)` — which only worked in stock JSDoc\n// because the file was copied to the flat output root — resolves through the\n// content-hashed `_assets/` pipeline here (v5 pages are nested, so the reference\n// also has to be rewritten, not just the file copied).\n\n/** Normalized `templates.default.staticFiles` config. */\nexport interface StaticFilesConfig {\n /** Resolved-as-given include paths (dirs or files), trimmed, non-empty. */\n include: string[];\n /** Paths to exclude (a file equal to, or under, an excluded dir is dropped). */\n exclude: string[];\n /** Regex (source string) a file's POSIX abs path must match to be included. */\n includePattern?: string;\n /** Regex (source string) that drops a file when its POSIX abs path matches. */\n excludePattern?: string;\n}\n\n/**\n * Normalize a raw `staticFiles` block into a {@link StaticFilesConfig}, or\n * `undefined` when there's nothing to include. `include`/`exclude` accept a\n * string or string[]; patterns are kept as source strings (compiled later, so a\n * bad pattern fails open rather than throwing). Pure + exported for testing.\n */\nexport function normalizeStaticFilesConfig(raw: unknown): StaticFilesConfig | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const o = raw as Record<string, unknown>;\n const toStrArr = (v: unknown): string[] =>\n (Array.isArray(v) ? v : typeof v === 'string' ? [v] : [])\n .filter((s): s is string => typeof s === 'string' && s.trim().length > 0)\n .map((s) => s.trim());\n const include = toStrArr(o.include);\n if (include.length === 0) return undefined;\n const includePattern =\n typeof o.includePattern === 'string' && o.includePattern.trim().length > 0\n ? o.includePattern\n : undefined;\n const excludePattern =\n typeof o.excludePattern === 'string' && o.excludePattern.trim().length > 0\n ? o.excludePattern\n : undefined;\n return {\n include,\n exclude: toStrArr(o.exclude),\n ...(includePattern ? { includePattern } : {}),\n ...(excludePattern ? { excludePattern } : {}),\n };\n}\n\n/**\n * Read `templates.default.staticFiles` from JSDoc's canonical `jsdoc/env` conf\n * (the only place the root-level `templates` block lives at runtime), falling\n * back to a nested `opts.templates.default.staticFiles`. Mirrors the probe order\n * of {@link outputSourceFilesEnabled}. Returns `undefined` when unset/unusable.\n */\nexport function readStaticFilesConfig(opts: JSDocOpts): StaticFilesConfig | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { staticFiles?: unknown } } };\n };\n const fromEnv = normalizeStaticFilesConfig(env?.conf?.templates?.default?.staticFiles);\n if (fromEnv) return fromEnv;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n return normalizeStaticFilesConfig(opts?.templates?.default?.staticFiles);\n}\n\n/**\n * Output-relative path (POSIX) for a static file under an include root: strip the\n * resolved-root prefix so `<root>/img/sub/x.png` under root `<root>/img` →\n * `sub/x.png` (JSDoc maps an include dir's contents to the output ROOT). When the\n * include was a single FILE (`absFile === includeRootAbs`), the output name is its\n * basename. Windows-aware: separators are normalized and the prefix match is\n * case-insensitive (NTFS). Pure + exported for testing.\n */\nexport function staticFileOutputName(absFile: string, includeRootAbs: string): string {\n const norm = (p: string): string => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const f = norm(absFile);\n const root = norm(includeRootAbs);\n const baseOf = (p: string): string => p.slice(p.lastIndexOf('/') + 1);\n if (f === root) return baseOf(f); // single-file include\n const prefix = root + '/';\n return f.toLowerCase().startsWith(prefix.toLowerCase()) ? f.slice(prefix.length) : baseOf(f);\n}\n\n/**\n * Whether a static file passes a config's filter — `includePattern` (must match),\n * `excludePattern` (must not match), and `exclude` (file equal to, or nested\n * under, an excluded path is dropped). Patterns are tested against the file's\n * POSIX-normalized absolute path; a malformed pattern fails open (ignored). Pure\n * + exported for testing.\n */\nexport function staticFileIncluded(absFile: string, config: StaticFilesConfig): boolean {\n const norm = (p: string): string => resolvePath(p).replace(/\\\\/g, '/');\n const fn = norm(absFile);\n if (config.includePattern) {\n try {\n if (!new RegExp(config.includePattern).test(fn)) return false;\n } catch {\n /* bad pattern → ignore (fail open) */\n }\n }\n if (config.excludePattern) {\n try {\n if (new RegExp(config.excludePattern).test(fn)) return false;\n } catch {\n /* bad pattern → ignore */\n }\n }\n for (const ex of config.exclude) {\n const exAbs = norm(ex);\n if (fn === exAbs || fn.toLowerCase().startsWith(exAbs.toLowerCase() + '/')) return false;\n }\n return true;\n}\n\n/** Directory names skipped while walking a staticFiles tree (build/vcs noise). */\nconst STATIC_DIR_SKIP = new Set(['node_modules', '.git', '.svn', '.hg']);\n\n/** One verbatim static-file copy entry. */\nexport interface StaticFileEntry {\n /** Output-relative POSIX path (where it lands under the destination). */\n outputPath: string;\n /** Absolute source path (matched against the image collector's `consumed`). */\n absSource: string;\n contents: Buffer;\n}\n\n/**\n * Collect the files matched by a {@link StaticFilesConfig}: walk each include\n * path (a directory recursively, or a single file), apply\n * {@link staticFileIncluded}, and read each match. Returns the verbatim copy\n * entries (output path = include-root-stripped, JSDoc's \"contents → output root\"\n * mapping) plus the resolved `searchDirs` the image resolver uses as fallback\n * roots (an include dir as-is; a file include's parent dir). Resilient: a missing\n * include path / unreadable file is warned + skipped, never fatal. Exported for\n * testing.\n */\nexport async function collectStaticFiles(\n config: StaticFilesConfig,\n warn: (message: string) => void = (m) => console.warn(m)\n): Promise<{ files: StaticFileEntry[]; searchDirs: string[] }> {\n const files: StaticFileEntry[] = [];\n const searchDirs = new Set<string>();\n const seenOutput = new Set<string>(); // de-dup output paths across include roots\n\n for (const inc of config.include) {\n const root = resolvePath(inc);\n let st: import('node:fs').Stats;\n try {\n st = await stat(root);\n } catch {\n warn(\n `clean-jsdoc-theme: staticFiles include '${inc}' (resolved '${root}') was not found; skipping it.`\n );\n continue;\n }\n\n if (st.isDirectory()) {\n searchDirs.add(root);\n const walk = async (absDir: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.')) continue;\n const abs = joinPath(absDir, entry.name);\n if (entry.isDirectory()) {\n if (!STATIC_DIR_SKIP.has(entry.name)) await walk(abs);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!staticFileIncluded(abs, config)) continue;\n const outputPath = staticFileOutputName(abs, root);\n if (seenOutput.has(outputPath)) continue;\n let contents: Buffer;\n try {\n contents = await readFile(abs);\n } catch (err) {\n warn(\n `clean-jsdoc-theme: could not read static file '${abs}' — ${(err as Error).message}; skipping.`\n );\n continue;\n }\n seenOutput.add(outputPath);\n files.push({ outputPath, absSource: resolvePath(abs), contents });\n }\n };\n await walk(root);\n } else if (st.isFile()) {\n // A file include's parent dir is the search root, so the image resolver can\n // find it by the bare output name (its basename).\n searchDirs.add(dirname(root));\n if (!staticFileIncluded(root, config)) continue;\n const outputPath = staticFileOutputName(root, root);\n if (!seenOutput.has(outputPath)) {\n try {\n const contents = await readFile(root);\n seenOutput.add(outputPath);\n files.push({ outputPath, absSource: resolvePath(root), contents });\n } catch (err) {\n warn(\n `clean-jsdoc-theme: could not read static file '${root}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n }\n }\n\n // Deterministic order so the manifest/output is stable build-to-build.\n files.sort((a, b) => a.outputPath.localeCompare(b.outputPath));\n return { files, searchDirs: [...searchDirs] };\n}\n\n/** The output of {@link resolveDocImages}: resolved docs + their image assets. */\nexport interface ResolvedDocs {\n docs: DocInput[];\n files: OutputFile[];\n inlineSvgs: Record<string, string>;\n}\n\n/**\n * Overlay a locale's resolved docs over the default set (the per-locale docs\n * track). A locale page WINS over the default page with the same `path`; a\n * default page absent from the locale falls back (stays). Image asset files are\n * deduped by served path (same content-hashed name → one copy), and inline SVGs\n * merge locale-over-default. Output docs are re-sorted by `path` so the manifest\n * stays stable regardless of merge order. Pure — the I/O already happened in the\n * two {@link resolveDocImages} calls that produced `base`/`locale`.\n */\nexport function overlayDocs(base: ResolvedDocs, locale: ResolvedDocs): ResolvedDocs {\n const byPath = new Map(base.docs.map((d) => [d.path, d]));\n for (const d of locale.docs) byPath.set(d.path, d); // locale wins; default falls back\n const filesByPath = new Map<string, OutputFile>();\n for (const f of [...base.files, ...locale.files]) filesByPath.set(f.path, f); // dedupe\n return {\n docs: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)),\n files: [...filesByPath.values()],\n inlineSvgs: { ...base.inlineSvgs, ...locale.inlineSvgs },\n };\n}\n\n/**\n * Validate `opts.docGroups` into a clean `string[]`, or `undefined` to fall back\n * to setu's default doc-group order. Mirrors {@link normalizeSectionOrder}:\n * accepts only an array; trims string entries and drops non-strings/empties.\n */\nexport function normalizeDocGroups(raw: unknown): string[] | undefined {\n return normalizeSectionOrder(raw);\n}\n\n/** Format an elapsed-ms span compactly: `840ms` under a second, else `5.2s`. */\nfunction formatElapsed(ms: number): string {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Handle a stage's `fn` can use to report sub-step progress on the spinner. */\ninterface StageHandle {\n /** Replace the live spinner label mid-stage (no-op when progress is off). */\n setText(text: string): void;\n}\n\n/**\n * Build-stage narrator backed by `ora`. The setu→dwar pipeline does much more\n * than a bare jsdoc run (per-page MDX compile, per-island esbuild bundling), so\n * a 7–8s build can otherwise look hung. `stage(label, fn)`\n * starts an ora spinner, runs `fn`, then resolves it to `✔ <label> (<elapsed>)`\n * on success or `✖ <label>` on failure. ora handles the spinner animation, TTY\n * detection (no animation when piped/CI), and the success/fail symbols.\n *\n * The catch: ora animates its frame on a `setInterval`, but each stage does\n * heavy *synchronous* work (module evaluation during the dynamic `import()`,\n * per-page MDX compile/SSR) that blocks the event loop — so the interval can't\n * fire and the spinner freezes on one frame, looking hung. Two things keep it\n * visibly alive: an elapsed-seconds **heartbeat** appended to the label (so it\n * advances whenever the loop breathes — module-graph I/O gaps, esbuild\n * subprocess waits), and the `setText` handle, which long stages use to report\n * their current sub-step (e.g. the renderer load steps setu → dwar → utils).\n *\n * `ora` is `null` when progress is disabled (`opts.progress === false`) or the\n * package couldn't be loaded — then `stage` just runs `fn` with no output.\n */\nfunction createBuildProgress(ora: OraFactory | null) {\n async function stage<T>(label: string, fn: (handle: StageHandle) => T | Promise<T>): Promise<T> {\n const noop: StageHandle = { setText: () => {} };\n if (!ora) return await fn(noop);\n const spinner = ora(label).start();\n const begin = Date.now();\n let current = label;\n // Refresh the spinner text with the current sub-step + elapsed seconds. ora\n // repaints on its own interval, so this only shows once the event loop is\n // free, but it means a long stage advances rather than sitting on one frame.\n const refresh = () => {\n const secs = Math.floor((Date.now() - begin) / 1000);\n spinner.text = secs > 0 ? `${current} (${secs}s)` : current;\n };\n const heartbeat = setInterval(refresh, 1000);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n const handle: StageHandle = {\n setText(text) {\n current = text;\n refresh();\n },\n };\n try {\n const result = await fn(handle);\n clearInterval(heartbeat);\n spinner.succeed(`${label} (${formatElapsed(Date.now() - begin)})`);\n return result;\n } catch (err) {\n clearInterval(heartbeat);\n spinner.fail(label);\n throw err;\n }\n }\n\n return { stage };\n}\n\n/** A per-locale render spec (utils' `BuildSpec`) written by `aadesh build`. */\ninterface BuildSpec {\n locale: string;\n defaultLocale: string;\n apiMessages: Record<string, string>;\n chromeMessages: Record<string, string>;\n destination: string;\n basePath: string;\n siteBasePath: string;\n locales: Array<{ code: string; name?: string }>;\n /** Absolute path of this locale's docs-overlay dir (`docs.<locale>/`), if any. */\n docsDir?: string;\n}\n\n/**\n * Read the localization build spec when `CLEAN_JSDOC_THEME_BUILD` points at one\n * (set by `aadesh build` per locale). When present, the theme stamps the API\n * translations and renders to the spec's `destination`/`basePath` instead of the\n * jsdoc.json values. Returns `null` for a normal (single-locale) build.\n */\nfunction readBuildSpec(): BuildSpec | null {\n const path = process.env.CLEAN_JSDOC_THEME_BUILD?.trim();\n if (!path) return null;\n const spec = JSON.parse(readFileSync(path, 'utf8')) as Partial<BuildSpec> & { version?: number };\n // Must match utils' BUILD_SPEC_VERSION — guards an old theme vs new aadesh mix.\n if (typeof spec.version === 'number' && spec.version !== 1) {\n throw new Error(\n `clean-jsdoc-theme: build spec version ${spec.version} unsupported ` +\n `(expected 1) — update clean-jsdoc-theme and aadesh together.`\n );\n }\n if (typeof spec.destination !== 'string' || typeof spec.basePath !== 'string') {\n throw new Error(`clean-jsdoc-theme: malformed build spec at \"${path}\".`);\n }\n return {\n locale: typeof spec.locale === 'string' ? spec.locale : '',\n defaultLocale: typeof spec.defaultLocale === 'string' ? spec.defaultLocale : 'en',\n apiMessages: spec.apiMessages ?? {},\n chromeMessages: spec.chromeMessages ?? {},\n destination: spec.destination,\n basePath: spec.basePath,\n siteBasePath: typeof spec.siteBasePath === 'string' ? spec.siteBasePath : '/',\n locales: Array.isArray(spec.locales) ? spec.locales : [],\n ...(typeof spec.docsDir === 'string' && spec.docsDir ? { docsDir: spec.docsDir } : {}),\n };\n}\n\nexport async function publish(data: unknown, opts: JSDocOpts, tutorials?: unknown): Promise<void> {\n // Localization build mode (aadesh): a per-locale spec overrides the output\n // destination + base path and supplies the API translations to stamp in.\n const buildSpec = readBuildSpec();\n const destination = buildSpec?.destination ?? opts.destination;\n if (!destination || typeof destination !== 'string') {\n throw new Error(\n 'clean-jsdoc-theme publish: opts.destination is required ' +\n '(set \"opts.destination\" in your jsdoc.json).'\n );\n }\n\n // The theme depends on JSDoc's `plugins/markdown` to pre-render doclet\n // Markdown to HTML; bail early with an actionable message if it's missing.\n assertMarkdownPlugin();\n\n // Color only on a real TTY (and unless JSDoc's `--nocolor` is set).\n const color = Boolean(process.stdout.isTTY) && opts.nocolor !== true;\n\n // Kick off the project file-reading I/O NOW, so it runs concurrently with the\n // renderer load below. None of it (pkg resolution, source files, the docs\n // tree) needs setu/dwar/utils, so on large projects — where reading hundreds\n // of source files is non-trivial — it overlaps the multi-second module\n // evaluation instead of running serially after it. These collectors are\n // internally resilient (unreadable files are warned + skipped, never thrown),\n // so starting them before their await point can't surface an unhandled\n // rejection; we await them at their narrated stages below.\n const docsDir =\n typeof opts.docs === 'string' && opts.docs.trim().length > 0 ? opts.docs.trim() : undefined;\n const tutorialsDir =\n typeof opts.tutorials === 'string' && opts.tutorials.trim().length > 0\n ? opts.tutorials.trim()\n : undefined;\n // JSDoc's `templates.default.staticFiles` (verbatim passthrough + image search\n // fallback roots). `undefined` when unset, so the whole feature is inert then.\n const staticCfg = readStaticFilesConfig(opts);\n const pkgPromise = resolvePkg(data, opts);\n const sourcesPromise: Promise<SourceFileInput[]> = outputSourceFilesEnabled(opts)\n ? collectSourceFiles(data)\n : Promise.resolve([]);\n const docsPromise: Promise<DocInput[]> = docsDir ? collectDocs(docsDir) : Promise.resolve([]);\n\n // Stage progress (ora spinners) is on by default; `opts.progress: false`\n // silences it. ora loads first so the narrator can wrap the renderer load\n // (stage 1) too; a load failure degrades to silent rather than breaking.\n const ora = opts.progress === false ? null : await loadOra();\n const progress = createBuildProgress(ora);\n\n const [\n { generateSite, stampSite },\n { render },\n {\n validateThemeOpts,\n createGoogleFontResolver,\n formatDiagnostics,\n warningsOnly,\n formatBuildReport,\n formatRenderError,\n normalizeBasePath,\n withBase,\n toExtractManifest,\n normalizeCollapsibleSidebarSections,\n unmatchedCollapsibleSections,\n topLevelSectionLabels,\n normalizeScrollbar,\n },\n // Loaded sequentially (not Promise.all) so the spinner can step its label\n // through each module — the evaluation of these large ESM bundles is the\n // single longest, most event-loop-blocking stage, so visibly naming the\n // module in flight is what stops it from reading as a hang.\n ] = await progress.stage('Loading renderer', async ({ setText }) => {\n setText('Loading renderer (setu)');\n const setu = await loadSetu();\n setText('Loading renderer (dwar)');\n const dwar = await loadDwar();\n setText('Loading renderer (utils)');\n const utils = await loadUtils();\n return [setu, dwar, utils] as const;\n });\n\n // Normalized base-path prefix (`/` when unset). Threaded into every emitted\n // href — logos and custom assets here; dwar prefixes the rest at render time.\n const basePath = normalizeBasePath(buildSpec?.basePath ?? opts.basePath);\n // The OutputFile `path` stays relative; only the served href gets the prefix.\n const hrefForServed = (servedPath: string): string => withBase(basePath, '/' + servedPath);\n\n // Validate the theme options early (before any render work) so the developer\n // sees problems first. The Google-Font check is the one networked piece, kept\n // behind an injectable resolver in utils; it's fail-open, so an offline build\n // never breaks on it. Unknown keys get typo suggestions (`suggest-typos`),\n // never blanket warnings — JSDoc's own opts share this flat namespace.\n const fontResolver = createGoogleFontResolver();\n const { value, diagnostics } = await progress.stage('Validating options', () =>\n validateThemeOpts({\n opts,\n fontResolver,\n unknownKeyPolicy: 'suggest-typos',\n knownNonThemeKeys: JSDOC_OWN_OPTS,\n })\n );\n\n // Strict mode: `opts.strict` (or nested `templates.default.strict`). When on\n // AND there are errors, log + throw to fail the build. Otherwise (the\n // resilient default) log and continue — a bad font/typo never breaks a build.\n const strict =\n opts.strict === true ||\n (opts.templates as { default?: { strict?: unknown } } | undefined)?.default?.strict === true;\n\n if (diagnostics.list.length > 0) {\n const formatted = formatDiagnostics(diagnostics, { color });\n if (strict && diagnostics.hasErrors()) {\n console.error(formatted);\n throw new Error(\n 'clean-jsdoc-theme: opts validation failed in strict mode ' +\n '(see the diagnostics above). Fix the errors or unset `strict`.'\n );\n }\n console.log(formatted);\n }\n\n // Resolved off the kickoff above (started concurrently with the renderer load).\n const pkg = await pkgPromise;\n\n // README (rendered to HTML by JSDoc into `opts.readme`) → home page; the\n // tutorials resolver tree → guide pages. Both flow through setu as ordinary\n // pages. Local images they reference (and those in JSDoc-comment prose) are\n // routed through the `_assets/` pipeline below, like `opts.docs` images.\n const readme =\n typeof opts.readme === 'string' && opts.readme.length > 0 ? opts.readme : undefined;\n const tutorialTree = normalizeTutorials(tutorials);\n\n // Source viewer pages + `Source: file:line` member links. Gated behind\n // JSDoc's `templates.default.outputSourceFiles` (default ON); reading files\n // is optional and self-skips on error, so this never aborts the build.\n const sourceLinkToComment = sourceLinkToCommentEnabled(opts);\n\n // The docs tree → prose pages at clean (unprefixed) slugs; `docGroups` orders\n // the doc-group sidebar sections, `defaultDocGroup` labels ungrouped docs. The\n // reads were started in the kickoff above (the bridge is the sanctioned I/O\n // layer; setu stays disk-free), so this stage just awaits the now-overlapped\n // work — narrated as a single step.\n // JSDoc `templates.default.staticFiles` passthrough: collect the included\n // files up front. Their dirs become fallback search roots for image resolution\n // (so a bare `![x](classes-io.png)` whose file lives in a staticFiles dir still\n // resolves + hashes), and the files themselves are copied verbatim to the\n // output after render (covering non-image assets). Read once; `undefined` when\n // the option is unset, so nothing changes for projects that don't use it.\n const staticFiles = staticCfg\n ? await progress.stage('Reading static files', () =>\n collectStaticFiles(staticCfg, (m) => console.warn(m))\n )\n : undefined;\n\n // ONE image collector for the whole build: docs, tutorials, README, and doclet\n // comments all route their local images through it (content-hashed `_assets/`,\n // SVG-inlined, deduped across sources). `staticFiles.searchDirs` are the B2\n // fallback roots. `consumed` (the source paths it copied) lets the verbatim\n // static-file pass skip images it already served from `_assets/`.\n const images = createImageCollector(staticFiles?.searchDirs ?? []);\n\n const { sources, docs } = await progress.stage('Reading sources & docs', async () => {\n const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);\n // Route the local images those docs reference through the shared collector\n // (copy + rewrite the src), so they cache-bust like the logo/custom assets.\n const base = docsDir\n ? await resolveDocImages(rawDocs, docsDir, images)\n : { docs: rawDocs };\n\n // Per-locale docs overlay (build mode): a locale's `docs.<locale>/` files win\n // over the default docs by path; default-only docs fall back. Both sets'\n // images accumulate on the shared collector; overlayDocs merges the content.\n if (!buildSpec?.docsDir) return { sources: srcs, docs: base.docs };\n const localeRaw = await collectDocs(buildSpec.docsDir);\n const locale = await resolveDocImages(localeRaw, buildSpec.docsDir, images);\n const merged = overlayDocs(\n { docs: base.docs, files: [], inlineSvgs: {} },\n { docs: locale.docs, files: [], inlineSvgs: {} }\n );\n return { sources: srcs, docs: merged.docs };\n });\n\n // Tutorials, the README, and JSDoc-comment (doclet) prose can all reference\n // local images with relative paths (`![x](../img/x.png)` / `<img src>`); route\n // them through the SAME shared collector. Tutorials resolve against the\n // tutorials dir, the README against the project root (its usual home), and each\n // doclet's images against its own source file's directory. Doclets are mutated\n // IN PLACE (salty hands out live references) BEFORE `generateSite`/`stampSite`\n // reads them.\n const { tutorialTree: resolvedTutorials, readme: resolvedReadme } = await progress.stage(\n 'Resolving prose images',\n async () => {\n const tree =\n tutorialsDir && tutorialTree.length > 0\n ? await resolveTutorialImages(tutorialTree, tutorialsDir, images)\n : tutorialTree;\n const md = readme ? await rewriteImageRefs(readme, process.cwd(), images) : readme;\n await resolveDocletImages(data, images);\n return { tutorialTree: tree, readme: md };\n }\n );\n\n // Every source's image assets now live on the one shared collector, deduped by\n // served path; the inline-SVG map is keyed by rewritten src for the renderer.\n const imageFiles = images.files;\n const allInlineSvgs = images.inlineSvgs;\n\n const docGroups = normalizeDocGroups(opts.docGroups);\n const defaultDocGroup =\n typeof opts.defaultDocGroup === 'string' && opts.defaultDocGroup.trim().length > 0\n ? opts.defaultDocGroup.trim()\n : undefined;\n\n // Sidebar config: `menu` (full control) takes precedence over `sectionOrder`.\n // Each accepts only well-formed input; anything else falls back to defaults.\n const sectionOrder = normalizeSectionOrder(opts.sectionOrder);\n const menu = normalizeMenu(opts.menu);\n const clubSidebarItems = opts.clubSidebarItems === true;\n const { value: collapsibleSidebarSections, warnings: collapsibleWarnings } =\n normalizeCollapsibleSidebarSections(opts.collapsibleSidebarSections);\n collapsibleWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));\n // Scrollbar presentation mode (see #281); an unrecognized value warns and\n // falls back to `undefined`, so dwar defaults to `styled`.\n const { value: scrollbar, warnings: scrollbarWarnings } = normalizeScrollbar(opts.scrollbar);\n scrollbarWarnings.forEach((w) => console.warn(`clean-jsdoc-theme: ${w}`));\n // The enablement slice (provider selection + enableForAllExamples) gates setu's\n // `@playground` handling; the runtime slice is threaded into the theme instead.\n const playground = normalizePlayground(opts.playground);\n\n const siteOptions = {\n ...(pkg ? { pkg } : {}),\n ...(resolvedReadme ? { readme: resolvedReadme } : {}),\n ...(resolvedTutorials.length > 0 ? { tutorials: resolvedTutorials } : {}),\n ...(sources.length > 0 ? { sources } : {}),\n ...(sources.length > 0 && sourceLinkToComment ? { sourceLinkToComment } : {}),\n ...(docs.length > 0 ? { docs } : {}),\n ...(docGroups ? { docGroups } : {}),\n ...(defaultDocGroup ? { defaultDocGroup } : {}),\n ...(sectionOrder ? { sectionOrder } : {}),\n ...(menu ? { menu } : {}),\n ...(clubSidebarItems ? { clubSidebarItems } : {}),\n ...(collapsibleSidebarSections !== undefined ? { collapsibleSidebarSections } : {}),\n ...(playground ? { playground: playground.site } : {}),\n };\n // Build mode stamps the locale's API translations in; a normal build doesn't.\n const manifest = await progress.stage('Generating pages', () =>\n buildSpec\n ? stampSite(data, buildSpec.apiMessages, siteOptions)\n : generateSite(data, siteOptions)\n );\n\n if (Array.isArray(collapsibleSidebarSections)) {\n const present = topLevelSectionLabels(manifest.nav);\n const unmatched = unmatchedCollapsibleSections(collapsibleSidebarSections, present);\n if (unmatched.length > 0) {\n console.warn(\n `clean-jsdoc-theme: collapsibleSidebarSections — no sidebar section matches ` +\n `${unmatched.map((l) => `'${l}'`).join(', ')}. ` +\n `Available sections: ${present.join(', ')}.`\n );\n }\n }\n\n // Localization extract mode (aadesh, Phase 3): when CLEAN_JSDOC_THEME_EXTRACT\n // names a path, write the translatable slot template there and STOP — skipping\n // the expensive render/island-bundle. aadesh spawns jsdoc with this\n // env var set to harvest the template, then drives the per-locale builds.\n const extractPath = process.env.CLEAN_JSDOC_THEME_EXTRACT?.trim();\n if (extractPath) {\n const target = resolvePath(extractPath);\n await progress.stage('Writing extract manifest', async () => {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, JSON.stringify(toExtractManifest(manifest), null, 2) + '\\n', 'utf8');\n });\n console.log(\n `clean-jsdoc-theme: extract mode — wrote ${manifest.slots?.length ?? 0} slot(s) to ${target}`\n );\n return;\n }\n\n // Resolve siteName (text or logo set) and copy any local logo images into the\n // output before render, so the served paths are baked into the markup. The\n // shape was already validated above; `prepareSiteName` now only does the\n // local-logo file-copy I/O on the validated value.\n const { siteName, files: logoFiles } = await prepareSiteName(value.siteName, hrefForServed);\n\n // Resilient font fallback: a family flagged `fonts/not-google` is dropped so\n // `resolveTheme` falls back to the default for that slot (the error was\n // already reported in the diagnostics block). Verified/unverified families\n // pass through.\n const notGoogle = new Set(\n diagnostics.list\n .filter((d) => d.code === 'fonts/not-google' && d.path)\n .map((d) => d.path as string)\n );\n const fonts: ValidatedFonts = { ...value.fonts };\n if (notGoogle.has('fonts.heading')) delete fonts.heading;\n if (notGoogle.has('fonts.body')) delete fonts.body;\n // Same resilient drop for per-locale fonts (`fonts.ja:heading`), so a bad\n // locale font falls back to the base/default rather than breaking the build.\n if (fonts.locales) {\n const cleaned: Record<string, FontSet> = {};\n for (const [loc, set] of Object.entries(fonts.locales)) {\n const s: FontSet = { ...set };\n if (notGoogle.has(`fonts.${loc}:heading`)) delete s.heading;\n if (notGoogle.has(`fonts.${loc}:body`)) delete s.body;\n cleaned[loc] = s;\n }\n fonts.locales = cleaned;\n }\n\n // Custom CSS/JS (v4 parity): inline strings pass through; custom files are\n // copied AS-IS to content-hashed `_assets` here (the I/O layer) and merged onto\n // the theme as hrefs, so dwar links them while render() stays pure. Empty/unset\n // → no fields added, so behavior is unchanged when unused.\n const customAssets = await resolveCustomAssets(opts, hrefForServed);\n // Custom footer (v4 parity): inline HTML passes through; the `{ file }` form\n // is read here (the I/O layer) → a resolved string on the theme, so render()\n // stays pure. Unset/empty → default footer.\n const footer = await resolveFooter(opts.footer);\n // Favicon (v4 parity, restored): the file is copied to a content-hashed\n // `_assets` asset here (the I/O layer) and dwar emits the `<link rel=\"icon\">`,\n // so render() stays pure. Hashed like the other custom assets. Unset → none.\n const favicon = await resolveFavicon(opts.favicon, opts.hashCustomAssets !== false, hrefForServed);\n // Site-wide custom <meta> tags. Validated/normalized here (junk dropped +\n // warned); dwar does the escaping + de-dupe against its head defaults.\n const meta = normalizeMeta(opts.meta);\n\n const absoluteDestination = resolvePath(destination);\n // Cache the island esbuild bundle across builds — see RenderOptions.islandCacheDir;\n // the dev/watch loop reuses it when rang/dwar are unchanged.\n const islandCacheDir = resolvePath(process.cwd(), 'node_modules', '.cache', 'clean-jsdoc-theme');\n const result = await progress.stage('Rendering site', () =>\n render(manifest, {\n theme: {\n ...resolveTheme(opts, siteName, fonts, basePath, buildSpec?.locale),\n ...customAssets.theme,\n ...(footer ? { footer } : {}),\n ...(favicon ? { favicon: favicon.href } : {}),\n ...(meta ? { meta } : {}),\n ...(scrollbar ? { scrollbar } : {}),\n },\n destination: absoluteDestination,\n islandCacheDir,\n inlineSvgs: allInlineSvgs,\n // Emit sitemap.xml when a public site URL is configured (the protocol needs\n // absolute URLs). In a localized build each locale's basePath yields that\n // locale's URLs, so each locale dir gets its own sitemap. `value.siteUrl` is\n // the validated form — a malformed URL warned above and lands here as\n // `undefined`, so we never hand dwar something it would silently drop.\n ...(value.siteUrl ? { siteUrl: value.siteUrl } : {}),\n // llms.txt / llms-full.txt (llmstxt.org). `undefined` means either unset or\n // \"enabled but no usable siteUrl\" — the latter already warned in validation.\n ...(value.llmsTxt ? { llmsTxt: value.llmsTxt } : {}),\n // Build mode: render chrome in the locale (SSR provider + island seeding)\n // and, with >1 locale, mount the language switcher.\n ...(buildSpec\n ? {\n locale: {\n code: buildSpec.locale,\n defaultLocale: buildSpec.defaultLocale,\n messages: buildSpec.chromeMessages,\n siteBasePath: buildSpec.siteBasePath,\n locales: buildSpec.locales.map((l) => ({ code: l.code, label: l.name ?? l.code })),\n },\n }\n : {}),\n })\n );\n\n const generatedFiles = [\n ...result.files,\n ...logoFiles,\n ...customAssets.files,\n ...imageFiles,\n ...(favicon?.files ?? []),\n ];\n\n // Static-file passthrough (A): copy each included file verbatim to its output\n // path. Skip any file the image pipeline already consumed (it's served hashed\n // from `_assets/`, so a root duplicate would be dead weight), and any path that\n // would clobber a generated file or a reserved theme dir — generated output\n // always wins; the collision is warned, never silently overwritten.\n const staticOutputFiles: OutputFile[] = [];\n if (staticFiles) {\n const generatedPaths = new Set(generatedFiles.map((f) => f.path));\n const RESERVED_PREFIXES = ['_assets/', '_islands/'];\n let skippedConsumed = 0;\n for (const f of staticFiles.files) {\n if (images.consumed.has(f.absSource)) {\n skippedConsumed++; // already hashed into `_assets/` and referenced there\n continue;\n }\n if (\n generatedPaths.has(f.outputPath) ||\n RESERVED_PREFIXES.some((p) => f.outputPath.startsWith(p))\n ) {\n console.warn(\n `clean-jsdoc-theme: static file '${f.outputPath}' would clobber generated output; skipping it.`\n );\n continue;\n }\n staticOutputFiles.push({ path: f.outputPath, contents: f.contents });\n }\n if (staticFiles.files.length > 0) {\n console.log(\n `clean-jsdoc-theme: staticFiles — copied ${staticOutputFiles.length} file(s) verbatim` +\n (skippedConsumed > 0 ? ` (${skippedConsumed} served hashed via _assets/)` : '') +\n '.'\n );\n }\n }\n\n const outputFiles = [...generatedFiles, ...staticOutputFiles];\n // Empty the destination first so a page removed/renamed since the last build\n // (or a stale content-hashed asset like `styles.<hash>.css`) doesn't linger in\n // the served site. Default on; opt out with `templates.default.cleanOutputDir:\n // false`. Skipped in localization build mode: each locale is a separate process\n // writing the default site to the root and others to `root/<locale>`, so a\n // recursive clean here would clobber a sibling locale's already-built output.\n if (!buildSpec && cleanOutputDirEnabled(opts)) {\n await progress.stage('Cleaning output', () =>\n rm(absoluteDestination, { recursive: true, force: true })\n );\n }\n await progress.stage('Writing files', () => writeOutputFiles(absoluteDestination, outputFiles));\n\n // Next.js-style build report: where the files landed, page/asset counts, and\n // per-route sizes (+ gzip). `node:zlib` is injected here as the gzip sizer so\n // utils stays node-free. Replaces the old single `rendered N page(s)…` line.\n const zlib = await import('node:zlib');\n const gzipSizer = (b: Uint8Array | string): number => zlib.gzipSync(b).length;\n console.log(\n formatBuildReport({\n files: outputFiles,\n stats: result.stats,\n destination,\n gzipSizer,\n color,\n })\n );\n\n // Opts warnings were printed BEFORE any render work, so by now they've scrolled\n // away behind the build log. Re-print just the warnings here — this is near the\n // last thing on screen, so a skipped llms.txt or a font fallback can't go\n // unnoticed by someone who expected that file in the output.\n const optsWarnings = warningsOnly(diagnostics);\n if (optsWarnings.list.length > 0) {\n console.warn(formatDiagnostics(optsWarnings, { color }));\n }\n\n // Skipped pages (render failures) are folded in right after the report so the\n // count is visible alongside the successful totals — never fatal.\n if (result.errors && result.errors.length > 0) {\n console.warn(\n `clean-jsdoc-theme: ${result.errors.length} page(s) failed to render and were skipped:`\n );\n for (const e of result.errors) {\n console.warn(formatRenderError(e));\n }\n }\n\n // Non-fatal authoring warnings (e.g. unbalanced inline-code backticks). The\n // pages still rendered; we surface these so the author can clean up the source.\n if (result.warnings && result.warnings.length > 0) {\n console.warn(\n `clean-jsdoc-theme: ${result.warnings.length} content warning(s) (non-fatal):`\n );\n for (const w of result.warnings) {\n console.warn(formatRenderError(w));\n }\n }\n\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;AAIA,MAAM,oBAAoB,cAAc,YAAY,GAAG;AAIvD,MAAa,aAA6B,4BAAY;;;ACFtD,eAAsB,iBACpB,aACA,OACe;CACf,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,SAAS,KAAK,aAAa,KAAK,IAAI;EAC1C,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW,OAAO,KAAK,KAAK,QAAQ;EAC9F,MAAM,UAAU,QAAQ,QAAQ;CAClC;AACF;;;ACmBA,MAAM,+BAA+B;AAKrC,SAAS,aAAqB;CAC5B,IAAI,OAAO,eAAe,UAAU,OAAO;CAC3C,MAAM,IAAI,MACR,6FACF;AACF;AAEA,SAAS,kBAAkB,MAAsB;CAC/C,MAAM,QAAQ,WAAW;CACzB,IAAI,MAAM,QAAQ,KAAK;CACvB,IAAI,OAAO;CACX,OAAO,QAAQ,MAAM;EACnB,MAAM,YAAYA,QAAY,KAAK,gBAAgB,IAAI;EACvD,IAAI;GACF,aAAaA,QAAY,WAAW,cAAc,GAAG,MAAM;GAC3D,OAAO;EACT,QAAQ,CAER;EACA,OAAO;EACP,MAAM,QAAQ,GAAG;CACnB;CACA,MAAM,IAAI,MAAM,wCAAwC,KAAK,0BAA0B,MAAM,EAAE;AACjG;;;;;;;;AAeA,SAAS,oBAAoB,MAAe,SAAqC;CAC/E,IAAI,OAAO,SAAS,UAAU,OAAOA,QAAY,SAAS,IAAI;CAC9D,I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,QAAQ,KACN,sBAAsB,OAAO,OAAO,OAAO,4CAC7C;EACA,KAAK,MAAM,KAAK,OAAO,QACrB,QAAQ,KAAK,kBAAkB,CAAC,CAAC;CAErC;CAIA,IAAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;EACjD,QAAQ,KACN,sBAAsB,OAAO,SAAS,OAAO,iCAC/C;EACA,KAAK,MAAM,KAAK,OAAO,UACrB,QAAQ,KAAK,kBAAkB,CAAC,CAAC;CAErC;AAEF"}
1
+ {"version":3,"file":"publish.mjs","names":["resolvePath","joinPath","relativePath","resolve"],"sources":["../../../node_modules/.pnpm/tsdown@0.22.14_tsx@4.22.3_typescript@5.9.3_unrun@0.3.1/node_modules/tsdown/esm-shims.js","../src/write-output-files.ts","../src/https-fetch.ts","../src/publish.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","'use strict';\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { OutputFile } from '@clean-jsdoc-theme/dwar';\n\nexport async function writeOutputFiles(\n destination: string,\n files: readonly OutputFile[]\n): Promise<void> {\n for (const file of files) {\n const target = join(destination, file.path);\n await mkdir(dirname(target), { recursive: true });\n const contents = typeof file.contents === 'string' ? file.contents : Buffer.from(file.contents);\n await writeFile(target, contents);\n }\n}\n","/**\n * A `node:https` implementation of utils' `FetchLike`, injected into\n * `createGoogleFontResolver` instead of the global (undici) `fetch`.\n *\n * Why: on Windows, `process.exit` shortly after an undici `fetch()` aborts Node\n * with a libuv assertion (`!(handle->flags & UV_HANDLE_CLOSING)`, exit 127).\n * A strict build that fails validation right after the Google Fonts check\n * exits exactly then, so the failure surfaced as a native crash instead of\n * exit 1. A plain `node:https` request has no such handle and exits cleanly.\n *\n * Only the status code is read; the response body is discarded and the\n * socket destroyed (`res.destroy()`), so nothing lingers after the check.\n * Abort (the resolver's timeout) and network errors reject, which the\n * resolver maps to `'unknown'` (fail-open, an info note) exactly as before.\n * Redirects are not followed: a 3xx resolves the check to `'unknown'`.\n *\n * The request goes through Node's default agent (`https.globalAgent`), so it\n * honours the env proxy (`NODE_USE_ENV_PROXY=1` / `--use-env-proxy` with\n * `HTTPS_PROXY`/`NO_PROXY`, Node >= 24) just like the global `fetch`. Don't\n * pass `agent: false`: that builds a fresh Agent without the proxy settings.\n *\n * utils stays browser-safe because the `node:` import lives here, in the\n * Node-only bridge. The TypeDoc bridge carries a copy\n * (`packages/typedoc/src/https-fetch.ts`); keep the two in sync.\n */\nimport { get } from 'node:https';\nimport type { FetchLike } from '@clean-jsdoc-theme/utils';\n\nexport const httpsFetch: FetchLike = (url, init) =>\n new Promise((resolve, reject) => {\n const req = get(\n url,\n {\n ...(init?.headers ? { headers: init.headers } : {}),\n ...(init?.signal ? { signal: init.signal } : {}),\n },\n (res) => {\n const status = res.statusCode ?? 0;\n // Status is all the resolver needs; drop the body and the socket.\n res.destroy();\n resolve({ status });\n }\n );\n req.on('error', reject);\n });\n","'use strict';\n\n// JSDoc 4 → setu → dwar bridge. `publish(taffyData, opts, tutorials)` is the\n// entry JSDoc invokes; everything below orchestrates the four phase packages.\n\nimport { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport {\n basename,\n dirname,\n extname,\n join as joinPath,\n relative as relativePath,\n resolve as resolvePath,\n sep,\n} from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type {\n CopyPageAction,\n CopyPageConfig,\n PageNavConfig,\n MetaTag,\n OutputFile,\n SiteLogo,\n SiteManifest,\n SiteName,\n ThemeColors,\n ThemeConfig,\n} from '@clean-jsdoc-theme/dwar';\nimport type {\n DocInput,\n MenuItem,\n PlaygroundSiteConfig,\n SourceFileInput,\n TutorialInput,\n} from '@clean-jsdoc-theme/setu';\nimport type { PlaygroundProvider } from '@clean-jsdoc-theme/utils';\nimport { writeOutputFiles } from './write-output-files';\nimport { httpsFetch } from './https-fetch';\n\n// JSDoc's tutorial source-type enum (jsdoc/lib/jsdoc/tutorial.js): HTML = 1,\n// MARKDOWN = 2. A tutorial's `.content` is the RAW source; `.type` says how to\n// read it.\nconst JSDOC_TUTORIAL_TYPE_MARKDOWN = 2;\n\n// Absolute path of the running module. `__filename` is native in the CJS build\n// and injected into the ESM build by tsdown's `shims` option (from\n// import.meta.url), so this resolves in both without an eval/`new Function` shim.\nfunction anchorPath(): string {\n if (typeof __filename === 'string') return __filename;\n throw new Error(\n 'clean-jsdoc-theme: could not determine the running module path (__filename is unavailable).'\n );\n}\n\nfunction resolvePackageDir(name: string): string {\n const start = anchorPath();\n let dir = dirname(start);\n let prev = '';\n while (dir !== prev) {\n const candidate = resolvePath(dir, 'node_modules', name);\n try {\n readFileSync(resolvePath(candidate, 'package.json'), 'utf8');\n return candidate;\n } catch {\n // not here — go up.\n }\n prev = dir;\n dir = dirname(dir);\n }\n throw new Error(`clean-jsdoc-theme: could not locate '${name}' on disk starting from ${start}.`);\n}\n\ninterface MinimalPkgJson {\n main?: string;\n module?: string;\n exports?: string | Record<string, unknown>;\n}\n\n/**\n * Resolve an `exports` condition subtree (a string target, or a conditions\n * object like `{ import, require, default, types }`) to an absolute path,\n * preferring the ESM condition (`import`, then a bare `default`). Recurses for\n * nested conditions (`import: { default: \"…\" }`). Returns `undefined` when no\n * usable target is present.\n */\nfunction resolveExportTarget(node: unknown, pkgRoot: string): string | undefined {\n if (typeof node === 'string') return resolvePath(pkgRoot, node);\n if (!node || typeof node !== 'object') return undefined;\n const o = node as Record<string, unknown>;\n const imp = resolveExportTarget(o.import, pkgRoot);\n if (imp) return imp;\n if (typeof o.default === 'string') return resolvePath(pkgRoot, o.default);\n return undefined;\n}\n\nfunction resolveEsmEntry(name: string): string {\n const pkgRoot = resolvePackageDir(name);\n const pkg = JSON.parse(\n readFileSync(resolvePath(pkgRoot, 'package.json'), 'utf8')\n ) as MinimalPkgJson;\n\n const exp = pkg.exports;\n if (typeof exp === 'string') return resolvePath(pkgRoot, exp);\n if (exp && typeof exp === 'object') {\n // Either a `.` subpath (`{ \".\": … }`) or top-level conditions with no\n // subpaths (`{ import, default, types }`, as ora ships). Resolve whichever.\n const dot = (exp as Record<string, unknown>)['.'];\n const target = resolveExportTarget(dot !== undefined ? dot : exp, pkgRoot);\n if (target) return target;\n }\n if (typeof pkg.module === 'string') return resolvePath(pkgRoot, pkg.module);\n if (typeof pkg.main === 'string') return resolvePath(pkgRoot, pkg.main);\n\n throw new Error(\n `clean-jsdoc-theme: could not determine ESM entry file for '${name}' (no exports/module/main).`\n );\n}\n\n// setu and dwar are ESM-only; JSDoc 4 loads this theme via `require()`, so the\n// CJS bundle here can't `require()` them. Dynamic-import a `file://` URL\n// instead. The specifier is funneled through a variable so the bundler don't\n// rewrite the dynamic import into a static `require()` during CJS bundling.\nasync function loadDep<T>(name: string, requiredExports: readonly string[]): Promise<T> {\n const entry = resolveEsmEntry(name);\n const id = pathToFileURL(entry).href;\n const mod = (await import(id)) as Record<string, unknown>;\n for (const key of requiredExports) {\n if (typeof mod[key] !== 'function') {\n throw new Error(\n `clean-jsdoc-theme: '${name}' did not export a '${key}' function ` +\n `(resolved from ${entry}; got keys: ${Object.keys(mod).join(', ') || '(none)'}).`\n );\n }\n }\n return mod as T;\n}\nconst loadSetu = (): Promise<typeof import('@clean-jsdoc-theme/setu')> =>\n loadDep('@clean-jsdoc-theme/setu', ['generateSite', 'stampSite']);\nconst loadDwar = (): Promise<typeof import('@clean-jsdoc-theme/dwar')> =>\n loadDep('@clean-jsdoc-theme/dwar', ['render']);\nconst loadUtils = (): Promise<typeof import('@clean-jsdoc-theme/utils')> =>\n loadDep('@clean-jsdoc-theme/utils', [\n 'validateThemeOpts',\n 'createGoogleFontResolver',\n 'formatDiagnostics',\n 'DiagnosticBag',\n 'formatBuildReport',\n 'formatRenderError',\n 'normalizeBasePath',\n 'withBase',\n 'toExtractManifest',\n 'normalizeCollapsibleSidebarSections',\n 'unmatchedCollapsibleSections',\n 'topLevelSectionLabels',\n 'normalizeScrollbar',\n ]);\n\n/** The `ora` spinner factory (its default export). */\ntype OraFactory = typeof import('ora').default;\n\n/**\n * Load `ora` (ESM-only) the same way as the other deps — via a resolved\n * `file://` URL so the CJS bundle doesn't `require()` it. Returns `null` if\n * `ora` can't be loaded, so progress degrades to silent rather than failing\n * the build.\n */\nconst loadOra = async (): Promise<OraFactory | null> => {\n try {\n const mod = await loadDep<typeof import('ora')>('ora', ['default']);\n return mod.default;\n } catch {\n return null;\n }\n};\n\n/**\n * JSDoc's own standard `opts` keys (`jsdoc/lib/jsdoc/opts/argparser.js` +\n * `conf` schema). These share the flat `opts` namespace with the theme's\n * options, so they must never be flagged as unknown theme keys — even by a\n * near-miss typo distance. Theme keys (`docs`, `docGroups`, …) live in\n * `THEME_OPT_KEYS`, NOT here.\n */\nconst JSDOC_OWN_OPTS: ReadonlySet<string> = new Set([\n 'destination',\n 'template',\n 'encoding',\n 'recurse',\n 'readme',\n 'package',\n 'tutorials',\n 'query',\n 'private',\n 'access',\n 'explain',\n 'debug',\n 'verbose',\n 'pedantic',\n 'match',\n 'nocolor',\n 'templates',\n]);\n\ninterface JSDocOpts {\n destination?: string;\n package?: string;\n /** JSDoc's `--private`: document `@private` symbols (any truthy value, as in JSDoc). */\n private?: unknown;\n /** JSDoc's `--access` (repeatable on the CLI, so usually an array). */\n access?: string | string[];\n /**\n * Site identity from `jsdoc.json` (`\"opts\": { \"siteName\": ... }`). Either a\n * string (shown in the header/footer and appended to each page's `<title>`),\n * or a logo image set `{ default, dark, light, alt }`. Local image paths are\n * copied into the output; `http(s)://` and `data:` values pass through. The\n * `alt` text (or `pkg.name`) is used for the `<title>` suffix and image alt.\n */\n siteName?: string | SiteLogo;\n /**\n * Font overrides from `jsdoc.json` (`\"opts\": { \"fonts\": { ... } }`). Values\n * are Google Fonts family names for `heading`/`body`; `mono` is a CSS stack.\n */\n fonts?: { heading?: string; body?: string; mono?: string };\n /**\n * Light-mode color overrides from `jsdoc.json` (`\"opts\": { \"colors\": { ... } }`).\n * Any subset of `bg`, `bgMuted`, `fg`, `fgMuted`, `accent`, `accentFg`, `border`;\n * each value is any CSS color string (the theme ships oklch). Omitted keys keep\n * the default palette.\n */\n colors?: unknown;\n /**\n * Dark-mode color overrides (`\"opts\": { \"darkColors\": { ... } }`). Same keys as\n * {@link JSDocOpts.colors}; emitted under `[data-theme=\"dark\"]`. Omitted keys\n * keep the default dark palette.\n */\n darkColors?: unknown;\n /**\n * Project README as HTML. JSDoc renders the Markdown README (`-R`/`opts.readme`\n * or one found in the source paths) and replaces this with the resulting HTML\n * before calling `publish`. Rendered as the site home page.\n */\n readme?: string;\n /** Path to the tutorials directory (`-u`/`opts.tutorials`); resolved tree arrives as the 3rd `publish` arg. */\n tutorials?: string;\n /**\n * Path to a docs content directory (`jsdoc.json` `\"opts\": { \"docs\": \"docs/\" }`),\n * resolved relative to the cwd. The bridge walks it recursively; each\n * `*.md`/`*.markdown` (and `*.html`) file becomes a prose page at its clean,\n * unprefixed slug (the relative path), grouped by frontmatter/directory. A root\n * `index.md` becomes the home page. Unset → no docs site (today's behavior).\n */\n docs?: unknown;\n /**\n * Top-level doc-group display order (`jsdoc.json` `\"opts\": { \"docGroups\": [...] }`).\n * An ordered list of doc-group labels controlling how the doc-group sidebar\n * sections render (after the API sections). Omit for the default order.\n */\n docGroups?: unknown;\n /**\n * Group label assigned to a doc page that carries no frontmatter/directory\n * group (`jsdoc.json` `\"opts\": { \"defaultDocGroup\": \"Docs\" }`). Omit to leave\n * such pages ungrouped.\n */\n defaultDocGroup?: unknown;\n /**\n * Sidebar section order from `jsdoc.json` (`\"opts\": { \"sectionOrder\": [...] }`).\n * An ordered list of section labels (e.g. `[\"Classes\", \"Tutorials\"]`) that both\n * filters and orders the sidebar sections; \"Home\" and \"Source Files\" are always\n * shown regardless. Omit (or leave empty) for the default order.\n */\n sectionOrder?: unknown;\n /**\n * Full sidebar menu from `jsdoc.json` (`\"opts\": { \"menu\": [...] }`). An ordered\n * list of `{ id, title, href, icon }` entries. When present it takes precedence\n * over `sectionOrder` and controls the entire sidebar (built-ins, sections, and\n * external links). See setu's {@link MenuItem}.\n */\n menu?: unknown;\n /**\n * Club related sidebar entries into prefix-grouped subtrees (`jsdoc.json`\n * `\"opts\": { \"clubSidebarItems\": true }`). Groups entries within each section\n * by the path segment before the first `/` (e.g. `queue/*` under a `queue`\n * parent); a prefix with a single entry is left flat. Off by default.\n */\n clubSidebarItems?: unknown;\n /**\n * Which top-level sidebar sections collapse (`jsdoc.json`\n * `\"opts\": { \"collapsibleSidebarSections\": true | [\"Classes\",\"Namespaces\"] }`).\n * `true`/absent → all; `false` → none; array → only those exact labels\n * (case-sensitive). Unmatched labels warn. See utils `resolveCollapsibleSections`.\n */\n collapsibleSidebarSections?: unknown;\n /**\n * Custom prompt for the copy-page button's \"Open in ChatGPT/Claude/Perplexity\"\n * actions (`jsdoc.json` `\"opts\": { \"aiPrompt\": \"…\" }`). `{siteName}`, `{url}`,\n * and `{mdUrl}` (the page's raw Markdown link) placeholders are substituted at\n * click time. Only the prompt + links are sent (the AI fetches `{mdUrl}`), so\n * the query stays short for long docs. Omit for a sensible default.\n */\n aiPrompt?: unknown;\n /**\n * Copy-page button config (`jsdoc.json` `\"opts\": { \"copyPage\": … }`). Either a\n * boolean (`false` hides the button) or an object `{ enabled?, actions? }`,\n * where `actions` is an ordered subset of\n * `[\"copy\",\"view\",\"claude\",\"chatgpt\",\"perplexity\"]` (`[]` shows just the\n * primary copy button). Defaults to enabled with all actions.\n */\n copyPage?: unknown;\n /**\n * Previous/next page pager config (`jsdoc.json` `\"opts\": { \"pageNav\": … }`).\n * Either a boolean (`false` hides the pager) or an object `{ enabled? }`. The\n * pager links each content page to its neighbors in sidebar reading order.\n * Defaults to enabled.\n */\n pageNav?: unknown;\n /**\n * Scrollbar presentation (`jsdoc.json` `\"opts\": { \"scrollbar\": \"native\" }`).\n * `\"styled\"` (default) = overlay bar that hides at rest; `\"visible\"` = themed\n * bar always shown; `\"native\"` = the browser's own scrollbar. See #281.\n */\n scrollbar?: unknown;\n /**\n * Code-playground config (`jsdoc.json` `\"opts\": { \"playground\": … }`). Either\n * a boolean (`true` turns it on with defaults; absent/`false` = off) or an\n * object `{ enableForAllExamples?, providers?, codepen?, jsfiddle?,\n * codesandbox? }`. `providers` picks which of CodePen/JSFiddle/CodeSandbox an\n * `@example` (or prose code block) can be opened in; the per-provider records\n * hold their site-wide runtime options. When set, `@playground` tags are\n * honored; when off, they're ignored (byte-identical output).\n */\n playground?: unknown;\n /**\n * Custom site footer (`jsdoc.json` `\"opts\": { \"footer\": … }`). Either an\n * inline HTML string (v4 parity) or `{ \"file\": \"./footer.html\" }` (read from\n * disk by the bridge). Rendered into rang's footer slot in place of the\n * default footer on every page; style it with `customCss`/`customCssFile`.\n * Omit for the default footer.\n */\n footer?: unknown;\n /**\n * Site public base URL (`jsdoc.json` `\"opts\": { \"siteUrl\": \"https://example.com\" }`).\n * When set, the build emits a `sitemap.xml` at the output root listing every\n * non-hidden page's canonical URL. Only the URL's origin is used — the deploy\n * sub-path comes from `basePath` — so a bare origin or a full URL whose path\n * equals `basePath` both work. Omit it for no sitemap.\n */\n siteUrl?: unknown;\n /**\n * Emit an llmstxt.org index (`jsdoc.json` `\"opts\": { \"llmsTxt\": true }`) —\n * `llms.txt` at the output root, plus `llms-full.txt` (every page concatenated)\n * unless `full: false`. Accepts `true` (⇒ `{ full: true, api: true }`) or\n * `{ full?: boolean, api?: boolean | 'index' }`, where `api: 'index'` lists API\n * pages without descriptions and omits their bodies from `llms-full.txt`, and\n * `api: false` omits API pages entirely. **Requires `siteUrl`** — the file is\n * fetched standalone, so its links must be absolute; without it the build warns\n * and emits nothing.\n */\n llmsTxt?: unknown;\n /**\n * Favicon (`jsdoc.json` `\"opts\": { \"favicon\": \"./icon.svg\" }`). A path to an\n * image file (`.svg`/`.png`/`.ico`/…), relative to the working dir. The bridge\n * copies it to a content-hashed `_assets/` asset and emits a `<link rel=\"icon\">`\n * in every page's `<head>`. Needed for an SVG favicon (browsers only\n * auto-discover a root `favicon.ico`). Omit for none.\n */\n favicon?: unknown;\n /**\n * Site-wide custom `<meta>` tags (`jsdoc.json` `\"opts\": { \"meta\": [...] }`). An\n * array of attribute maps — each object's key/value pairs become one `<meta>`\n * tag in `<head>` (`{ name, content }`, `{ property, content }`, …). dwar\n * escapes values, drops invalid attribute names, and de-dupes against its own\n * head defaults (an author `name: \"description\"` replaces the auto one).\n */\n meta?: unknown;\n /**\n * Inline custom CSS (`jsdoc.json` `\"opts\": { \"customCss\": \"…\" }`), injected as\n * a `<style>` after the theme stylesheet so it can override.\n */\n customCss?: unknown;\n /**\n * Path(s) to custom CSS file(s) (`\"opts\": { \"customCssFile\": \"a.css\" }` or an\n * array). Each file is copied AS-IS (its own bytes) to\n * `_assets/<name>.<hash>.css` and linked after the theme stylesheet. The\n * `<hash>` is a content hash (see `hashCustomAssets`), so an unchanged file\n * keeps a stable, cacheable URL.\n */\n customCssFile?: unknown;\n /**\n * Inline custom JS (`\"opts\": { \"customJs\": \"…\" }`), injected as a classic\n * `<script>` before `</body>`, after the theme's own scripts.\n */\n customJs?: unknown;\n /**\n * Path(s) to custom JS file(s) (`\"opts\": { \"customJsFile\": \"a.js\" }` or an\n * array). Each file is copied AS-IS to `_assets/<name>.<hash>.js` and\n * referenced before `</body>`. See `hashCustomAssets`.\n */\n customJsFile?: unknown;\n /**\n * Whether to append a content hash to copied `customCssFile`/`customJsFile`\n * asset names (`_assets/<name>.<hash>.css`). Defaults to `true` — the hash is\n * derived from the file's content (NOT random), so an unchanged file yields\n * the same URL across builds (cache-friendly) and a changed file cache-busts.\n * Set `false` to copy with the original `<name>.css`/`.js` (no hash).\n */\n hashCustomAssets?: unknown;\n /**\n * Build-stage progress output (`jsdoc.json` `\"opts\": { \"progress\": false }`).\n * The setu→dwar pipeline does noticeably more than a bare jsdoc run (per-page\n * MDX compile, per-island esbuild bundling, the island cache), so by default\n * the bridge narrates each stage with its elapsed time. Set `false` to silence\n * the stage lines (the build report still prints).\n */\n progress?: unknown;\n /**\n * JSDoc's default-template source options, read from `conf.templates.default`\n * (or, as a fallback, nested under `opts.templates`):\n * - `outputSourceFiles` — defaults to `true`; set `false` to suppress the\n * per-file source viewer pages and the `Source: file:line` member links.\n * - `sourceLinkToComment` — defaults to `false`. By default a `Source:`\n * link lands on the first line of the declaration; set `true` to point it\n * at the doclet's doc-comment line instead (the pre-v5 behavior).\n * - `cleanOutputDir` — defaults to `true`; set `false` to keep existing files\n * in the destination instead of emptying it before each build.\n */\n templates?: {\n default?: {\n outputSourceFiles?: unknown;\n sourceLinkToComment?: unknown;\n cleanOutputDir?: unknown;\n /**\n * JSDoc's standard static-file passthrough\n * (`templates.default.staticFiles`): `{ include, exclude, includePattern,\n * excludePattern }`. Files matched by `include` are copied verbatim into\n * the output (an include dir's contents land at the output root, JSDoc's\n * mapping) AND their dirs become fallback search roots for image\n * resolution, so a bare/relative reference to a static image resolves.\n */\n staticFiles?: unknown;\n };\n };\n [key: string]: unknown;\n}\n\nconst defaultTheme: ThemeConfig = {\n tokens: {\n // Light palette (oklch). bg #fdfdf7 · fg #3e3e3e · border #eeeeee;\n // muted/accent derived to harmonize.\n colors: {\n bg: 'oklch(0.9924 0.0079 106.54)',\n bgMuted: 'oklch(0.9595 0.0079 106.55)',\n fg: 'oklch(0.3639 0 0)',\n fgMuted: 'oklch(0.5278 0 0)',\n accent: 'oklch(0 0 0)',\n accentFg: 'oklch(1 0 0)',\n border: 'oklch(0.9561 0 0)',\n },\n // Dark palette (oklch). bg #09090b · fg #9e9e9e · border #141416;\n // muted/accent derived to harmonize.\n darkColors: {\n bg: 'oklch(0.1408 0.0044 285.82)',\n bgMuted: 'oklch(0.2103 0.0059 285.89)',\n fg: 'oklch(0.6993 0 0)',\n fgMuted: 'oklch(0.5382 0 0)',\n accent: 'oklch(1 0 0)',\n accentFg: 'oklch(0 0 0)',\n border: 'oklch(0.2321 0.004 286.02)',\n },\n fonts: {\n heading: 'Source Serif 4',\n body: 'Roboto',\n mono: 'ui-monospace, SFMono-Regular, Menlo, monospace',\n },\n shiki: { light: 'github-light', dark: 'github-dark' },\n },\n basePath: '/',\n};\n\n/** One font triple — any subset of `{ heading, body, mono }`. */\ninterface FontSet {\n heading?: string;\n body?: string;\n mono?: string;\n}\n\n/**\n * The shape validated font overrides take: base `{ heading, body, mono }` plus\n * optional per-locale overrides (from `<code>:heading`-style opts). Mirrors\n * utils' `ValidatedFonts`.\n */\ninterface ValidatedFonts extends FontSet {\n locales?: Record<string, FontSet>;\n}\n\n/**\n * Resolve the font triple for the active `locale`: a per-locale override wins,\n * then the base font, then the theme default — per slot. With no locale (a\n * normal, non-localized build) only the base + default apply, so the result is\n * byte-identical to before per-locale fonts existed.\n */\nfunction resolveFontSet(fonts: ValidatedFonts, locale: string | undefined) {\n const base = defaultTheme.tokens.fonts;\n const override = (locale && fonts.locales?.[locale]) || {};\n return {\n heading: override.heading ?? fonts.heading ?? base.heading,\n body: override.body ?? fonts.body ?? base.body,\n mono: override.mono ?? fonts.mono ?? base.mono,\n };\n}\n\n/**\n * Merge validated user overrides from `jsdoc.json` (`siteName`, `fonts`) over\n * the defaults. Only the keys the user supplies are overridden; everything else\n * keeps the default theme. `siteName` is pre-resolved/validated and its local\n * logos copied by `prepareSiteName`; `fonts` is the validated subset (any\n * family flagged `fonts/not-google` is dropped upstream so the default applies).\n * `locale` (set in build mode) selects per-locale font overrides.\n */\nfunction resolveTheme(\n opts: JSDocOpts,\n siteName: SiteName | undefined,\n fonts: ValidatedFonts,\n basePath: string,\n locale?: string\n): ThemeConfig {\n const aiPrompt =\n typeof opts.aiPrompt === 'string' && opts.aiPrompt.trim() ? opts.aiPrompt.trim() : undefined;\n const copyPage = normalizeCopyPage(opts.copyPage);\n const pageNav = normalizePageNav(opts.pageNav);\n // Only the runtime (per-provider options) slice belongs in the theme; the\n // enablement slice goes to setu (see the siteOptions assembly).\n const playground = normalizePlayground(opts.playground);\n\n // Color overrides merge per-key over the default palettes, so supplying only\n // `colors.bg` keeps every other default color. `darkColors` layers over the\n // default dark palette the same way.\n const colors = normalizeColors(opts.colors);\n const darkColors = normalizeColors(opts.darkColors);\n\n return {\n ...defaultTheme,\n basePath,\n ...(aiPrompt ? { aiPrompt } : {}),\n ...(copyPage ? { copyPage } : {}),\n ...(pageNav ? { pageNav } : {}),\n ...(playground ? { playground: playground.theme } : {}),\n tokens: {\n ...defaultTheme.tokens,\n colors: { ...defaultTheme.tokens.colors, ...(colors ?? {}) },\n darkColors: { ...defaultTheme.tokens.darkColors, ...(darkColors ?? {}) },\n fonts: resolveFontSet(fonts, locale),\n ...(siteName ? { siteName } : {}),\n },\n };\n}\n\n/**\n * Where an option problem found outside `validateThemeOpts` is reported. The\n * default prints a warning; `publish` passes a sink that, under `strict`,\n * records it as an error instead (see `warnOption` there).\n */\ntype WarnSink = (message: string) => void;\nconst consoleWarn: WarnSink = (message) => console.warn(message);\n\n/** Trim a value to a non-empty string, or `undefined`. */\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined;\n}\n\n/**\n * Short, deterministic content hash for cache-stable custom-asset filenames.\n * Derived from the file's bytes (NOT random), so an unchanged file produces the\n * same name across builds (browser cache hit) and a changed file cache-busts.\n */\nfunction contentHash(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex').slice(0, 8);\n}\n\n/**\n * Copy custom CSS/JS file(s) (a path or array, relative to the working dir) to\n * served `_assets` files and return their hrefs. Each file is copied AS-IS (its\n * own bytes — never concatenated). The asset name is `<base>.<hash>.<ext>` when\n * `hash` is on (the hash is content-derived → stable URL for unchanged files),\n * else the bare `<base><ext>`. A file that can't be read is skipped with a\n * warning (resilient, like `prepareSiteName`); an identical served name is\n * emitted once.\n *\n * Only local file paths are copied. An entry that isn't a string (v4's\n * `add_style_path`/`add_script_path` took `{ href, integrity, crossorigin }`\n * CDN objects) or is a remote URL is skipped with a warning naming the\n * alternative (`remoteAlternative`), instead of vanishing silently.\n */\nasync function copyCustomFiles(\n raw: unknown,\n ext: '.css' | '.js',\n hash: boolean,\n label: string,\n remoteAlternative: string,\n hrefForServed: (servedPath: string) => string,\n warn: WarnSink = consoleWarn\n): Promise<{ links: string[]; files: OutputFile[] }> {\n const entries = raw === undefined || raw === null ? [] : Array.isArray(raw) ? raw : [raw];\n const paths: string[] = [];\n for (const entry of entries) {\n if (typeof entry !== 'string') {\n warn(\n `clean-jsdoc-theme: ${label} takes local file paths; skipping ${JSON.stringify(entry)}. ` +\n `For a remote file, download it or ${remoteAlternative}.`\n );\n continue;\n }\n const trimmed = entry.trim();\n if (trimmed.length === 0) continue;\n if (/^([a-z][a-z0-9+.-]*:)?\\/\\//i.test(trimmed)) {\n warn(\n `clean-jsdoc-theme: ${label} only copies local files; skipping '${trimmed}'. ` +\n `Download it, or ${remoteAlternative}.`\n );\n continue;\n }\n paths.push(trimmed);\n }\n const links: string[] = [];\n const files: OutputFile[] = [];\n const seen = new Set<string>();\n for (const trimmed of paths) {\n let bytes: Buffer;\n try {\n bytes = await readFile(resolvePath(trimmed));\n } catch {\n warn(`clean-jsdoc-theme: could not read ${label} ('${trimmed}'); skipping it.`);\n continue;\n }\n const base = basename(trimmed, extname(trimmed)) || 'custom';\n const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;\n const servedPath = `_assets/${name}`;\n if (seen.has(servedPath)) continue;\n seen.add(servedPath);\n files.push({ path: servedPath, contents: bytes });\n // The OutputFile `path` stays relative (no leading slash); only the served\n // href gets the base-path prefix (`/` when unset → unchanged).\n links.push(hrefForServed(servedPath));\n }\n return { links, files };\n}\n\n/**\n * Resolve the custom CSS/JS injection options into render-ready `ThemeConfig`\n * fields plus the asset files to write. Inline strings (`customCss`/`customJs`)\n * pass through; file options (`customCssFile`/`customJsFile`) are read + copied\n * to content-hashed assets here — the bridge is the I/O layer, so dwar's\n * `render()` stays pure and just links the resulting hrefs. `hashCustomAssets`\n * (default `true`) toggles the content-hash suffix.\n */\nexport async function resolveCustomAssets(\n opts: JSDocOpts,\n hrefForServed: (servedPath: string) => string,\n warn: WarnSink = consoleWarn\n): Promise<{\n theme: {\n customCss?: string;\n customCssLinks?: string[];\n customJs?: string;\n customJsLinks?: string[];\n };\n files: OutputFile[];\n}> {\n const hash = opts.hashCustomAssets !== false; // content-hashed by default\n const [cssAssets, jsAssets] = await Promise.all([\n copyCustomFiles(\n opts.customCssFile,\n '.css',\n hash,\n 'customCssFile',\n '`@import url(…)` it from `customCss`',\n hrefForServed,\n warn\n ),\n copyCustomFiles(\n opts.customJsFile,\n '.js',\n hash,\n 'customJsFile',\n 'load it from `customJs` (e.g. append a `<script src>`)',\n hrefForServed,\n warn\n ),\n ]);\n const customCss = nonEmptyString(opts.customCss)?.trim();\n const customJs = nonEmptyString(opts.customJs)?.trim();\n return {\n theme: {\n ...(customCss ? { customCss } : {}),\n ...(cssAssets.links.length > 0 ? { customCssLinks: cssAssets.links } : {}),\n ...(customJs ? { customJs } : {}),\n ...(jsAssets.links.length > 0 ? { customJsLinks: jsAssets.links } : {}),\n },\n files: [...cssAssets.files, ...jsAssets.files],\n };\n}\n\n/**\n * Resolve `opts.footer` (inline HTML `string` | `{ file }`) into the single\n * `ThemeConfig.footer` string. The `{ file }` form is read from disk HERE — the\n * bridge is the I/O layer, so dwar's `render()` only ever sees the resolved\n * string. A missing/unreadable file is warned about and dropped (resilient,\n * like the logo/custom-asset paths), and an empty value yields `undefined` so\n * the default footer renders. Exported for testing.\n */\nexport async function resolveFooter(\n raw: unknown,\n warn: WarnSink = consoleWarn\n): Promise<string | undefined> {\n if (typeof raw === 'string') {\n const trimmed = raw.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n }\n if (raw && typeof raw === 'object' && typeof (raw as { file?: unknown }).file === 'string') {\n const file = (raw as { file: string }).file.trim();\n if (!file) return undefined;\n try {\n const html = await readFile(resolvePath(file), 'utf8');\n return html.trim().length > 0 ? html : undefined;\n } catch {\n warn(\n `clean-jsdoc-theme: could not read footer file ('${file}'); omitting the custom footer.`\n );\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Resolve `opts.favicon` (a file path) into a served `_assets/` href + the file\n * to write — the bridge is the I/O layer, so dwar only sees the final URL and\n * `render()` stays pure. The asset name is content-hashed (cache-busted) unless\n * `hash` is off, and the source extension is preserved so dwar can derive the\n * `<link>` `type`. A missing/unreadable file is warned about and dropped\n * (resilient, like the logo/custom-asset paths). Exported for testing.\n */\nexport async function resolveFavicon(\n raw: unknown,\n hash: boolean,\n hrefForServed: (servedPath: string) => string,\n warn: WarnSink = consoleWarn\n): Promise<{ href: string; files: OutputFile[] } | undefined> {\n if (typeof raw !== 'string' || raw.trim().length === 0) return undefined;\n const trimmed = raw.trim();\n let bytes: Buffer;\n try {\n bytes = await readFile(resolvePath(trimmed));\n } catch {\n warn(`clean-jsdoc-theme: could not read favicon ('${trimmed}'); omitting it.`);\n return undefined;\n }\n const ext = extname(trimmed) || '.ico';\n const base = basename(trimmed, extname(trimmed)) || 'favicon';\n const name = hash ? `${base}.${contentHash(bytes)}${ext}` : `${base}${ext}`;\n const servedPath = `_assets/${name}`;\n // The OutputFile `path` stays relative; only the served href gets the prefix.\n return { href: hrefForServed(servedPath), files: [{ path: servedPath, contents: bytes }] };\n}\n\n/** Attributes that identify a `<meta>` tag (so an entry must carry at least one). */\nconst META_IDENTITY_ATTRS = ['name', 'property', 'http-equiv', 'charset', 'itemprop'] as const;\n\n/**\n * Validate `opts.meta` into a clean `MetaTag[]` (attribute maps), or `undefined`\n * when there's nothing usable. Accepts only an array of objects; within each,\n * keeps string→string pairs (trimming the value, coercing finite numbers to\n * strings for convenience) and drops the rest. An entry with no recognized\n * identifying attribute (`name`/`property`/`http-equiv`/`charset`/`itemprop`) is\n * dropped with a warning — dwar does the final escaping + key validation.\n */\nexport function normalizeMeta(raw: unknown, warn: WarnSink = consoleWarn): MetaTag[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: MetaTag[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;\n const o = entry as Record<string, unknown>;\n const tag: MetaTag = {};\n for (const [k, v] of Object.entries(o)) {\n if (typeof v === 'string') {\n const t = v.trim();\n if (t.length > 0) tag[k] = t;\n } else if (typeof v === 'number' && Number.isFinite(v)) {\n tag[k] = String(v);\n }\n }\n const hasIdentity = META_IDENTITY_ATTRS.some((a) => typeof tag[a] === 'string');\n if (!hasIdentity || Object.keys(tag).length === 0) {\n warn(\n `clean-jsdoc-theme: skipping a meta entry with no usable name/property/http-equiv/charset attribute (${JSON.stringify(entry)}).`\n );\n continue;\n }\n out.push(tag);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/** A logo value that's already a servable URL/URI needs no copying. */\nfunction isServableUrl(value: string): boolean {\n return /^(https?:)?\\/\\//i.test(value) || /^data:/i.test(value);\n}\n\n/**\n * Resolve `opts.siteName` into a render-ready value plus any image files to\n * write. A string passes through (trimmed). For a logo set, each local image\n * path is read and emitted as a content-hashed output asset\n * (`_assets/logo-<key>.<hash><ext>`, cache-busted like the custom assets) with\n * its value rewritten to the served path; `http(s)://` / `data:` values pass\n * through untouched, and the `alt` label is preserved. A path that can't be\n * read is left verbatim with a warning rather than aborting the build.\n */\nasync function prepareSiteName(\n raw: string | SiteLogo | undefined,\n hrefForServed: (servedPath: string) => string,\n warn: WarnSink = consoleWarn\n): Promise<{ siteName: SiteName | undefined; files: OutputFile[] }> {\n if (typeof raw === 'string') {\n const trimmed = raw.trim();\n return { siteName: trimmed.length > 0 ? trimmed : undefined, files: [] };\n }\n if (!raw || typeof raw !== 'object') return { siteName: undefined, files: [] };\n\n const files: OutputFile[] = [];\n const out: SiteLogo = {};\n if (typeof raw.alt === 'string' && raw.alt.trim().length > 0) out.alt = raw.alt.trim();\n\n for (const key of ['default', 'dark', 'light'] as const) {\n const value = raw[key];\n if (typeof value !== 'string' || value.trim().length === 0) continue;\n const v = value.trim();\n\n if (isServableUrl(v)) {\n out[key] = v;\n continue;\n }\n\n try {\n const abs = resolvePath(v);\n const buf = await readFile(abs);\n const served = `_assets/logo-${key}.${contentHash(buf)}${extname(abs)}`;\n files.push({ path: served, contents: buf });\n // OutputFile `path` stays relative; only the served href gets the prefix.\n out[key] = hrefForServed(served);\n } catch {\n warn(\n `clean-jsdoc-theme: could not read logo image for siteName.${key} ('${v}'); using it verbatim.`\n );\n out[key] = v;\n }\n }\n\n const hasContent = out.default || out.dark || out.light || out.alt;\n return { siteName: hasContent ? out : undefined, files };\n}\n\n// Priority: opts.package file → taffy `kind:'package'` doclet → undefined.\nasync function resolvePkg(\n data: unknown,\n opts: JSDocOpts\n): Promise<SiteManifest['pkg'] | undefined> {\n if (typeof opts.package === 'string' && opts.package.length > 0) {\n try {\n const json = await readFile(opts.package, 'utf8');\n const parsed = JSON.parse(json) as Record<string, unknown>;\n return pickPkgFields(parsed);\n } catch {\n // fall through — try the taffy collection instead.\n }\n }\n\n // Probe the taffy collection for a `kind: 'package'` doclet without\n // taking a hard dependency on the salty API surface here.\n if (typeof data === 'function') {\n try {\n const pkgDoclets = (data as (q: unknown) => { get(): unknown[] })({ kind: 'package' }).get();\n if (Array.isArray(pkgDoclets) && pkgDoclets.length > 0) {\n return pickPkgFields(pkgDoclets[0] as Record<string, unknown>);\n }\n } catch {\n // ignore — collection isn't a salty DB or has no package doclet.\n }\n }\n\n return undefined;\n}\n\nfunction pickPkgFields(raw: Record<string, unknown>): SiteManifest['pkg'] {\n const pkg: SiteManifest['pkg'] = {};\n if (typeof raw.name === 'string') pkg.name = raw.name;\n if (typeof raw.version === 'string') pkg.version = raw.version;\n if (typeof raw.description === 'string') pkg.description = raw.description;\n if (typeof raw.homepage === 'string') pkg.homepage = raw.homepage;\n // `repository` may be a string or { url }; normalize to a string.\n if (typeof raw.repository === 'string') {\n pkg.repository = raw.repository;\n } else if (\n raw.repository &&\n typeof raw.repository === 'object' &&\n typeof (raw.repository as { url?: unknown }).url === 'string'\n ) {\n pkg.repository = (raw.repository as { url: string }).url;\n }\n return pkg;\n}\n\n/** Minimal view of JSDoc's `Tutorial` (jsdoc/lib/jsdoc/tutorial.js). */\ninterface JSDocTutorial {\n name?: unknown;\n title?: unknown;\n content?: unknown;\n type?: unknown;\n children?: unknown;\n}\n\n/**\n * Normalize JSDoc's tutorial resolver tree (the `tutorials` arg to `publish`)\n * into setu's plain {@link TutorialInput} shape. The root's `children` are the\n * top-level tutorials; each child carries its own `children`, so a depth-first\n * walk preserves the resolved hierarchy. Content is taken raw (`.content`);\n * `.type === 2` (MARKDOWN) is markdown, everything else is treated as HTML.\n */\nfunction normalizeTutorials(root: unknown): TutorialInput[] {\n const walk = (node: JSDocTutorial): TutorialInput | null => {\n const name = typeof node.name === 'string' ? node.name : '';\n if (!name) return null;\n const title = typeof node.title === 'string' && node.title.length > 0 ? node.title : name;\n const content = typeof node.content === 'string' ? node.content : '';\n const type = node.type === JSDOC_TUTORIAL_TYPE_MARKDOWN ? 'markdown' : 'html';\n const children = Array.isArray(node.children)\n ? (node.children as JSDocTutorial[]).map(walk).filter((t): t is TutorialInput => t !== null)\n : [];\n return { name, title, content, type, children };\n };\n\n const children = (root as JSDocTutorial | undefined)?.children;\n if (!Array.isArray(children)) return [];\n return (children as JSDocTutorial[]).map(walk).filter((t): t is TutorialInput => t !== null);\n}\n\n/**\n * Resolve JSDoc's `templates.default.outputSourceFiles` flag. The `opts` arg\n * `publish` receives is `env.opts` — the `opts` block — which does NOT carry the\n * root-level `templates` block, so we probe in priority order and default ON:\n * 1. `require('jsdoc/env').conf.templates.default.outputSourceFiles` (the\n * canonical location at runtime; wrapped in try/catch so a missing\n * `jsdoc/env` — e.g. in unit tests — never throws the build).\n * 2. `opts.templates.default.outputSourceFiles` (in case a user nests it\n * under `opts`).\n * Resolves to `false` ONLY when one of those is exactly `=== false`; otherwise\n * `true` (matching JSDoc's default-template default).\n */\nexport function outputSourceFilesEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { outputSourceFiles?: unknown } } };\n };\n if (env?.conf?.templates?.default?.outputSourceFiles === false) return false;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.outputSourceFiles === false) return false;\n return true;\n}\n\n/**\n * Resolve `templates.default.sourceLinkToComment`. Probed in the same priority\n * order as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a\n * nested `opts.templates` fallback). Resolves to `true` ONLY when one of those\n * is exactly `=== true`; otherwise `false` (the default: links jump to code).\n */\nexport function sourceLinkToCommentEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { sourceLinkToComment?: unknown } } };\n };\n if (env?.conf?.templates?.default?.sourceLinkToComment === true) return true;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.sourceLinkToComment === true) return true;\n return false;\n}\n\n/**\n * Whether private doclets should be documented — the private-access slice of\n * JSDoc's `templateHelper.prune`, with its exact tests: `env.opts.private` is\n * truthy (`--private`), or `env.opts.access` `.includes('private')` or\n * `.includes('all')`. Like prune, `includes` runs on whatever `access` is: an\n * array from the CLI (the flag is repeatable) or a string from `jsdoc.json`, so\n * `\"private,protected\"` and `\"all\"` count via substring match, exactly as in\n * JSDoc. Default: hidden.\n *\n * Only this slice is implemented. prune's other `--access` levels (`public`,\n * `protected`, `package`, `undefined` — e.g. `--access public` hiding\n * protected symbols) are NOT applied: those symbols stay documented.\n */\nexport function includePrivateEnabled(opts: JSDocOpts): boolean {\n if (opts?.private) return true;\n const access: unknown = opts?.access;\n if (typeof access !== 'string' && !Array.isArray(access)) return false;\n return access.includes('private') || access.includes('all');\n}\n\n/**\n * Resolve `templates.default.cleanOutputDir`. Probed in the same priority order\n * as {@link outputSourceFilesEnabled} (canonical `jsdoc/env` conf, then a nested\n * `opts.templates` fallback). Defaults to `true` — the build empties its\n * destination first so a page removed or renamed between runs (e.g. a deleted\n * class, or a stale content-hashed `styles.<hash>.css`) doesn't linger in the\n * served site. Resolves to `false` ONLY when one is exactly `=== false`.\n */\nexport function cleanOutputDirEnabled(opts: JSDocOpts): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { cleanOutputDir?: unknown } } };\n };\n if (env?.conf?.templates?.default?.cleanOutputDir === false) return false;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n if (opts?.templates?.default?.cleanOutputDir === false) return false;\n return true;\n}\n\n/**\n * Whether a JSDoc `conf.plugins` list enables the bundled `plugins/markdown`\n * plugin. The theme relies on it: JSDoc runs `plugins/markdown` to convert the\n * Markdown in doclet descriptions/tags to HTML *before* `publish` ever sees the\n * doclets, so without it descriptions arrive as raw Markdown and render wrong.\n * Pure + exported for testing — accepts the `plugins` array (module specifiers,\n * e.g. `\"plugins/markdown\"`; tolerant of a `.js` suffix or path separators).\n */\nexport function hasMarkdownPlugin(plugins: unknown): boolean {\n if (!Array.isArray(plugins)) return false;\n return plugins.some((p) => typeof p === 'string' && /(^|[\\\\/])markdown(\\.js)?$/i.test(p.trim()));\n}\n\n/**\n * Hard-require JSDoc's `plugins/markdown` plugin (see {@link hasMarkdownPlugin}).\n * Reads the merged config from `require('jsdoc/env').conf.plugins` — the\n * canonical location at runtime — and throws if the plugin is absent so the\n * build stops early with an actionable message. When `jsdoc/env` can't be\n * resolved (e.g. unit tests, or a non-JSDoc caller) the check is skipped: the\n * plugin list is unknowable there, so it can't be enforced.\n */\nfunction assertMarkdownPlugin(): void {\n let conf: { plugins?: unknown } | undefined;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n conf = (require('jsdoc/env') as { conf?: { plugins?: unknown } }).conf;\n } catch {\n return; // `jsdoc/env` isn't resolvable here — can't verify, so don't enforce.\n }\n if (!conf) return;\n if (!hasMarkdownPlugin(conf.plugins)) {\n throw new Error(\n 'clean-jsdoc-theme requires JSDoc\\'s \"plugins/markdown\" plugin, which ' +\n 'renders Markdown in doclet descriptions to HTML. Add it to your ' +\n 'jsdoc.json:\\n\\n \"plugins\": [\"plugins/markdown\"]\\n'\n );\n }\n}\n\n/**\n * Validate `opts.sectionOrder` into a clean `string[]`, or `undefined` to fall\n * back to setu's default order. Accepts only an array; trims string entries and\n * drops non-strings/empties. An array that yields no usable labels → `undefined`.\n */\nexport function normalizeSectionOrder(raw: unknown): string[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out = raw\n .filter((s): s is string => typeof s === 'string')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Validate `opts.menu` into a clean `MenuItem[]`, or `undefined` when there's no\n * usable menu. Accepts only an array of objects; trims string fields. The link\n * URL is read from `link` (preferred) or `href`. Keeps only actionable entries —\n * a built-in (`id`) or an external link (`link`/`href`).\n */\nexport function normalizeMenu(raw: unknown): MenuItem[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: MenuItem[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== 'object') continue;\n const o = entry as Record<string, unknown>;\n const item: MenuItem = {};\n if (typeof o.id === 'string' && o.id.trim()) item.id = o.id.trim();\n if (typeof o.title === 'string' && o.title.trim()) item.title = o.title.trim();\n const link =\n typeof o.link === 'string' && o.link.trim()\n ? o.link.trim()\n : typeof o.href === 'string' && o.href.trim()\n ? o.href.trim()\n : undefined;\n if (link) item.link = link;\n if (typeof o.icon === 'string' && o.icon.trim()) item.icon = o.icon.trim();\n if (typeof o.target === 'string' && o.target.trim()) item.target = o.target.trim();\n if (typeof o.class === 'string' && o.class.trim()) item.class = o.class.trim();\n if (item.id || item.link) out.push(item);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/** Valid copy-page dropdown actions (mirrors setu/dwar's `CopyPageAction`). */\nconst COPY_PAGE_ACTIONS: readonly CopyPageAction[] = [\n 'copy',\n 'view',\n 'claude',\n 'chatgpt',\n 'perplexity',\n];\n\n/**\n * Validate `opts.copyPage` into a {@link CopyPageConfig}, or `undefined` to use\n * the defaults (enabled, all actions). Accepts a boolean shorthand (`false`\n * hides the button) or an object: `enabled` is read if boolean; `actions`, if an\n * array, is filtered to the known action ids (preserving order, dropping\n * unknowns/dupes) — an empty/all-invalid array still yields `[]` (primary button\n * only), which is meaningful and kept.\n */\nexport function normalizeCopyPage(raw: unknown): CopyPageConfig | undefined {\n if (raw === false) return { enabled: false };\n if (raw === true || raw == null) return undefined;\n if (typeof raw !== 'object') return undefined;\n\n const o = raw as Record<string, unknown>;\n const config: CopyPageConfig = {};\n if (typeof o.enabled === 'boolean') config.enabled = o.enabled;\n if (Array.isArray(o.actions)) {\n const seen = new Set<CopyPageAction>();\n for (const a of o.actions) {\n if (typeof a === 'string' && (COPY_PAGE_ACTIONS as readonly string[]).includes(a)) {\n seen.add(a as CopyPageAction);\n }\n }\n config.actions = COPY_PAGE_ACTIONS.filter((a) => seen.has(a));\n }\n return Object.keys(config).length > 0 ? config : undefined;\n}\n\n/**\n * Validate `opts.pageNav` into a {@link PageNavConfig}, or `undefined` to use the\n * default (enabled). Accepts a boolean shorthand (`false` hides the pager) or an\n * object whose `enabled` is read when boolean.\n */\nexport function normalizePageNav(raw: unknown): PageNavConfig | undefined {\n if (raw === false) return { enabled: false };\n if (raw === true || raw == null) return undefined;\n if (typeof raw !== 'object') return undefined;\n const enabled = (raw as Record<string, unknown>).enabled;\n return typeof enabled === 'boolean' ? { enabled } : undefined;\n}\n\n/** Valid code-playground providers (mirrors utils' `PlaygroundProvider`). */\nconst PLAYGROUND_PROVIDERS: readonly PlaygroundProvider[] = ['codepen', 'jsfiddle', 'codesandbox'];\n\n/** A site-wide per-provider options record, or `undefined` for a non-object. */\nfunction playgroundOptionRecord(raw: unknown): Record<string, unknown> | undefined {\n return raw && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Validate `opts.playground` into its two consumer slices, or `undefined` when\n * the feature is off (absent or `false`). `playground: true` / `{}` turns it on\n * with defaults — every provider available, opt-in per `@playground`. The\n * **`site`** slice feeds setu's `@playground` resolver (enablement + provider\n * selection); the **`theme`** slice becomes `ThemeConfig.playground` (the\n * site-wide per-provider runtime options dwar hands the browser island). Unknown\n * providers/keys are dropped (lenient, like {@link normalizeCopyPage}). setu\n * gates on the `site` slice's presence, so returning `undefined` keeps output\n * byte-identical.\n */\nexport function normalizePlayground(\n raw: unknown\n): { site: PlaygroundSiteConfig; theme: NonNullable<ThemeConfig['playground']> } | undefined {\n if (raw == null || raw === false) return undefined;\n const o = raw === true ? {} : raw;\n if (typeof o !== 'object' || Array.isArray(o)) return undefined;\n const obj = o as Record<string, unknown>;\n\n const site: PlaygroundSiteConfig = {};\n if (obj.enableForAllExamples === true) site.enableForAllExamples = true;\n if (Array.isArray(obj.providers)) {\n const providers: PlaygroundProvider[] = [];\n for (const p of obj.providers) {\n if (\n typeof p === 'string' &&\n (PLAYGROUND_PROVIDERS as readonly string[]).includes(p) &&\n !providers.includes(p as PlaygroundProvider)\n ) {\n providers.push(p as PlaygroundProvider);\n }\n }\n if (providers.length > 0) site.providers = providers;\n }\n\n const theme: NonNullable<ThemeConfig['playground']> = { enabled: true };\n const codepen = playgroundOptionRecord(obj.codepen);\n const jsfiddle = playgroundOptionRecord(obj.jsfiddle);\n const codesandbox = playgroundOptionRecord(obj.codesandbox);\n if (codepen) theme.codepen = codepen;\n if (jsfiddle) theme.jsfiddle = jsfiddle;\n if (codesandbox) theme.codesandbox = codesandbox;\n\n return { site, theme };\n}\n\n/** The palette keys a user may override under `opts.colors` / `opts.darkColors`. */\nconst COLOR_KEYS = [\n 'bg',\n 'bgMuted',\n 'fg',\n 'fgMuted',\n 'accent',\n 'accentFg',\n 'border',\n 'codeHeaderBg',\n 'codeHeaderFg',\n 'codeHighlightBg',\n] as const;\n\n/**\n * Validate a user `colors`/`darkColors` object from `jsdoc.json` into a clean\n * `Partial<ThemeColors>`: keeps only the known palette keys whose value is a\n * non-empty string, dropping everything else. Returns `undefined` when the input\n * is not an object or yields no usable keys, so callers can fall back cleanly.\n * Values are passed through verbatim (any CSS color is valid).\n */\nexport function normalizeColors(raw: unknown): Partial<ThemeColors> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const src = raw as Record<string, unknown>;\n const out: Partial<ThemeColors> = {};\n for (const key of COLOR_KEYS) {\n const v = src[key];\n if (typeof v === 'string' && v.trim().length > 0) out[key] = v.trim();\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Extensions we treat as \"source\" worth emitting a viewer page for. */\nconst SOURCE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']);\n\n/**\n * Compute project-relative paths for a set of absolute source paths by stripping\n * their longest common directory prefix. Returns a `Map<absPath, relPath>` with\n * `relPath` normalized to forward slashes. Pure + exported for testing.\n *\n * Windows-aware: paths are split on both `/` and `\\\\`, and segment comparison is\n * case-insensitive (NTFS is case-insensitive, and JSDoc's `meta.path` casing can\n * differ from disk). The single-file case yields just its basename. If the paths\n * share no common leading segment (e.g. different drives / UNC vs. drive), each\n * file falls back to its basename so the index stays sane.\n */\nexport function computeRelPaths(absPaths: readonly string[]): Map<string, string> {\n const out = new Map<string, string>();\n if (absPaths.length === 0) return out;\n\n const split = (p: string): string[] => p.split(/[\\\\/]+/).filter((s) => s.length > 0);\n const segLists = absPaths.map(split);\n\n // Longest common directory prefix (exclude the basename from the prefix so a\n // single file resolves to its own name, not the empty string).\n let common = segLists[0].slice(0, -1);\n for (let i = 1; i < segLists.length && common.length > 0; i++) {\n const segs = segLists[i];\n let j = 0;\n const max = Math.min(common.length, segs.length - 1);\n while (j < max && common[j].toLowerCase() === segs[j].toLowerCase()) j++;\n common = common.slice(0, j);\n }\n\n for (let i = 0; i < absPaths.length; i++) {\n const segs = segLists[i];\n const rel =\n common.length > 0 && segs.length > common.length\n ? segs.slice(common.length).join('/')\n : (segs[segs.length - 1] ?? absPaths[i]);\n out.set(absPaths[i], rel);\n }\n return out;\n}\n\n/**\n * Collect every source file referenced by a doclet's `meta` and read its\n * contents, ready to hand to setu as {@link SourceFileInput}s. `absPath` is the\n * exact `resolve(meta.path, meta.filename)` so setu's `Source: file:line`\n * matching (which joins the same fields) lines up. Files that can't be read are\n * warned about and skipped — never fatal. Returns sorted-by-`relPath` for\n * stable output.\n */\nasync function collectSourceFiles(data: unknown): Promise<SourceFileInput[]> {\n // Mirror resolvePkg's safe probe, but query ALL doclets (empty query).\n let doclets: unknown[] = [];\n if (typeof data === 'function') {\n try {\n doclets = (data as (q: unknown) => { get(): unknown[] })({}).get();\n } catch {\n try {\n doclets = (data as () => { get(): unknown[] })().get();\n } catch {\n doclets = [];\n }\n }\n }\n if (!Array.isArray(doclets) || doclets.length === 0) return [];\n\n // Unique absolute paths from doclet meta.\n const absSet = new Set<string>();\n for (const d of doclets) {\n const meta = (d as { meta?: { path?: unknown; filename?: unknown } } | undefined)?.meta;\n if (!meta || typeof meta.path !== 'string' || typeof meta.filename !== 'string') continue;\n const filename = meta.filename;\n // Skip obvious non-source by extension, but stay permissive (no ext → keep).\n const ext = extname(filename).toLowerCase();\n if (ext.length > 0 && !SOURCE_EXTENSIONS.has(ext)) continue;\n absSet.add(resolvePath(meta.path, filename));\n }\n if (absSet.size === 0) return [];\n\n const absPaths = [...absSet];\n const relPaths = computeRelPaths(absPaths);\n\n const inputs: SourceFileInput[] = [];\n for (const abs of absPaths) {\n try {\n const content = await readFile(abs, 'utf8');\n inputs.push({ absPath: abs, relPath: relPaths.get(abs) ?? abs, content });\n } catch (err) {\n console.warn(\n `clean-jsdoc-theme: could not read source file '${abs}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n\n inputs.sort((a, b) => a.relPath.localeCompare(b.relPath));\n return inputs;\n}\n\n/** Doc-file extensions → `DocInput.type`. Markdown is the priority; html maps to 'html'. */\nconst DOC_EXTENSIONS = new Map<string, DocInput['type']>([\n ['.md', 'markdown'],\n ['.markdown', 'markdown'],\n ['.html', 'html'],\n ['.htm', 'html'],\n]);\n\n/** Directory names skipped while walking a docs tree (build/vcs noise). */\nconst DOC_DIR_SKIP = new Set(['node_modules', '.git', '.svn', '.hg']);\n\n/**\n * Recursively walk a docs directory and read each Markdown/HTML file into a\n * {@link DocInput} for setu's docs front-end. Mirrors {@link collectSourceFiles}'s\n * safe-probe style:\n *\n * - `path` is the file path relative to `dir`, POSIX-normalized (forward slashes)\n * with the extension stripped (`<dir>/guides/advanced.md` → `'guides/advanced'`,\n * `<dir>/index.md` → `'index'`).\n * - `content` is the raw UTF-8 text (frontmatter stays embedded — setu parses it).\n * - `type` is `'markdown'` for `.md`/`.markdown`, `'html'` for `.html`/`.htm`.\n *\n * Resilient by design: a missing/unreadable directory yields `[]` (never throws);\n * dotfiles/dot-dirs and `node_modules`-like noise are skipped; a single\n * unreadable file is warned about and skipped. Results are sorted by `path` so\n * the output is stable build-to-build. Setu does no I/O — this is the only place\n * the docs tree is read.\n */\nexport async function collectDocs(dir: string): Promise<DocInput[]> {\n if (typeof dir !== 'string' || dir.trim().length === 0) return [];\n const root = resolvePath(dir);\n const docs: DocInput[] = [];\n\n const walk = async (absDir: string, relPrefix: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n // Missing/unreadable directory — skip leniently (root miss → []).\n return;\n }\n\n for (const entry of entries) {\n const name = entry.name;\n // Skip dotfiles/dot-dirs and known build/vcs noise.\n if (name.startsWith('.')) continue;\n if (entry.isDirectory()) {\n if (DOC_DIR_SKIP.has(name)) continue;\n await walk(joinPath(absDir, name), relPrefix ? `${relPrefix}/${name}` : name);\n continue;\n }\n if (!entry.isFile()) continue;\n\n const ext = extname(name).toLowerCase();\n const type = DOC_EXTENSIONS.get(ext);\n if (!type) continue;\n\n const abs = joinPath(absDir, name);\n const stem = name.slice(0, name.length - ext.length);\n const relPath = relPrefix ? `${relPrefix}/${stem}` : stem;\n try {\n const content = await readFile(abs, 'utf8');\n // `source` only names the file in diagnostics (e.g. a skipped page).\n const source = relativePath(process.cwd(), abs).split(sep).join('/');\n docs.push({ path: relPath, content, type, source });\n } catch (err) {\n console.warn(\n `clean-jsdoc-theme: could not read doc file '${abs}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n };\n\n await walk(root, '');\n\n // Deterministic order so the manifest is stable build-to-build.\n docs.sort((a, b) => a.path.localeCompare(b.path));\n return docs;\n}\n\n/** Markdown image: captures `![alt](`, the src, an optional `\"title\"`, and `)`. */\nconst DOC_IMAGE_RE = /(!\\[[^\\]]*\\]\\()([^)\\s]+)((?:\\s+\"[^\"]*\")?\\))/g;\n\n/**\n * HTML image: captures the `<img …src=` prefix (through the opening quote), the\n * quote char, the src value, and the closing quote (a backreference to the\n * opener). JSDoc's `plugins/markdown` renders a comment's `![alt](src)` to\n * `<img src=\"…\" alt=\"…\">`, and prose can embed raw `<img>`; this matches both\n * quote styles wherever `src` sits in the tag.\n */\nconst HTML_IMAGE_RE = /(<img\\b[^>]*?\\bsrc\\s*=\\s*([\"']))([^\"']*)(\\2)/gi;\n\n/**\n * A reusable local-image asset pipeline shared by every prose source (docs,\n * tutorials, README, doclet comments). `resolve(src, baseDir)` copies a local\n * image to `_assets/<base>.<hash><ext>` (content-hashed → cache-busted, deduped\n * across all sources via the shared caches) and returns the root-relative\n * `/_assets/…` href — deliberately WITHOUT `basePath`: rang's `MdxImg` adds it\n * for HTML and dwar's `prefixRootRelativeUrls` for the companion `.md` /\n * `llms-full.txt`, once each; `hrefForServed` is only for theme assets (logos,\n * favicon, custom CSS/JS). The TypeDoc twin (`typedoc/src/docs.ts`) follows the\n * same rule (#377). It accumulates each copied file on `files`, each SVG's\n * markup on `inlineSvgs` (keyed by the rewritten href, so the renderer can inline\n * it — its `[data-theme]` styles then track the toggle), and the absolute source\n * path of every copied image on `consumed` (so the static-file passthrough can\n * skip re-copying an image it already served from `_assets/`).\n *\n * Resolution tries, in order: the doc-relative path (or project root for a\n * `/`-rooted src), then — for the JSDoc `staticFiles` convention — each\n * `staticDirs` root joined with the reference's output-relative name. So a bare\n * `![x](classes-io.png)` whose file lives in a declared `staticFiles` dir still\n * resolves and is hashed. External (`http(s):`, `data:`), `#`-anchor, and\n * fully-unresolvable srcs yield `null` (the last warned once) so callers leave\n * them untouched.\n */\nexport interface ImageCollector {\n resolve(rawSrc: string, baseDir: string): Promise<string | null>;\n readonly files: OutputFile[];\n readonly inlineSvgs: Record<string, string>;\n readonly consumed: Set<string>;\n}\n\nexport function createImageCollector(staticDirs: readonly string[] = []): ImageCollector {\n const files: OutputFile[] = [];\n const inlineSvgs: Record<string, string> = {};\n const consumed = new Set<string>();\n const seenServed = new Set<string>();\n // abs path → rewritten src (root-relative `/_assets/…`), or null if unreadable.\n const cache = new Map<string, string | null>();\n const warnedMisses = new Set<string>();\n\n const resolve = async (rawSrc: string, baseDir: string): Promise<string | null> => {\n const src = rawSrc.trim();\n if (!src || isServableUrl(src) || src.startsWith('#') || src.startsWith('data:')) return null;\n // Candidate absolute paths in priority order: the doc-relative / project-root\n // location first, then each staticFiles dir joined with the output-relative\n // name (leading slash stripped) as a fallback.\n const primary = src.startsWith('/') ? resolvePath(src.slice(1)) : resolvePath(baseDir, src);\n const candidates = [primary];\n if (staticDirs.length > 0) {\n const outName = src.replace(/^\\/+/, '');\n if (outName) for (const dir of staticDirs) candidates.push(resolvePath(dir, outName));\n }\n\n for (const abs of candidates) {\n const cached = cache.get(abs);\n if (cached !== undefined) {\n if (cached) return cached; // already copied\n continue; // known miss — try the next candidate\n }\n let bytes: Buffer;\n try {\n bytes = await readFile(abs);\n } catch {\n cache.set(abs, null);\n continue;\n }\n const ext = extname(abs);\n const served = `_assets/${basename(abs, ext) || 'asset'}.${contentHash(bytes)}${ext}`;\n if (!seenServed.has(served)) {\n seenServed.add(served);\n files.push({ path: served, contents: bytes });\n }\n const href = '/' + served; // base-free by design — see the doc comment above (#377)\n // SVGs are ALSO inlined: the renderer drops the markup into the page so its\n // `[data-theme=\"dark\"]` styles track the theme toggle (an `<img>`-loaded SVG\n // only sees the OS color scheme). A responsive sizing style is injected onto\n // the `<svg>` root; the `_assets/` copy still backs the companion `.md` link.\n if (ext.toLowerCase() === '.svg') {\n inlineSvgs[href] = bytes\n .toString('utf8')\n .replace(/<svg\\b/, '<svg style=\"max-width:100%;height:auto;display:block\"');\n }\n cache.set(abs, href);\n consumed.add(abs);\n return href;\n }\n\n if (!warnedMisses.has(src)) {\n warnedMisses.add(src);\n console.warn(\n `clean-jsdoc-theme: could not read image '${src}' (looked in: ${candidates.join(', ')}); leaving it as-is.`\n );\n }\n return null;\n };\n\n return { resolve, files, inlineSvgs, consumed };\n}\n\n/**\n * Rewrite the local image references in `content` to their content-hashed\n * `/_assets/…` paths, routing each through `collector`. Handles BOTH Markdown\n * `![alt](src)` and raw HTML `<img src=\"…\">` (JSDoc renders comment/tutorial\n * images to the latter), so prose in either form is covered. Relative srcs\n * resolve against `baseDir`, `/`-rooted srcs against the project root, and\n * external/`data:`/anchor srcs are left untouched. Returns the original string\n * unchanged when nothing was rewritten.\n */\n/**\n * Char ranges of Markdown/HTML **code** regions — fenced blocks (` ``` `/`~~~`),\n * HTML `<pre>`/`<code>`, and inline backtick spans. Image references inside these\n * are literal example syntax an author is *documenting*, not real images, so the\n * rewriter skips them (no spurious copy/rewrite, no \"could not read\" warning).\n * Order matters: the multi-line block forms come before the inline span so a\n * fence isn't chopped at its first inner backtick.\n */\nconst CODE_REGION_RE =\n /```[\\s\\S]*?```|~~~[\\s\\S]*?~~~|<pre[\\s\\S]*?<\\/pre>|<code[^>]*>[\\s\\S]*?<\\/code>|`[^`\\n]+`/gi;\n\n/** Collect the [start, end) char ranges of code regions in `content`. */\nfunction codeRanges(content: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n for (const m of content.matchAll(CODE_REGION_RE)) {\n if (m.index !== undefined) ranges.push([m.index, m.index + m[0].length]);\n }\n return ranges;\n}\n\n/** Whether char offset `idx` falls inside any of the (sorted-ish) code ranges. */\nfunction indexInCode(idx: number, ranges: ReadonlyArray<[number, number]>): boolean {\n for (const [s, e] of ranges) if (idx >= s && idx < e) return true;\n return false;\n}\n\nasync function rewriteImageRefs(\n content: string,\n baseDir: string,\n collector: ImageCollector\n): Promise<string> {\n if (!content) return content;\n const ranges = codeRanges(content);\n const map = new Map<string, string>();\n const collect = async (re: RegExp, srcGroup: number): Promise<void> => {\n for (const m of content.matchAll(re)) {\n if (m.index !== undefined && indexInCode(m.index, ranges)) continue; // example syntax\n const src = m[srcGroup];\n if (map.has(src)) continue;\n const href = await collector.resolve(src, baseDir);\n if (href) map.set(src, href);\n }\n };\n await collect(DOC_IMAGE_RE, 2);\n await collect(HTML_IMAGE_RE, 3);\n if (map.size === 0) return content;\n return content\n .replace(DOC_IMAGE_RE, (full, pre, src, post, offset: number) =>\n !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${post}` : full\n )\n .replace(HTML_IMAGE_RE, (full, pre, _quote, src, close, offset: number) =>\n !indexInCode(offset, ranges) && map.has(src) ? `${pre}${map.get(src)}${close}` : full\n );\n}\n\n/**\n * Resolve the local images a doc references and route them through the shared\n * content-hashed `_assets/` pipeline (see {@link createImageCollector}). Each\n * `![alt](src)` / `<img src>` whose `src` points to a file on disk is copied and\n * its `src` rewritten to the root-relative `/_assets/<base>.<hash><ext>` (rang's\n * `MdxImg` adds the base path, like it does for links, and dwar adds it to the\n * `.md`/llms outputs), resolved relative to the project root when it starts with\n * `/`, else relative to the doc's own directory. Returns the docs with rewritten\n * content plus the asset files to write. The bridge is the I/O layer here, so\n * setu/dwar only ever see the final `_assets/` paths.\n */\nexport async function resolveDocImages(\n docs: DocInput[],\n docsDir: string,\n collector: ImageCollector = createImageCollector()\n): Promise<{ docs: DocInput[]; files: OutputFile[]; inlineSvgs: Record<string, string> }> {\n if (docs.length === 0) return { docs, files: collector.files, inlineSvgs: collector.inlineSvgs };\n const root = resolvePath(docsDir);\n const out: DocInput[] = [];\n for (const doc of docs) {\n const docDir = dirname(resolvePath(root, doc.path));\n const content = await rewriteImageRefs(doc.content, docDir, collector);\n out.push(content === doc.content ? doc : { ...doc, content });\n }\n return { docs: out, files: collector.files, inlineSvgs: collector.inlineSvgs };\n}\n\n/**\n * Resolve the local images referenced by tutorial content, routing them through\n * the shared `collector` (the same content-hashed `_assets/` pipeline as docs).\n * JSDoc reads every tutorial from a single directory, so each tutorial's relative\n * srcs (`![x](../img/x.png)`, `<img src>`) resolve against `tutorialsDir`. Walks\n * the resolved tree (sub-tutorials included), rewriting each node's content —\n * Markdown or HTML; the tree shape is preserved. Returns a new tree (the input is\n * left untouched). Exported for testing.\n */\nexport async function resolveTutorialImages(\n tree: TutorialInput[],\n tutorialsDir: string,\n collector: ImageCollector\n): Promise<TutorialInput[]> {\n const base = resolvePath(tutorialsDir);\n const walk = async (node: TutorialInput): Promise<TutorialInput> => {\n const content = await rewriteImageRefs(node.content, base, collector);\n const children: TutorialInput[] = [];\n for (const child of node.children ?? []) children.push(await walk(child));\n return { ...node, content, children };\n };\n const out: TutorialInput[] = [];\n for (const node of tree) out.push(await walk(node));\n return out;\n}\n\n/**\n * Doclet keys whose string values are raw source/code/meta, NOT rendered prose —\n * never scanned for images (a stray `<img`/`![` there must not be rewritten).\n */\nconst DOCLET_IMAGE_SKIP_KEYS = new Set([\n 'meta',\n 'comment',\n 'examples',\n 'tags',\n '___id',\n '___s',\n]);\n\n/**\n * Recursively rewrite the `<img>`/`![]()` image srcs in every prose string\n * reachable from a doclet object, resolving against `baseDir`. Only strings that\n * actually carry an image marker (`<img` or `![`) are touched — a cheap guard so\n * names/identifiers/code are never scanned — and raw/code keys\n * ({@link DOCLET_IMAGE_SKIP_KEYS}) are skipped entirely. Recurses into nested\n * objects/arrays (e.g. `params[].description`). Mutates `node` in place.\n */\nasync function rewriteDocletStrings(\n node: Record<string, unknown>,\n baseDir: string,\n collector: ImageCollector\n): Promise<void> {\n for (const [key, value] of Object.entries(node)) {\n if (DOCLET_IMAGE_SKIP_KEYS.has(key)) continue;\n if (typeof value === 'string') {\n if (value.includes('<img') || value.includes('![')) {\n const rewritten = await rewriteImageRefs(value, baseDir, collector);\n if (rewritten !== value) node[key] = rewritten;\n }\n } else if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n if (typeof item === 'string') {\n if (item.includes('<img') || item.includes('![')) {\n const rewritten = await rewriteImageRefs(item, baseDir, collector);\n if (rewritten !== item) value[i] = rewritten;\n }\n } else if (item && typeof item === 'object') {\n await rewriteDocletStrings(item as Record<string, unknown>, baseDir, collector);\n }\n }\n } else if (value && typeof value === 'object') {\n await rewriteDocletStrings(value as Record<string, unknown>, baseDir, collector);\n }\n }\n}\n\n/**\n * Resolve the local images referenced inside JSDoc-comment prose (doclet\n * descriptions, `@classdesc`, nested `@param`/`@property`/`@returns`\n * descriptions, …) and route them through the shared `collector`. JSDoc's\n * `plugins/markdown` has already turned a comment's `![alt](../img/x.png)` into\n * an HTML `<img src=\"../img/x.png\">` by the time `publish` runs, so each src is\n * resolved **relative to that doclet's own source file** (`meta.path` — the\n * directory of the file the comment lives in). Doclets are mutated IN PLACE:\n * salty's `get()` hands out live object references, so the rewrite is visible\n * when setu later reads the same collection. Resilient — a non-collection `data`\n * or unreadable image is skipped (the latter warned), never fatal.\n */\nexport async function resolveDocletImages(\n data: unknown,\n collector: ImageCollector\n): Promise<void> {\n if (typeof data !== 'function') return;\n let doclets: unknown[] = [];\n try {\n doclets = (data as (q: unknown) => { get(): unknown[] })({}).get();\n } catch {\n try {\n doclets = (data as () => { get(): unknown[] })().get();\n } catch {\n return;\n }\n }\n if (!Array.isArray(doclets)) return;\n\n for (const d of doclets) {\n if (!d || typeof d !== 'object') continue;\n const meta = (d as { meta?: { path?: unknown } }).meta;\n // Without the source file's directory there's no base to resolve a relative\n // src against, so skip (synthetic/global doclets often carry no meta.path).\n if (!meta || typeof meta.path !== 'string' || meta.path.length === 0) continue;\n await rewriteDocletStrings(d as Record<string, unknown>, meta.path, collector);\n }\n}\n\n// ─── JSDoc `templates.default.staticFiles` passthrough ──────────────────────\n//\n// JSDoc's default template copies arbitrary files into the output via\n// `templates.default.staticFiles` (an include dir's CONTENTS land at the output\n// root). The theme honors that contract: matched files are copied verbatim\n// (covering non-image assets and references the image pipeline doesn't scan),\n// and the include dirs additionally become fallback search roots so a bare image\n// reference like `![x](classes-io.png)` — which only worked in stock JSDoc\n// because the file was copied to the flat output root — resolves through the\n// content-hashed `_assets/` pipeline here (v5 pages are nested, so the reference\n// also has to be rewritten, not just the file copied).\n\n/** Normalized `templates.default.staticFiles` config. */\nexport interface StaticFilesConfig {\n /** Resolved-as-given include paths (dirs or files), trimmed, non-empty. */\n include: string[];\n /** Paths to exclude (a file equal to, or under, an excluded dir is dropped). */\n exclude: string[];\n /** Regex (source string) a file's POSIX abs path must match to be included. */\n includePattern?: string;\n /** Regex (source string) that drops a file when its POSIX abs path matches. */\n excludePattern?: string;\n}\n\n/**\n * Normalize a raw `staticFiles` block into a {@link StaticFilesConfig}, or\n * `undefined` when there's nothing to include. `include`/`exclude` accept a\n * string or string[]; patterns are kept as source strings (compiled later, so a\n * bad pattern fails open rather than throwing). Pure + exported for testing.\n */\nexport function normalizeStaticFilesConfig(raw: unknown): StaticFilesConfig | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const o = raw as Record<string, unknown>;\n const toStrArr = (v: unknown): string[] =>\n (Array.isArray(v) ? v : typeof v === 'string' ? [v] : [])\n .filter((s): s is string => typeof s === 'string' && s.trim().length > 0)\n .map((s) => s.trim());\n const include = toStrArr(o.include);\n if (include.length === 0) return undefined;\n const includePattern =\n typeof o.includePattern === 'string' && o.includePattern.trim().length > 0\n ? o.includePattern\n : undefined;\n const excludePattern =\n typeof o.excludePattern === 'string' && o.excludePattern.trim().length > 0\n ? o.excludePattern\n : undefined;\n return {\n include,\n exclude: toStrArr(o.exclude),\n ...(includePattern ? { includePattern } : {}),\n ...(excludePattern ? { excludePattern } : {}),\n };\n}\n\n/**\n * Read `templates.default.staticFiles` from JSDoc's canonical `jsdoc/env` conf\n * (the only place the root-level `templates` block lives at runtime), falling\n * back to a nested `opts.templates.default.staticFiles`. Mirrors the probe order\n * of {@link outputSourceFilesEnabled}. Returns `undefined` when unset/unusable.\n */\nexport function readStaticFilesConfig(opts: JSDocOpts): StaticFilesConfig | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const env = require('jsdoc/env') as {\n conf?: { templates?: { default?: { staticFiles?: unknown } } };\n };\n const fromEnv = normalizeStaticFilesConfig(env?.conf?.templates?.default?.staticFiles);\n if (fromEnv) return fromEnv;\n } catch {\n // `jsdoc/env` isn't resolvable (e.g. unit tests) — fall back to opts.\n }\n return normalizeStaticFilesConfig(opts?.templates?.default?.staticFiles);\n}\n\n/**\n * Output-relative path (POSIX) for a static file under an include root: strip the\n * resolved-root prefix so `<root>/img/sub/x.png` under root `<root>/img` →\n * `sub/x.png` (JSDoc maps an include dir's contents to the output ROOT). When the\n * include was a single FILE (`absFile === includeRootAbs`), the output name is its\n * basename. Windows-aware: separators are normalized and the prefix match is\n * case-insensitive (NTFS). Pure + exported for testing.\n */\nexport function staticFileOutputName(absFile: string, includeRootAbs: string): string {\n const norm = (p: string): string => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const f = norm(absFile);\n const root = norm(includeRootAbs);\n const baseOf = (p: string): string => p.slice(p.lastIndexOf('/') + 1);\n if (f === root) return baseOf(f); // single-file include\n const prefix = root + '/';\n return f.toLowerCase().startsWith(prefix.toLowerCase()) ? f.slice(prefix.length) : baseOf(f);\n}\n\n/**\n * Whether a static file passes a config's filter — `includePattern` (must match),\n * `excludePattern` (must not match), and `exclude` (file equal to, or nested\n * under, an excluded path is dropped). Patterns are tested against the file's\n * POSIX-normalized absolute path; a malformed pattern fails open (ignored). Pure\n * + exported for testing.\n */\nexport function staticFileIncluded(absFile: string, config: StaticFilesConfig): boolean {\n const norm = (p: string): string => resolvePath(p).replace(/\\\\/g, '/');\n const fn = norm(absFile);\n if (config.includePattern) {\n try {\n if (!new RegExp(config.includePattern).test(fn)) return false;\n } catch {\n /* bad pattern → ignore (fail open) */\n }\n }\n if (config.excludePattern) {\n try {\n if (new RegExp(config.excludePattern).test(fn)) return false;\n } catch {\n /* bad pattern → ignore */\n }\n }\n for (const ex of config.exclude) {\n const exAbs = norm(ex);\n if (fn === exAbs || fn.toLowerCase().startsWith(exAbs.toLowerCase() + '/')) return false;\n }\n return true;\n}\n\n/** Directory names skipped while walking a staticFiles tree (build/vcs noise). */\nconst STATIC_DIR_SKIP = new Set(['node_modules', '.git', '.svn', '.hg']);\n\n/** One verbatim static-file copy entry. */\nexport interface StaticFileEntry {\n /** Output-relative POSIX path (where it lands under the destination). */\n outputPath: string;\n /** Absolute source path (matched against the image collector's `consumed`). */\n absSource: string;\n contents: Buffer;\n}\n\n/**\n * Collect the files matched by a {@link StaticFilesConfig}: walk each include\n * path (a directory recursively, or a single file), apply\n * {@link staticFileIncluded}, and read each match. Returns the verbatim copy\n * entries (output path = include-root-stripped, JSDoc's \"contents → output root\"\n * mapping) plus the resolved `searchDirs` the image resolver uses as fallback\n * roots (an include dir as-is; a file include's parent dir). Resilient: a missing\n * include path / unreadable file is warned + skipped, never fatal. Exported for\n * testing.\n */\nexport async function collectStaticFiles(\n config: StaticFilesConfig,\n warn: (message: string) => void = (m) => console.warn(m)\n): Promise<{ files: StaticFileEntry[]; searchDirs: string[] }> {\n const files: StaticFileEntry[] = [];\n const searchDirs = new Set<string>();\n const seenOutput = new Set<string>(); // de-dup output paths across include roots\n\n for (const inc of config.include) {\n const root = resolvePath(inc);\n let st: import('node:fs').Stats;\n try {\n st = await stat(root);\n } catch {\n warn(\n `clean-jsdoc-theme: staticFiles include '${inc}' (resolved '${root}') was not found; skipping it.`\n );\n continue;\n }\n\n if (st.isDirectory()) {\n searchDirs.add(root);\n const walk = async (absDir: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await readdir(absDir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.name.startsWith('.')) continue;\n const abs = joinPath(absDir, entry.name);\n if (entry.isDirectory()) {\n if (!STATIC_DIR_SKIP.has(entry.name)) await walk(abs);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!staticFileIncluded(abs, config)) continue;\n const outputPath = staticFileOutputName(abs, root);\n if (seenOutput.has(outputPath)) continue;\n let contents: Buffer;\n try {\n contents = await readFile(abs);\n } catch (err) {\n warn(\n `clean-jsdoc-theme: could not read static file '${abs}' — ${(err as Error).message}; skipping.`\n );\n continue;\n }\n seenOutput.add(outputPath);\n files.push({ outputPath, absSource: resolvePath(abs), contents });\n }\n };\n await walk(root);\n } else if (st.isFile()) {\n // A file include's parent dir is the search root, so the image resolver can\n // find it by the bare output name (its basename).\n searchDirs.add(dirname(root));\n if (!staticFileIncluded(root, config)) continue;\n const outputPath = staticFileOutputName(root, root);\n if (!seenOutput.has(outputPath)) {\n try {\n const contents = await readFile(root);\n seenOutput.add(outputPath);\n files.push({ outputPath, absSource: resolvePath(root), contents });\n } catch (err) {\n warn(\n `clean-jsdoc-theme: could not read static file '${root}' — ${(err as Error).message}; skipping.`\n );\n }\n }\n }\n }\n\n // Deterministic order so the manifest/output is stable build-to-build.\n files.sort((a, b) => a.outputPath.localeCompare(b.outputPath));\n return { files, searchDirs: [...searchDirs] };\n}\n\n/** The output of {@link resolveDocImages}: resolved docs + their image assets. */\nexport interface ResolvedDocs {\n docs: DocInput[];\n files: OutputFile[];\n inlineSvgs: Record<string, string>;\n}\n\n/**\n * Overlay a locale's resolved docs over the default set (the per-locale docs\n * track). A locale page WINS over the default page with the same `path`; a\n * default page absent from the locale falls back (stays). Image asset files are\n * deduped by served path (same content-hashed name → one copy), and inline SVGs\n * merge locale-over-default. Output docs are re-sorted by `path` so the manifest\n * stays stable regardless of merge order. Pure — the I/O already happened in the\n * two {@link resolveDocImages} calls that produced `base`/`locale`.\n */\nexport function overlayDocs(base: ResolvedDocs, locale: ResolvedDocs): ResolvedDocs {\n const byPath = new Map(base.docs.map((d) => [d.path, d]));\n for (const d of locale.docs) byPath.set(d.path, d); // locale wins; default falls back\n const filesByPath = new Map<string, OutputFile>();\n for (const f of [...base.files, ...locale.files]) filesByPath.set(f.path, f); // dedupe\n return {\n docs: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)),\n files: [...filesByPath.values()],\n inlineSvgs: { ...base.inlineSvgs, ...locale.inlineSvgs },\n };\n}\n\n/**\n * Validate `opts.docGroups` into a clean `string[]`, or `undefined` to fall back\n * to setu's default doc-group order. Mirrors {@link normalizeSectionOrder}:\n * accepts only an array; trims string entries and drops non-strings/empties.\n */\nexport function normalizeDocGroups(raw: unknown): string[] | undefined {\n return normalizeSectionOrder(raw);\n}\n\n/** Format an elapsed-ms span compactly: `840ms` under a second, else `5.2s`. */\nfunction formatElapsed(ms: number): string {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;\n}\n\n/** Handle a stage's `fn` can use to report sub-step progress on the spinner. */\ninterface StageHandle {\n /** Replace the live spinner label mid-stage (no-op when progress is off). */\n setText(text: string): void;\n}\n\n/**\n * Build-stage narrator backed by `ora`. The setu→dwar pipeline does much more\n * than a bare jsdoc run (per-page MDX compile, per-island esbuild bundling), so\n * a 7–8s build can otherwise look hung. `stage(label, fn)`\n * starts an ora spinner, runs `fn`, then resolves it to `✔ <label> (<elapsed>)`\n * on success or `✖ <label>` on failure. ora handles the spinner animation, TTY\n * detection (no animation when piped/CI), and the success/fail symbols.\n *\n * The catch: ora animates its frame on a `setInterval`, but each stage does\n * heavy *synchronous* work (module evaluation during the dynamic `import()`,\n * per-page MDX compile/SSR) that blocks the event loop — so the interval can't\n * fire and the spinner freezes on one frame, looking hung. Two things keep it\n * visibly alive: an elapsed-seconds **heartbeat** appended to the label (so it\n * advances whenever the loop breathes — module-graph I/O gaps, esbuild\n * subprocess waits), and the `setText` handle, which long stages use to report\n * their current sub-step (e.g. the renderer load steps setu → dwar → utils).\n *\n * `ora` is `null` when progress is disabled (`opts.progress === false`) or the\n * package couldn't be loaded — then `stage` just runs `fn` with no output.\n */\nfunction createBuildProgress(ora: OraFactory | null) {\n async function stage<T>(label: string, fn: (handle: StageHandle) => T | Promise<T>): Promise<T> {\n const noop: StageHandle = { setText: () => {} };\n if (!ora) return await fn(noop);\n const spinner = ora(label).start();\n const begin = Date.now();\n let current = label;\n // Refresh the spinner text with the current sub-step + elapsed seconds. ora\n // repaints on its own interval, so this only shows once the event loop is\n // free, but it means a long stage advances rather than sitting on one frame.\n const refresh = () => {\n const secs = Math.floor((Date.now() - begin) / 1000);\n spinner.text = secs > 0 ? `${current} (${secs}s)` : current;\n };\n const heartbeat = setInterval(refresh, 1000);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n const handle: StageHandle = {\n setText(text) {\n current = text;\n refresh();\n },\n };\n try {\n const result = await fn(handle);\n clearInterval(heartbeat);\n spinner.succeed(`${label} (${formatElapsed(Date.now() - begin)})`);\n return result;\n } catch (err) {\n clearInterval(heartbeat);\n spinner.fail(label);\n throw err;\n }\n }\n\n return { stage };\n}\n\n/** A per-locale render spec (utils' `BuildSpec`) written by `aadesh build`. */\ninterface BuildSpec {\n locale: string;\n defaultLocale: string;\n apiMessages: Record<string, string>;\n chromeMessages: Record<string, string>;\n destination: string;\n basePath: string;\n siteBasePath: string;\n locales: Array<{ code: string; name?: string }>;\n /** Absolute path of this locale's docs-overlay dir (`docs.<locale>/`), if any. */\n docsDir?: string;\n}\n\n/**\n * Read the localization build spec when `CLEAN_JSDOC_THEME_BUILD` points at one\n * (set by `aadesh build` per locale). When present, the theme stamps the API\n * translations and renders to the spec's `destination`/`basePath` instead of the\n * jsdoc.json values. Returns `null` for a normal (single-locale) build.\n */\nfunction readBuildSpec(): BuildSpec | null {\n const path = process.env.CLEAN_JSDOC_THEME_BUILD?.trim();\n if (!path) return null;\n const spec = JSON.parse(readFileSync(path, 'utf8')) as Partial<BuildSpec> & { version?: number };\n // Must match utils' BUILD_SPEC_VERSION — guards an old theme vs new aadesh mix.\n if (typeof spec.version === 'number' && spec.version !== 1) {\n throw new Error(\n `clean-jsdoc-theme: build spec version ${spec.version} unsupported ` +\n `(expected 1) — update clean-jsdoc-theme and aadesh together.`\n );\n }\n if (typeof spec.destination !== 'string' || typeof spec.basePath !== 'string') {\n throw new Error(`clean-jsdoc-theme: malformed build spec at \"${path}\".`);\n }\n return {\n locale: typeof spec.locale === 'string' ? spec.locale : '',\n defaultLocale: typeof spec.defaultLocale === 'string' ? spec.defaultLocale : 'en',\n apiMessages: spec.apiMessages ?? {},\n chromeMessages: spec.chromeMessages ?? {},\n destination: spec.destination,\n basePath: spec.basePath,\n siteBasePath: typeof spec.siteBasePath === 'string' ? spec.siteBasePath : '/',\n locales: Array.isArray(spec.locales) ? spec.locales : [],\n ...(typeof spec.docsDir === 'string' && spec.docsDir ? { docsDir: spec.docsDir } : {}),\n };\n}\n\n/**\n * The template entry JSDoc calls. Wraps {@link runPublish} so a failed build\n * fails the process: JSDoc 4 runs `publish()` inside a promise chain with no\n * rejection handler, so a thrown error was printed as `Unhandled rejection\n * <stack>` and JSDoc still exited 0 — invisible to CI, and to aadesh, which\n * checks each locale build's exit code. Every failure (strict-mode option\n * errors, a missing `plugins/markdown`, a bad build spec, a render setup\n * error) goes through {@link reportBuildFailure} instead.\n */\nexport async function publish(data: unknown, opts: JSDocOpts, tutorials?: unknown): Promise<void> {\n // Option errors/warnings are printed once, at the end of the build (see\n // `report.optionProblems` in runPublish). If the build throws first, print\n // them on the way out so a failure never hides them.\n const report: OptionProblemsReport = { optionProblems: () => {} };\n try {\n await runPublish(data, opts, tutorials, report);\n } catch (err) {\n report.optionProblems();\n reportBuildFailure(err, opts.debug === true || opts.verbose === true);\n }\n}\n\n/** Prints the non-strict option errors/warnings; set by runPublish after validation. */\ninterface OptionProblemsReport {\n optionProblems: () => void;\n}\n\n/** The slice of JSDoc's `jsdoc/util/logger` that {@link reportBuildFailure} uses. */\ninterface JSDocLogger {\n error: (message: string) => void;\n}\n\n/** JSDoc's logger — resolvable only inside a JSDoc process (see `jsdoc/env` above). */\nfunction loadJSDocLogger(): JSDocLogger {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return require('jsdoc/util/logger') as JSDocLogger;\n}\n\n/**\n * Report a failed build once and make the process exit non-zero. Inside JSDoc,\n * log through JSDoc's own logger: `logger.error` prints the message once and,\n * through JSDoc's `logger:error` listener, marks the run as failed. Normally\n * that sets a flag JSDoc turns into exit code 1 once `publish` settles; under\n * `--pedantic` the listener calls `cli.exit(1)`, which registers a process\n * `exit` handler that exits with 1 — it doesn't stop the process on the spot,\n * so the remaining work still finishes. `process.exitCode` is set too, as a\n * backstop.\n * Outside a JSDoc process (`jsdoc/util/logger` isn't resolvable — a direct\n * programmatic call, unit tests) rethrow, so the caller still gets the\n * rejection, and leave `process.exitCode` alone: the caller decides whether\n * the failure fails its process. `withStack` (JSDoc's `--debug`/`--verbose`)\n * adds the stack trace for bug reports. Exported for testing (`loadLogger` is\n * injectable).\n */\nexport function reportBuildFailure(\n err: unknown,\n withStack: boolean,\n loadLogger: () => JSDocLogger = loadJSDocLogger\n): void {\n let logger: JSDocLogger | undefined;\n try {\n logger = loadLogger();\n } catch {\n logger = undefined;\n }\n if (!logger || typeof logger.error !== 'function') throw err;\n process.exitCode = 1;\n const message = err instanceof Error ? err.message : String(err);\n const stack = withStack && err instanceof Error && err.stack ? `\\n${err.stack}` : '';\n logger.error(`${message}${stack}`);\n}\n\nasync function runPublish(\n data: unknown,\n opts: JSDocOpts,\n tutorials: unknown,\n report: OptionProblemsReport\n): Promise<void> {\n // Localization build mode (aadesh): a per-locale spec overrides the output\n // destination + base path and supplies the API translations to stamp in.\n const buildSpec = readBuildSpec();\n const destination = buildSpec?.destination ?? opts.destination;\n if (!destination || typeof destination !== 'string') {\n throw new Error(\n 'clean-jsdoc-theme publish: opts.destination is required ' +\n '(set \"opts.destination\" in your jsdoc.json).'\n );\n }\n\n // The theme depends on JSDoc's `plugins/markdown` to pre-render doclet\n // Markdown to HTML; bail early with an actionable message if it's missing.\n assertMarkdownPlugin();\n\n // Color only on a real TTY (and unless JSDoc's `--nocolor` is set).\n const color = Boolean(process.stdout.isTTY) && opts.nocolor !== true;\n\n // Kick off the project file-reading I/O NOW, so it runs concurrently with the\n // renderer load below. None of it (pkg resolution, source files, the docs\n // tree) needs setu/dwar/utils, so on large projects — where reading hundreds\n // of source files is non-trivial — it overlaps the multi-second module\n // evaluation instead of running serially after it. These collectors are\n // internally resilient (unreadable files are warned + skipped, never thrown),\n // so starting them before their await point can't surface an unhandled\n // rejection; we await them at their narrated stages below.\n const docsDir =\n typeof opts.docs === 'string' && opts.docs.trim().length > 0 ? opts.docs.trim() : undefined;\n const tutorialsDir =\n typeof opts.tutorials === 'string' && opts.tutorials.trim().length > 0\n ? opts.tutorials.trim()\n : undefined;\n // JSDoc's `templates.default.staticFiles` (verbatim passthrough + image search\n // fallback roots). `undefined` when unset, so the whole feature is inert then.\n const staticCfg = readStaticFilesConfig(opts);\n const pkgPromise = resolvePkg(data, opts);\n const sourcesPromise: Promise<SourceFileInput[]> = outputSourceFilesEnabled(opts)\n ? collectSourceFiles(data)\n : Promise.resolve([]);\n const docsPromise: Promise<DocInput[]> = docsDir ? collectDocs(docsDir) : Promise.resolve([]);\n\n // Stage progress (ora spinners) is on by default; `opts.progress: false`\n // silences it. ora loads first so the narrator can wrap the renderer load\n // (stage 1) too; a load failure degrades to silent rather than breaking.\n const ora = opts.progress === false ? null : await loadOra();\n const progress = createBuildProgress(ora);\n\n const [\n { generateSite, stampSite },\n { render },\n {\n validateThemeOpts,\n createGoogleFontResolver,\n formatDiagnostics,\n DiagnosticBag,\n formatBuildReport,\n formatRenderError,\n normalizeBasePath,\n withBase,\n toExtractManifest,\n normalizeCollapsibleSidebarSections,\n unmatchedCollapsibleSections,\n topLevelSectionLabels,\n normalizeScrollbar,\n },\n // Loaded sequentially (not Promise.all) so the spinner can step its label\n // through each module — the evaluation of these large ESM bundles is the\n // single longest, most event-loop-blocking stage, so visibly naming the\n // module in flight is what stops it from reading as a hang.\n ] = await progress.stage('Loading renderer', async ({ setText }) => {\n setText('Loading renderer (setu)');\n const setu = await loadSetu();\n setText('Loading renderer (dwar)');\n const dwar = await loadDwar();\n setText('Loading renderer (utils)');\n const utils = await loadUtils();\n return [setu, dwar, utils] as const;\n });\n\n // Normalized base-path prefix (`/` when unset). Threaded into every emitted\n // href — logos and custom assets here; dwar prefixes the rest at render time.\n const basePath = normalizeBasePath(buildSpec?.basePath ?? opts.basePath);\n // The OutputFile `path` stays relative; only the served href gets the prefix.\n const hrefForServed = (servedPath: string): string => withBase(basePath, '/' + servedPath);\n\n // Validate the theme options early (before any render work) so the developer\n // sees problems first. The Google-Font check is the one networked piece, kept\n // behind an injectable resolver in utils; it's fail-open, so an offline build\n // never breaks on it. Unknown keys get typo suggestions (`suggest-typos`),\n // never blanket warnings — JSDoc's own opts share this flat namespace. Leftover\n // v4 options (`theme_opts`, `base_url`, …) are the exception: they're known to\n // be ours, so they always warn with a migration hint (errors under strict).\n //\n // Strict mode: `opts.strict` (or nested `templates.default.strict`). When on\n // AND there are errors, log + throw to fail the build. Otherwise (the\n // resilient default) log and continue — a bad font/typo never breaks a build.\n const strict =\n opts.strict === true ||\n (opts.templates as { default?: { strict?: unknown } } | undefined)?.default?.strict === true;\n // Option problems found past validation — an unreadable footer/favicon/logo/\n // custom file, a dropped meta or customCssFile entry, a bad scrollbar or\n // collapsibleSidebarSections value. Resilient by default: warn and carry on.\n // Strict escalates them like the validation warnings: each prints as an error\n // and the build stops before anything is written (`failOnStrictOptionErrors`).\n const strictOptionErrors: string[] = [];\n const warnOption: WarnSink = (message) => {\n if (!strict) return console.warn(message);\n strictOptionErrors.push(message);\n console.error(message);\n };\n const failOnStrictOptionErrors = (): void => {\n if (strictOptionErrors.length === 0) return;\n throw new Error(\n `clean-jsdoc-theme: ${strictOptionErrors.length} option problem(s) in strict mode ` +\n '(see above). Fix them or unset `strict`.'\n );\n };\n // `node:https`, not the global fetch: see https-fetch.ts (Windows exit abort).\n const fontResolver = createGoogleFontResolver({ fetch: httpsFetch });\n const { value, diagnostics } = await progress.stage('Validating options', () =>\n validateThemeOpts({\n opts,\n fontResolver,\n unknownKeyPolicy: 'suggest-typos',\n knownNonThemeKeys: JSDOC_OWN_OPTS,\n checkV4Options: true,\n strict,\n })\n );\n\n if (diagnostics.list.length > 0) {\n const formatted = formatDiagnostics(diagnostics, { color });\n if (strict && diagnostics.hasErrors()) {\n console.error(formatted);\n throw new Error(\n 'clean-jsdoc-theme: opts validation failed in strict mode ' +\n '(see the diagnostics above). Fix the errors or unset `strict`.'\n );\n }\n // Advisory infos now. Errors and warnings are printed once, at the end of\n // the build — see `report.optionProblems` below.\n const notes = new DiagnosticBag();\n for (const d of diagnostics.list) if (d.level === 'info') notes.add(d);\n if (notes.list.length > 0) console.log(formatDiagnostics(notes, { color }));\n }\n\n // Non-strict option errors and warnings, printed exactly once, on stderr: at\n // the end of the build, near the last thing on screen, so a skipped llms.txt\n // or a font fallback can't scroll away behind the build log (or, via\n // `publish`, on the way out if the build throws). A localized build runs one\n // JSDoc process per locale, so each locale prints them once. Same as the\n // TypeDoc writer.\n let reported = false;\n report.optionProblems = () => {\n if (reported) return;\n reported = true;\n const problems = new DiagnosticBag();\n for (const d of diagnostics.list) if (d.level !== 'info') problems.add(d);\n if (problems.list.length > 0) console.warn(formatDiagnostics(problems, { color }));\n };\n\n // Resolved off the kickoff above (started concurrently with the renderer load).\n const pkg = await pkgPromise;\n\n // README (rendered to HTML by JSDoc into `opts.readme`) → home page; the\n // tutorials resolver tree → guide pages. Both flow through setu as ordinary\n // pages. Local images they reference (and those in JSDoc-comment prose) are\n // routed through the `_assets/` pipeline below, like `opts.docs` images.\n const readme =\n typeof opts.readme === 'string' && opts.readme.length > 0 ? opts.readme : undefined;\n const tutorialTree = normalizeTutorials(tutorials);\n\n // Source viewer pages + `Source: file:line` member links. Gated behind\n // JSDoc's `templates.default.outputSourceFiles` (default ON); reading files\n // is optional and self-skips on error, so this never aborts the build.\n const sourceLinkToComment = sourceLinkToCommentEnabled(opts);\n\n // The docs tree → prose pages at clean (unprefixed) slugs; `docGroups` orders\n // the doc-group sidebar sections, `defaultDocGroup` labels ungrouped docs. The\n // reads were started in the kickoff above (the bridge is the sanctioned I/O\n // layer; setu stays disk-free), so this stage just awaits the now-overlapped\n // work — narrated as a single step.\n // JSDoc `templates.default.staticFiles` passthrough: collect the included\n // files up front. Their dirs become fallback search roots for image resolution\n // (so a bare `![x](classes-io.png)` whose file lives in a staticFiles dir still\n // resolves + hashes), and the files themselves are copied verbatim to the\n // output after render (covering non-image assets). Read once; `undefined` when\n // the option is unset, so nothing changes for projects that don't use it.\n const staticFiles = staticCfg\n ? await progress.stage('Reading static files', () =>\n collectStaticFiles(staticCfg, (m) => console.warn(m))\n )\n : undefined;\n\n // ONE image collector for the whole build: docs, tutorials, README, and doclet\n // comments all route their local images through it (content-hashed `_assets/`,\n // SVG-inlined, deduped across sources). `staticFiles.searchDirs` are the B2\n // fallback roots. `consumed` (the source paths it copied) lets the verbatim\n // static-file pass skip images it already served from `_assets/`.\n const images = createImageCollector(staticFiles?.searchDirs ?? []);\n\n const { sources, docs } = await progress.stage('Reading sources & docs', async () => {\n const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);\n // Route the local images those docs reference through the shared collector\n // (copy + rewrite the src), so they cache-bust like the logo/custom assets.\n const base = docsDir\n ? await resolveDocImages(rawDocs, docsDir, images)\n : { docs: rawDocs };\n\n // Per-locale docs overlay (build mode): a locale's `docs.<locale>/` files win\n // over the default docs by path; default-only docs fall back. Both sets'\n // images accumulate on the shared collector; overlayDocs merges the content.\n if (!buildSpec?.docsDir) return { sources: srcs, docs: base.docs };\n const localeRaw = await collectDocs(buildSpec.docsDir);\n const locale = await resolveDocImages(localeRaw, buildSpec.docsDir, images);\n const merged = overlayDocs(\n { docs: base.docs, files: [], inlineSvgs: {} },\n { docs: locale.docs, files: [], inlineSvgs: {} }\n );\n return { sources: srcs, docs: merged.docs };\n });\n\n // Tutorials, the README, and JSDoc-comment (doclet) prose can all reference\n // local images with relative paths (`![x](../img/x.png)` / `<img src>`); route\n // them through the SAME shared collector. Tutorials resolve against the\n // tutorials dir, the README against the project root (its usual home), and each\n // doclet's images against its own source file's directory. Doclets are mutated\n // IN PLACE (salty hands out live references) BEFORE `generateSite`/`stampSite`\n // reads them.\n const { tutorialTree: resolvedTutorials, readme: resolvedReadme } = await progress.stage(\n 'Resolving prose images',\n async () => {\n const tree =\n tutorialsDir && tutorialTree.length > 0\n ? await resolveTutorialImages(tutorialTree, tutorialsDir, images)\n : tutorialTree;\n const md = readme ? await rewriteImageRefs(readme, process.cwd(), images) : readme;\n await resolveDocletImages(data, images);\n return { tutorialTree: tree, readme: md };\n }\n );\n\n // Every source's image assets now live on the one shared collector, deduped by\n // served path; the inline-SVG map is keyed by rewritten src for the renderer.\n const imageFiles = images.files;\n const allInlineSvgs = images.inlineSvgs;\n\n const docGroups = normalizeDocGroups(opts.docGroups);\n const defaultDocGroup =\n typeof opts.defaultDocGroup === 'string' && opts.defaultDocGroup.trim().length > 0\n ? opts.defaultDocGroup.trim()\n : undefined;\n\n // Sidebar config: `menu` (full control) takes precedence over `sectionOrder`.\n // Each accepts only well-formed input; anything else falls back to defaults.\n const sectionOrder = normalizeSectionOrder(opts.sectionOrder);\n const menu = normalizeMenu(opts.menu);\n const clubSidebarItems = opts.clubSidebarItems === true;\n const { value: collapsibleSidebarSections, warnings: collapsibleWarnings } =\n normalizeCollapsibleSidebarSections(opts.collapsibleSidebarSections);\n collapsibleWarnings.forEach((w) => warnOption(`clean-jsdoc-theme: ${w}`));\n // Scrollbar presentation mode (see #281); an unrecognized value warns and\n // falls back to `undefined`, so dwar defaults to `styled`.\n const { value: scrollbar, warnings: scrollbarWarnings } = normalizeScrollbar(opts.scrollbar);\n scrollbarWarnings.forEach((w) => warnOption(`clean-jsdoc-theme: ${w}`));\n // The enablement slice (provider selection + enableForAllExamples) gates setu's\n // `@playground` handling; the runtime slice is threaded into the theme instead.\n const playground = normalizePlayground(opts.playground);\n\n const siteOptions = {\n ...(pkg ? { pkg } : {}),\n ...(resolvedReadme ? { readme: resolvedReadme } : {}),\n ...(resolvedTutorials.length > 0 ? { tutorials: resolvedTutorials } : {}),\n ...(sources.length > 0 ? { sources } : {}),\n ...(sources.length > 0 && sourceLinkToComment ? { sourceLinkToComment } : {}),\n ...(docs.length > 0 ? { docs } : {}),\n ...(docGroups ? { docGroups } : {}),\n ...(defaultDocGroup ? { defaultDocGroup } : {}),\n ...(sectionOrder ? { sectionOrder } : {}),\n ...(menu ? { menu } : {}),\n ...(clubSidebarItems ? { clubSidebarItems } : {}),\n ...(collapsibleSidebarSections !== undefined ? { collapsibleSidebarSections } : {}),\n ...(playground ? { playground: playground.site } : {}),\n ...(includePrivateEnabled(opts) ? { includePrivate: true } : {}),\n };\n // Build mode stamps the locale's API translations in; a normal build doesn't.\n const manifest = await progress.stage('Generating pages', () =>\n buildSpec\n ? stampSite(data, buildSpec.apiMessages, siteOptions)\n : generateSite(data, siteOptions)\n );\n\n if (Array.isArray(collapsibleSidebarSections)) {\n const present = topLevelSectionLabels(manifest.nav);\n const unmatched = unmatchedCollapsibleSections(collapsibleSidebarSections, present);\n if (unmatched.length > 0) {\n warnOption(\n `clean-jsdoc-theme: collapsibleSidebarSections — no sidebar section matches ` +\n `${unmatched.map((l) => `'${l}'`).join(', ')}. ` +\n `Available sections: ${present.join(', ')}.`\n );\n }\n }\n\n // Localization extract mode (aadesh, Phase 3): when CLEAN_JSDOC_THEME_EXTRACT\n // names a path, write the translatable slot template there and STOP — skipping\n // the expensive render/island-bundle. aadesh spawns jsdoc with this\n // env var set to harvest the template, then drives the per-locale builds.\n failOnStrictOptionErrors();\n const extractPath = process.env.CLEAN_JSDOC_THEME_EXTRACT?.trim();\n if (extractPath) {\n const target = resolvePath(extractPath);\n await progress.stage('Writing extract manifest', async () => {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, JSON.stringify(toExtractManifest(manifest), null, 2) + '\\n', 'utf8');\n });\n console.log(\n `clean-jsdoc-theme: extract mode — wrote ${manifest.slots?.length ?? 0} slot(s) to ${target}`\n );\n report.optionProblems();\n return;\n }\n\n // Resolve siteName (text or logo set) and copy any local logo images into the\n // output before render, so the served paths are baked into the markup. The\n // shape was already validated above; `prepareSiteName` now only does the\n // local-logo file-copy I/O on the validated value.\n const { siteName, files: logoFiles } = await prepareSiteName(\n value.siteName,\n hrefForServed,\n warnOption\n );\n\n // Resilient font fallback: a family flagged `fonts/not-google` is dropped so\n // `resolveTheme` falls back to the default for that slot (the error was\n // already reported in the diagnostics block). Verified/unverified families\n // pass through.\n const notGoogle = new Set(\n diagnostics.list\n .filter((d) => d.code === 'fonts/not-google' && d.path)\n .map((d) => d.path as string)\n );\n const fonts: ValidatedFonts = { ...value.fonts };\n if (notGoogle.has('fonts.heading')) delete fonts.heading;\n if (notGoogle.has('fonts.body')) delete fonts.body;\n // Same resilient drop for per-locale fonts (`fonts.ja:heading`), so a bad\n // locale font falls back to the base/default rather than breaking the build.\n if (fonts.locales) {\n const cleaned: Record<string, FontSet> = {};\n for (const [loc, set] of Object.entries(fonts.locales)) {\n const s: FontSet = { ...set };\n if (notGoogle.has(`fonts.${loc}:heading`)) delete s.heading;\n if (notGoogle.has(`fonts.${loc}:body`)) delete s.body;\n cleaned[loc] = s;\n }\n fonts.locales = cleaned;\n }\n\n // Custom CSS/JS (v4 parity): inline strings pass through; custom files are\n // copied AS-IS to content-hashed `_assets` here (the I/O layer) and merged onto\n // the theme as hrefs, so dwar links them while render() stays pure. Empty/unset\n // → no fields added, so behavior is unchanged when unused.\n const customAssets = await resolveCustomAssets(opts, hrefForServed, warnOption);\n // Custom footer (v4 parity): inline HTML passes through; the `{ file }` form\n // is read here (the I/O layer) → a resolved string on the theme, so render()\n // stays pure. Unset/empty → default footer.\n const footer = await resolveFooter(opts.footer, warnOption);\n // Favicon (v4 parity, restored): the file is copied to a content-hashed\n // `_assets` asset here (the I/O layer) and dwar emits the `<link rel=\"icon\">`,\n // so render() stays pure. Hashed like the other custom assets. Unset → none.\n const favicon = await resolveFavicon(\n opts.favicon,\n opts.hashCustomAssets !== false,\n hrefForServed,\n warnOption\n );\n // Site-wide custom <meta> tags. Validated/normalized here (junk dropped +\n // warned); dwar does the escaping + de-dupe against its head defaults.\n const meta = normalizeMeta(opts.meta, warnOption);\n // Every option has been resolved by now; under strict, stop before rendering\n // or writing anything if any of them had a problem.\n failOnStrictOptionErrors();\n\n const absoluteDestination = resolvePath(destination);\n // Cache the island esbuild bundle across builds — see RenderOptions.islandCacheDir;\n // the dev/watch loop reuses it when rang/dwar are unchanged.\n const islandCacheDir = resolvePath(process.cwd(), 'node_modules', '.cache', 'clean-jsdoc-theme');\n const result = await progress.stage('Rendering site', () =>\n render(manifest, {\n theme: {\n ...resolveTheme(opts, siteName, fonts, basePath, buildSpec?.locale),\n ...customAssets.theme,\n ...(footer ? { footer } : {}),\n ...(favicon ? { favicon: favicon.href } : {}),\n ...(meta ? { meta } : {}),\n ...(scrollbar ? { scrollbar } : {}),\n },\n destination: absoluteDestination,\n islandCacheDir,\n inlineSvgs: allInlineSvgs,\n // Emit sitemap.xml when a public site URL is configured (the protocol needs\n // absolute URLs). In a localized build each locale's basePath yields that\n // locale's URLs, so each locale dir gets its own sitemap. `value.siteUrl` is\n // the validated form — a malformed URL warned above and lands here as\n // `undefined`, so we never hand dwar something it would silently drop.\n ...(value.siteUrl ? { siteUrl: value.siteUrl } : {}),\n // llms.txt / llms-full.txt (llmstxt.org). `undefined` means either unset or\n // \"enabled but no usable siteUrl\" — the latter already warned in validation.\n ...(value.llmsTxt ? { llmsTxt: value.llmsTxt } : {}),\n // Build mode: render chrome in the locale (SSR provider + island seeding)\n // and, with >1 locale, mount the language switcher.\n ...(buildSpec\n ? {\n locale: {\n code: buildSpec.locale,\n defaultLocale: buildSpec.defaultLocale,\n messages: buildSpec.chromeMessages,\n siteBasePath: buildSpec.siteBasePath,\n locales: buildSpec.locales.map((l) => ({ code: l.code, label: l.name ?? l.code })),\n },\n }\n : {}),\n })\n );\n\n const generatedFiles = [\n ...result.files,\n ...logoFiles,\n ...customAssets.files,\n ...imageFiles,\n ...(favicon?.files ?? []),\n ];\n\n // Static-file passthrough (A): copy each included file verbatim to its output\n // path. Skip any file the image pipeline already consumed (it's served hashed\n // from `_assets/`, so a root duplicate would be dead weight), and any path that\n // would clobber a generated file or a reserved theme dir — generated output\n // always wins; the collision is warned, never silently overwritten.\n const staticOutputFiles: OutputFile[] = [];\n if (staticFiles) {\n const generatedPaths = new Set(generatedFiles.map((f) => f.path));\n const RESERVED_PREFIXES = ['_assets/', '_islands/'];\n let skippedConsumed = 0;\n for (const f of staticFiles.files) {\n if (images.consumed.has(f.absSource)) {\n skippedConsumed++; // already hashed into `_assets/` and referenced there\n continue;\n }\n if (\n generatedPaths.has(f.outputPath) ||\n RESERVED_PREFIXES.some((p) => f.outputPath.startsWith(p))\n ) {\n console.warn(\n `clean-jsdoc-theme: static file '${f.outputPath}' would clobber generated output; skipping it.`\n );\n continue;\n }\n staticOutputFiles.push({ path: f.outputPath, contents: f.contents });\n }\n if (staticFiles.files.length > 0) {\n console.log(\n `clean-jsdoc-theme: staticFiles — copied ${staticOutputFiles.length} file(s) verbatim` +\n (skippedConsumed > 0 ? ` (${skippedConsumed} served hashed via _assets/)` : '') +\n '.'\n );\n }\n }\n\n const outputFiles = [...generatedFiles, ...staticOutputFiles];\n // Empty the destination first so a page removed/renamed since the last build\n // (or a stale content-hashed asset like `styles.<hash>.css`) doesn't linger in\n // the served site. Default on; opt out with `templates.default.cleanOutputDir:\n // false`. Skipped in localization build mode: each locale is a separate process\n // writing the default site to the root and others to `root/<locale>`, so a\n // recursive clean here would clobber a sibling locale's already-built output.\n if (!buildSpec && cleanOutputDirEnabled(opts)) {\n await progress.stage('Cleaning output', () =>\n rm(absoluteDestination, { recursive: true, force: true })\n );\n }\n await progress.stage('Writing files', () => writeOutputFiles(absoluteDestination, outputFiles));\n\n // Next.js-style build report: where the files landed, page/asset counts, and\n // per-route sizes (+ gzip). `node:zlib` is injected here as the gzip sizer so\n // utils stays node-free. Replaces the old single `rendered N page(s)…` line.\n const zlib = await import('node:zlib');\n const gzipSizer = (b: Uint8Array | string): number => zlib.gzipSync(b).length;\n console.log(\n formatBuildReport({\n files: outputFiles,\n stats: result.stats,\n destination,\n gzipSizer,\n color,\n })\n );\n\n report.optionProblems();\n\n // Skipped pages (render failures) are folded in right after the report so the\n // count is visible alongside the successful totals — never fatal.\n if (result.errors && result.errors.length > 0) {\n console.warn(\n `clean-jsdoc-theme: ${result.errors.length} page(s) failed to render and were skipped:`\n );\n for (const e of result.errors) {\n console.warn(formatRenderError(e));\n }\n }\n\n // Non-fatal authoring warnings (e.g. unbalanced inline-code backticks). The\n // pages still rendered; we surface these so the author can clean up the source.\n if (result.warnings && result.warnings.length > 0) {\n console.warn(\n `clean-jsdoc-theme: ${result.warnings.length} content warning(s) (non-fatal):`\n );\n for (const w of result.warnings) {\n console.warn(formatRenderError(w));\n }\n }\n\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;;AAIA,MAAM,oBAAoB,cAAc,YAAY,GAAG;AAIvD,MAAa,aAA6B,4BAAY;;;ACFtD,eAAsB,iBACpB,aACA,OACe;CACf,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,SAAS,KAAK,aAAa,KAAK,IAAI;EAC1C,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,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