clean-jsdoc-theme 5.0.0-alpha.3 → 5.0.0-alpha.4

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,"sources":["../src/publish.ts","../src/write-output-files.ts"],"sourcesContent":["'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 { readFile, readdir } 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, fileURLToPath } from 'node:url';\nimport type {\n CopyPageAction,\n CopyPageConfig,\n PageNavConfig,\n OutputFile,\n SiteLogo,\n SiteManifest,\n SiteName,\n ThemeColors,\n ThemeConfig,\n} from '@clean-jsdoc-theme/dwar';\nimport type { DocInput, MenuItem, SourceFileInput, TutorialInput } from '@clean-jsdoc-theme/setu';\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. The `new Function` wrapper around\n// `import.meta` keeps the CJS parser from rejecting it.\nfunction anchorPath(): string {\n if (typeof __filename === 'string') return __filename;\n try {\n const getEsmUrl = new Function(\n 'try { return import.meta && import.meta.url; } catch { return undefined; }'\n ) as () => string | undefined;\n const url = getEsmUrl();\n if (typeof url === 'string' && url.startsWith('file://')) {\n return fileURLToPath(url);\n }\n } catch {\n // fall through to the throw below.\n }\n throw new Error(\n 'clean-jsdoc-theme: could not determine the running module path ' +\n '(neither __filename nor import.meta.url resolved).'\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 tsup/esbuild 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']);\nconst loadDwar = (): Promise<typeof import('@clean-jsdoc-theme/dwar')> =>\n loadDep('@clean-jsdoc-theme/dwar', ['render', 'runPagefindAgainstDir']);\nconst loadUtils = (): Promise<typeof import('@clean-jsdoc-theme/utils')> =>\n loadDep('@clean-jsdoc-theme/utils', [\n 'validateThemeOpts',\n 'createGoogleFontResolver',\n 'formatDiagnostics',\n 'formatBuildReport',\n 'normalizeBasePath',\n 'withBase',\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 * 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 * 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 Pagefind index), 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 */\n templates?: { default?: { outputSourceFiles?: unknown; sourceLinkToComment?: unknown } };\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/** A subset of `{ heading, body, mono }` — the shape validated font overrides take. */\ninterface ValidatedFonts {\n heading?: string;\n body?: string;\n mono?: string;\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 */\nfunction resolveTheme(\n opts: JSDocOpts,\n siteName: SiteName | undefined,\n fonts: ValidatedFonts,\n basePath: 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\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 tokens: {\n ...defaultTheme.tokens,\n colors: { ...defaultTheme.tokens.colors, ...(colors ?? {}) },\n darkColors: { ...defaultTheme.tokens.darkColors, ...(darkColors ?? {}) },\n fonts: {\n heading: fonts.heading ?? defaultTheme.tokens.fonts.heading,\n body: fonts.body ?? defaultTheme.tokens.fonts.body,\n mono: fonts.mono ?? defaultTheme.tokens.fonts.mono,\n },\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/** 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 * 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(\n (p) => typeof p === 'string' && /(^|[\\\\/])markdown(\\.js)?$/i.test(p.trim())\n );\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 (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/** The palette keys a user may override under `opts.colors` / `opts.darkColors`. */\nconst COLOR_KEYS = ['bg', 'bgMuted', 'fg', 'fgMuted', 'accent', 'accentFg', 'border'] 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 * Resolve the local images a doc references and route them through the same\n * content-hashed `_assets/` pipeline the logo and custom files use. For each\n * `![alt](src)` whose `src` points to a file on disk, the file is copied to\n * `_assets/<base>.<hash><ext>` (cache-busted, deduped across docs) and the `src`\n * is rewritten to the root-relative `/_assets/<base>.<hash><ext>` (rang's\n * `MdxImg` adds the base path, like it does for links). A `src` is resolved\n * relative to the project root when it starts with `/`, else relative to the\n * doc's own directory; absolute (`http(s):`, `data:`), `#`-anchor, and\n * unreadable srcs are left untouched (the last with a warning). Returns the docs\n * with rewritten content plus the asset files to write. The bridge is the I/O\n * layer here, so setu/dwar only ever see the final `_assets/` paths.\n */\nexport async function resolveDocImages(\n docs: DocInput[],\n docsDir: string\n): Promise<{ docs: DocInput[]; files: OutputFile[]; inlineSvgs: Record<string, string> }> {\n if (docs.length === 0) return { docs, files: [], inlineSvgs: {} };\n const root = resolvePath(docsDir);\n const files: OutputFile[] = [];\n const seenServed = new Set<string>();\n // Inline-SVG markup keyed by the rewritten src, so the renderer can inline the\n // SVG (→ its `[data-theme]` styles follow the toggle) rather than `<img>` it.\n const inlineSvgs: Record<string, string> = {};\n // abs path → rewritten src (root-relative `/_assets/…`), or null if unreadable.\n const cache = new Map<string, string | null>();\n\n const resolveOne = async (rawSrc: string, docDir: string): Promise<string | null> => {\n const src = rawSrc.trim();\n if (!src || isServableUrl(src) || src.startsWith('#') || src.startsWith('data:')) return null;\n const abs = src.startsWith('/') ? resolvePath(src.slice(1)) : resolvePath(docDir, src);\n if (cache.has(abs)) return cache.get(abs) ?? null;\n let bytes: Buffer;\n try {\n bytes = await readFile(abs);\n } catch {\n console.warn(\n `clean-jsdoc-theme: could not read doc image '${src}' (resolved '${abs}'); leaving it as-is.`\n );\n cache.set(abs, null);\n return null;\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 return href;\n };\n\n const out: DocInput[] = [];\n for (const doc of docs) {\n const docDir = dirname(resolvePath(root, doc.path));\n const map = new Map<string, string>();\n for (const m of doc.content.matchAll(DOC_IMAGE_RE)) {\n const src = m[2];\n if (map.has(src)) continue;\n const href = await resolveOne(src, docDir);\n if (href) map.set(src, href);\n }\n if (map.size === 0) {\n out.push(doc);\n continue;\n }\n const content = doc.content.replace(DOC_IMAGE_RE, (full, pre, src, post) =>\n map.has(src) ? `${pre}${map.get(src)}${post}` : full\n );\n out.push({ ...doc, content });\n }\n return { docs: out, files, inlineSvgs };\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, the\n * Pagefind index), so 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/Pagefind\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>(\n label: string,\n fn: (handle: StageHandle) => T | Promise<T>\n ): 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\nexport async function publish(data: unknown, opts: JSDocOpts, tutorials?: unknown): Promise<void> {\n const 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 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 },\n { render, runPagefindAgainstDir },\n {\n validateThemeOpts,\n createGoogleFontResolver,\n formatDiagnostics,\n formatBuildReport,\n normalizeBasePath,\n withBase,\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(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. Note: local images referenced by README/tutorial Markdown are NOT\n // copied into the output — use absolute/served URLs for those.\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 const { sources, docs, docImageFiles, inlineSvgs } = await progress.stage(\n 'Reading sources & docs',\n async () => {\n const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);\n // Route the local images those docs reference through the content-hashed\n // `_assets/` pipeline (copy + rewrite the src), so they cache-bust like the\n // logo and custom assets. SVGs are additionally collected as inline markup\n // so render() can drop them into the page (theme-toggle-aware) — see\n // RenderOptions.inlineSvgs.\n const resolved = docsDir\n ? await resolveDocImages(rawDocs, docsDir)\n : { docs: rawDocs, files: [], inlineSvgs: {} };\n return {\n sources: srcs,\n docs: resolved.docs,\n docImageFiles: resolved.files,\n inlineSvgs: resolved.inlineSvgs,\n };\n }\n );\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\n const manifest = await progress.stage('Generating pages', () => generateSite(data, {\n ...(pkg ? { pkg } : {}),\n ...(readme ? { readme } : {}),\n ...(tutorialTree.length > 0 ? { tutorials: tutorialTree } : {}),\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 }));\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\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\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: { ...resolveTheme(opts, siteName, fonts, basePath), ...customAssets.theme },\n destination: absoluteDestination,\n islandCacheDir,\n inlineSvgs,\n })\n );\n\n const outputFiles = [...result.files, ...logoFiles, ...customAssets.files, ...docImageFiles];\n await progress.stage('Writing files', () =>\n writeOutputFiles(absoluteDestination, outputFiles)\n );\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 // 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(` - ${e.slug}: ${e.message}`);\n }\n }\n\n // Pagefind is optional; if the user doesn't have it installed we don't\n // want to fail the whole build. Surface the failure as a warning (the stage\n // marks ✗, then this note clarifies it's non-fatal).\n try {\n await progress.stage('Indexing search (pagefind)', () =>\n runPagefindAgainstDir(absoluteDestination)\n );\n } catch (err) {\n console.warn(\n `clean-jsdoc-theme: pagefind step skipped (optional) — ${(err as Error).message}`\n );\n }\n\n}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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,MACb;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,cAAc,CAAC,GAAG,OAAO,OAAO,GAAG,WAAW,GAAG,aAAa,OAAO,GAAG,aAAa;AAC3F,QAAM,SAAS;AAAA,IAAM;AAAA,IAAiB,MACpC,iBAAiB,qBAAqB,WAAW;AAAA,EACnD;AAKA,QAAM,OAAO,MAAM,OAAO,MAAW;AACrC,QAAM,YAAY,CAAC,MAAmC,KAAK,SAAS,CAAC,EAAE;AACvE,UAAQ;AAAA,IACN,kBAAkB;AAAA,MAChB,OAAO;AAAA,MACP,OAAO,OAAO;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAIA,MAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;AAC7C,YAAQ;AAAA,MACN,sBAAsB,OAAO,OAAO,MAAM;AAAA,IAC5C;AACA,eAAW,KAAK,OAAO,QAAQ;AAC7B,cAAQ,KAAK,OAAO,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE;AAAA,IAC5C;AAAA,EACF;AAKA,MAAI;AACF,UAAM,SAAS;AAAA,MAAM;AAAA,MAA8B,MACjD,sBAAsB,mBAAmB;AAAA,IAC3C;AAAA,EACF,SAAS,KAAK;AACZ,YAAQ;AAAA,MACN,8DAA0D,IAAc,OAAO;AAAA,IACjF;AAAA,EACF;AAEF;","names":["import_promises","import_node_path","resolvePath","children","joinPath"]}
1
+ {"version":3,"sources":["../src/publish.ts","../src/write-output-files.ts"],"sourcesContent":["'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, 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, fileURLToPath } from 'node:url';\nimport type {\n CopyPageAction,\n CopyPageConfig,\n PageNavConfig,\n OutputFile,\n SiteLogo,\n SiteManifest,\n SiteName,\n ThemeColors,\n ThemeConfig,\n} from '@clean-jsdoc-theme/dwar';\nimport type { DocInput, MenuItem, SourceFileInput, TutorialInput } from '@clean-jsdoc-theme/setu';\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. The `new Function` wrapper around\n// `import.meta` keeps the CJS parser from rejecting it.\nfunction anchorPath(): string {\n if (typeof __filename === 'string') return __filename;\n try {\n const getEsmUrl = new Function(\n 'try { return import.meta && import.meta.url; } catch { return undefined; }'\n ) as () => string | undefined;\n const url = getEsmUrl();\n if (typeof url === 'string' && url.startsWith('file://')) {\n return fileURLToPath(url);\n }\n } catch {\n // fall through to the throw below.\n }\n throw new Error(\n 'clean-jsdoc-theme: could not determine the running module path ' +\n '(neither __filename nor import.meta.url resolved).'\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 tsup/esbuild 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', 'runPagefindAgainstDir']);\nconst loadUtils = (): Promise<typeof import('@clean-jsdoc-theme/utils')> =>\n loadDep('@clean-jsdoc-theme/utils', [\n 'validateThemeOpts',\n 'createGoogleFontResolver',\n 'formatDiagnostics',\n 'formatBuildReport',\n 'normalizeBasePath',\n 'withBase',\n 'toExtractManifest',\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 * 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 * 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 Pagefind index), 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 */\n templates?: { default?: { outputSourceFiles?: unknown; sourceLinkToComment?: unknown } };\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\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 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/** 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 * 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 (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/** The palette keys a user may override under `opts.colors` / `opts.darkColors`. */\nconst COLOR_KEYS = ['bg', 'bgMuted', 'fg', 'fgMuted', 'accent', 'accentFg', 'border'] 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 * Resolve the local images a doc references and route them through the same\n * content-hashed `_assets/` pipeline the logo and custom files use. For each\n * `![alt](src)` whose `src` points to a file on disk, the file is copied to\n * `_assets/<base>.<hash><ext>` (cache-busted, deduped across docs) and the `src`\n * is rewritten to the root-relative `/_assets/<base>.<hash><ext>` (rang's\n * `MdxImg` adds the base path, like it does for links). A `src` is resolved\n * relative to the project root when it starts with `/`, else relative to the\n * doc's own directory; absolute (`http(s):`, `data:`), `#`-anchor, and\n * unreadable srcs are left untouched (the last with a warning). Returns the docs\n * with rewritten content plus the asset files to write. The bridge is the I/O\n * layer here, so setu/dwar only ever see the final `_assets/` paths.\n */\nexport async function resolveDocImages(\n docs: DocInput[],\n docsDir: string\n): Promise<{ docs: DocInput[]; files: OutputFile[]; inlineSvgs: Record<string, string> }> {\n if (docs.length === 0) return { docs, files: [], inlineSvgs: {} };\n const root = resolvePath(docsDir);\n const files: OutputFile[] = [];\n const seenServed = new Set<string>();\n // Inline-SVG markup keyed by the rewritten src, so the renderer can inline the\n // SVG (→ its `[data-theme]` styles follow the toggle) rather than `<img>` it.\n const inlineSvgs: Record<string, string> = {};\n // abs path → rewritten src (root-relative `/_assets/…`), or null if unreadable.\n const cache = new Map<string, string | null>();\n\n const resolveOne = async (rawSrc: string, docDir: string): Promise<string | null> => {\n const src = rawSrc.trim();\n if (!src || isServableUrl(src) || src.startsWith('#') || src.startsWith('data:')) return null;\n const abs = src.startsWith('/') ? resolvePath(src.slice(1)) : resolvePath(docDir, src);\n if (cache.has(abs)) return cache.get(abs) ?? null;\n let bytes: Buffer;\n try {\n bytes = await readFile(abs);\n } catch {\n console.warn(\n `clean-jsdoc-theme: could not read doc image '${src}' (resolved '${abs}'); leaving it as-is.`\n );\n cache.set(abs, null);\n return null;\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 return href;\n };\n\n const out: DocInput[] = [];\n for (const doc of docs) {\n const docDir = dirname(resolvePath(root, doc.path));\n const map = new Map<string, string>();\n for (const m of doc.content.matchAll(DOC_IMAGE_RE)) {\n const src = m[2];\n if (map.has(src)) continue;\n const href = await resolveOne(src, docDir);\n if (href) map.set(src, href);\n }\n if (map.size === 0) {\n out.push(doc);\n continue;\n }\n const content = doc.content.replace(DOC_IMAGE_RE, (full, pre, src, post) =>\n map.has(src) ? `${pre}${map.get(src)}${post}` : full\n );\n out.push({ ...doc, content });\n }\n return { docs: out, files, inlineSvgs };\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, the\n * Pagefind index), so 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/Pagefind\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 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, runPagefindAgainstDir },\n {\n validateThemeOpts,\n createGoogleFontResolver,\n formatDiagnostics,\n formatBuildReport,\n normalizeBasePath,\n withBase,\n toExtractManifest,\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. Note: local images referenced by README/tutorial Markdown are NOT\n // copied into the output — use absolute/served URLs for those.\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 const { sources, docs, docImageFiles, inlineSvgs } = await progress.stage(\n 'Reading sources & docs',\n async () => {\n const [srcs, rawDocs] = await Promise.all([sourcesPromise, docsPromise]);\n // Route the local images those docs reference through the content-hashed\n // `_assets/` pipeline (copy + rewrite the src), so they cache-bust like the\n // logo and custom assets. SVGs are additionally collected as inline markup\n // so render() can drop them into the page (theme-toggle-aware) — see\n // RenderOptions.inlineSvgs.\n const base = docsDir\n ? await resolveDocImages(rawDocs, docsDir)\n : { docs: rawDocs, files: [] as OutputFile[], inlineSvgs: {} as Record<string, string> };\n\n // Per-locale docs overlay (build mode): a locale's `docs.<locale>/` files\n // win over the default docs by path; default-only docs fall back, so a\n // partially-translated docs tree still renders the untranslated pages.\n // Each set's images resolve against its OWN root, then merge.\n if (!buildSpec?.docsDir) {\n return {\n sources: srcs,\n docs: base.docs,\n docImageFiles: base.files,\n inlineSvgs: base.inlineSvgs,\n };\n }\n const localeRaw = await collectDocs(buildSpec.docsDir);\n const locale = await resolveDocImages(localeRaw, buildSpec.docsDir);\n const merged = overlayDocs(base, locale);\n return {\n sources: srcs,\n docs: merged.docs,\n docImageFiles: merged.files,\n inlineSvgs: merged.inlineSvgs,\n };\n }\n );\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\n const siteOptions = {\n ...(pkg ? { pkg } : {}),\n ...(readme ? { readme } : {}),\n ...(tutorialTree.length > 0 ? { tutorials: tutorialTree } : {}),\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 };\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 // 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/Pagefind. 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\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 },\n destination: absoluteDestination,\n islandCacheDir,\n inlineSvgs,\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 outputFiles = [...result.files, ...logoFiles, ...customAssets.files, ...docImageFiles];\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 // 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(` - ${e.slug}: ${e.message}`);\n }\n }\n\n // Pagefind is optional; if the user doesn't have it installed we don't\n // want to fail the whole build. Surface the failure as a warning (the stage\n // marks ✗, then this note clarifies it's non-fatal).\n try {\n await progress.stage('Indexing search (pagefind)', () =>\n runPagefindAgainstDir(absoluteDestination)\n );\n } catch (err) {\n console.warn(`clean-jsdoc-theme: pagefind step skipped (optional) — ${(err as Error).message}`);\n }\n}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAAA,mBAAoD;AACpD,qBAA6B;AAC7B,yBAA2B;AAC3B,IAAAC,oBAAqF;AACrF,sBAA6C;;;ACP7C,sBAAiC;AACjC,uBAA8B;AAG9B,eAAsB,iBACpB,aACA,OACe;AACf,aAAW,QAAQ,OAAO;AACxB,UAAM,aAAS,uBAAK,aAAa,KAAK,IAAI;AAC1C,cAAM,2BAAM,0BAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAChD,UAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW,OAAO,KAAK,KAAK,QA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