@thallylabs/migrate 0.2.11 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/index.js +829 -102
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/repository.ts","../src/components.ts","../src/frontmatter.ts","../src/mdx.ts","../src/builtin-components.ts","../src/path.ts","../src/docusaurus.ts","../src/navigation.ts","../src/fern.ts","../src/render.ts","../src/url.ts","../src/remote-api.ts"],"sourcesContent":["/**\n * Repository adapter for the shared migration engine. Traversal is bounded;\n * `scanFiles` follows a symbolic link only when its resolved real path stays\n * inside the repository checkout (this covers a submodule mounted as a\n * symlink, e.g. Oasis's `docs/core -> ../external/oasis-core/docs`) and\n * guards against a cycle, but every other directory walk in this file still\n * skips symlinks outright. Git is always invoked with an argument array so\n * source-controlled branch names can never become shell commands.\n */\n\nimport { compileSync } from '@mdx-js/mdx'\nimport { spawn } from 'node:child_process'\nimport {\n closeSync,\n existsSync,\n lstatSync,\n openSync,\n readFileSync,\n readSync,\n readdirSync,\n realpathSync,\n rmSync,\n statSync,\n} from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, extname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path'\n\nimport { parse as parseYaml } from 'yaml'\nimport * as ts from 'typescript'\n\nimport { createComponentMigrator, declarationsReferenceBrowserGlobal, hasAnyFunctionValuedProp, normalizeIndentedFences, propsTargetExtractedClientComponent } from './components.js'\n\nimport {\n addDocusaurusTranslatedHeadingAliases,\n expandDocusaurusDocCardLists,\n projectDocusaurusNavigation,\n readDocusaurusRedirects,\n readDocusaurusSiteOrigin,\n readDocusaurusSiteSettings,\n readDocusaurusSidebars,\n readDocusaurusThemeColor,\n rewriteDocusaurusLinks,\n resolveDocusaurusPageIdentity,\n type DocusaurusPageDescriptor,\n type DocusaurusSidebars,\n} from './docusaurus.js'\nimport type { FernApiSection } from './fern.js'\nimport { projectFernNavigation, readFernConfig } from './fern.js'\nimport { escapeFernLiteralBraces, functionDeclaredNames, parseMarkdownPage, normalizeExplicitHeadingIds, protectMathBlocks, replaceLinkWithAnchor, replaceOutsideCode, replaceUnknownComponents, rewriteFernRelativePageLinks } from './mdx.js'\nimport {\n addMintlifyDirectoryRedirects,\n addMintlifyHomepageRedirects,\n buildNavigationFromPages,\n isDocumentationExtension,\n mintlifyAllVersionPrefixes,\n mintlifyDefaultVersionPrefixes,\n mintlifyNavigationApiReferences,\n projectMintlifyNavigation,\n pruneMissingNavigationPages,\n readMintlifyConfig,\n type MintlifyApiSpecReference,\n} from './navigation.js'\nimport {\n normalizeAssetPath,\n mintlifyLocalizedReference,\n pageIdFromReference,\n resolveWithin,\n resolveWithinRoot,\n trimEdgeSlashes,\n trimTrailingSlashes,\n} from './path.js'\nimport type {\n MigrationAsset,\n MigrationBundle,\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationPlatform,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_SOURCE_FILES = 5_000\nconst MAX_PAGE_BYTES = 2_000_000\nconst MAX_ASSET_BYTES = 25_000_000\nconst MAX_TOTAL_ASSET_BYTES = 500_000_000\n/** A Git LFS pointer file's fixed opening line (the smudge filter replaces this with the real binary; skipping it during clone leaves this text in place). */\nconst GIT_LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/v1'\n\n/** A small text file starting with the fixed Git LFS pointer line, not real asset content. */\nfunction isGitLfsPointer(content: Buffer): boolean {\n return content.length < 1024 && content.toString('utf8', 0, GIT_LFS_POINTER_PREFIX.length) === GIT_LFS_POINTER_PREFIX\n}\nconst IGNORED_DIRECTORIES = new Set([\n '.git', '.github', '.next', '.turbo', '.vercel', '.vscode',\n 'node_modules', 'dist', 'build', 'coverage',\n])\n// `dist`/`build`/`coverage` are build output when found while *looking for*\n// a docs root (root-detection BFS below, which walks the whole repository\n// checkout) — but once a docs content root is actually confirmed, a\n// same-named subdirectory inside it is real content, not output (e.g.\n// oasisprotocol/docs's `docs/build/`, a live section of the site).\n// `scanFiles`'s own walk is always already confined to a confirmed content\n// root, so it uses this narrower set instead of `IGNORED_DIRECTORIES`.\nfunction isIgnoredContentDirectory(name: string): boolean {\n return name.startsWith('.') || name === 'node_modules'\n}\nconst ASSET_DIRECTORIES = new Set(['assets', 'images', 'img', 'media', 'public', 'static'])\nconst ASSET_EXTENSIONS = new Set([\n '.avif', '.bmp', '.gif', '.ico', '.jpeg', '.jpg', '.m4a', '.mp3', '.mp4',\n '.ogg', '.pdf', '.png', '.svg', '.wav', '.webm', '.webp',\n])\nconst REPOSITORY_ONLY_DOCUMENTS = new Set([\n 'agents.md', 'claude.md', 'code_of_conduct.md', 'contributing.md',\n 'license.md', 'readme.md', 'security.md',\n])\nconst SNIPPET_DIRECTORIES = new Set(['snippets', '_snippets', 'partials', '_partials'])\n// Matches a default import (`import Name from '...'`), a default-as-named\n// import (`import { default as Name } from '...'`), and a plain named import\n// (`import { Name } from '...'`) — Mintlify snippets can export either way.\nconst SNIPPET_IMPORT_PATTERN = /\\bimport\\s+(?:\\{\\s*(?:default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}|([A-Z][A-Za-z0-9_]*))\\s+from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?/g\nconst SNIPPET_VALUE_IMPORT_PATTERN = /\\bimport\\s*\\{([^{}]+)\\}\\s*from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?/g\n\n/**\n * Mintlify's `<Snippet file=\"path.mdx\" />` tag form: unlike the import form\n * above, this never needs a matching `import` statement — `file` is a path\n * relative to the project's `snippets/` directory (Mintlify's own\n * convention; see `resolveSnippetPath`'s sibling below for the actual\n * lookup). Both self-closing and paired spellings are matched; a paired\n * tag's own children (if any) are always discarded in favor of the\n * resolved snippet's real content, matching Mintlify's own renderer.\n */\nconst SNIPPET_TAG_PATTERN = /<Snippet\\s+file=(?:\"([^\"]+)\"|'([^']+)')\\s*(?:\\/>|>[\\s\\S]*?<\\/Snippet>)/g\nconst MINTIGNORE_FILENAME = '.mintignore'\ninterface IgnoreMatcher {\n add(patterns: string): IgnoreMatcher\n ignores(pathname: string): boolean\n}\n// `ignore`'s CJS default export is mistyped under NodeNext module resolution\n// (the default import resolves to the whole module namespace); load it\n// through `require` and type it locally instead of fighting the interop.\nconst createIgnoreMatcher = createRequire(import.meta.url)('ignore') as () => IgnoreMatcher\n\n/** Dotfile directories (`.tooling`, `.vale`, tool/editor config, ...) never hold docs pages. */\nfunction isIgnoredDirectory(name: string): boolean {\n return name.startsWith('.') || IGNORED_DIRECTORIES.has(name)\n}\n\nconst OPENAPI_FILENAMES = new Set([\n 'openapi.json', 'openapi.yaml', 'openapi.yml',\n 'swagger.json', 'swagger.yaml', 'swagger.yml',\n])\n\nexport interface GitHubRepositorySource {\n owner: string\n repo: string\n branch: string\n docsDir: string\n cloneUrl: string\n}\n\nexport interface RepositoryMigrationOptions {\n repositoryDir: string\n sourceUrl: string\n docsDir?: string\n platform?: MigrationPlatform\n /** @internal Prefix used by additional Docusaurus docs-plugin instances. */\n docusaurusRoutePrefix?: string\n /** @internal Prevent recursive discovery while importing one plugin root. */\n docusaurusSkipPlugins?: boolean\n /** @internal Additional docs plugins default to autogenerated navigation. */\n docusaurusSkipSidebar?: boolean\n /** @internal A version's sidebar is parsed as static data. */\n docusaurusSidebarPath?: string\n /** @internal Static assets are shared across docs-plugin instances. */\n docusaurusSkipAssets?: boolean\n /** @internal Redirects are global config, read once, not per plugin instance. */\n docusaurusSkipRedirects?: boolean\n}\n\ninterface DocusaurusPluginRoot {\n docsDir: string\n routePrefix: string\n}\n\ninterface DocusaurusArchiveRoot extends DocusaurusPluginRoot {\n label: string\n sidebarPath?: string\n}\n\nconst DOCUSAURUS_CONFIG_FILENAMES = [\n 'docusaurus.config.js',\n 'docusaurus.config.ts',\n 'docusaurus.config.mjs',\n]\n\nfunction hasDocusaurusConfig(directory: string): boolean {\n return DOCUSAURUS_CONFIG_FILENAMES.some((filename) => {\n const path = resolveWithin(directory, filename)\n return existsSync(path) && lstatSync(path).isFile()\n })\n}\n\nfunction hasMintlifyConfig(directory: string): boolean {\n return ['docs.json', 'mint.json'].some((filename) => {\n const path = resolveWithin(directory, filename)\n if (!existsSync(path) || !lstatSync(path).isFile()) return false\n if (filename === 'mint.json') return true\n try {\n const config = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>\n return String(config.$schema ?? '').includes('mintlify') || 'navigation' in config\n } catch {\n return false\n }\n })\n}\n\n/**\n * Recursively counts `.md`/`.mdx` files under `directory` (skipping\n * ignored/symlinked directories, same as the root-finding BFS above), for\n * ranking two candidate project roots against each other. Bounded so a huge\n * false-positive candidate (e.g. `node_modules` slipping past\n * `isIgnoredDirectory`) can't make root detection itself slow.\n */\nfunction countMarkdownPages(directory: string, limit = 20_000): number {\n let count = 0\n const stack: Array<string> = [directory]\n while (stack.length > 0 && count < limit) {\n const current = stack.pop()!\n let entries: Array<Dirent>\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n continue\n }\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue\n if (entry.isDirectory()) {\n if (!isIgnoredDirectory(entry.name)) stack.push(resolveWithin(current, entry.name))\n } else if (/\\.mdx?$/i.test(entry.name)) {\n count++\n }\n }\n }\n return count\n}\n\n/**\n * Multiple config files can each look like a valid project root in the same\n * repository (Infisical ships both a top-level `company/mint.json` handbook\n * and `docs/docs.json`, the real docs). Picking the first one a breadth-\n * first walk happens to reach silently imports the wrong, usually much\n * smaller, site. Rank every candidate instead: `docs.json` before\n * `mint.json` (Mintlify's own current format), then a directory literally\n * named `docs`, then whichever has the most actual content — and warn\n * whenever there was more than one candidate, so a wrong guess is visible\n * and `--docs-dir` is offered as the fix, even when the ranking picked the\n * one the caller actually wanted.\n */\nfunction pickPreferredDocsRoot(\n candidates: Array<string>,\n repositoryDir: string,\n platformLabel: string,\n warnings: Array<MigrationWarning> | undefined,\n rank?: (directory: string) => number,\n): string {\n const ranked = [...candidates].sort((left, right) => {\n const byRank = (rank?.(right) ?? 0) - (rank?.(left) ?? 0)\n if (byRank !== 0) return byRank\n const byName = (basename(right) === 'docs' ? 1 : 0) - (basename(left) === 'docs' ? 1 : 0)\n if (byName !== 0) return byName\n return countMarkdownPages(right) - countMarkdownPages(left)\n })\n const winner = ranked[0]\n if (candidates.length > 1 && warnings) {\n const relativePaths = candidates.map((candidate) => relative(repositoryDir, candidate) || '.')\n warnings.push({\n code: 'unsupported-config',\n message: `Multiple possible ${platformLabel} project roots were found (${relativePaths.join(', ')}); `\n + `${relative(repositoryDir, winner) || '.'} was picked. Pass --docs-dir to choose a different one if this is wrong.`,\n source: '.',\n })\n }\n return winner\n}\n\nfunction findMintlifyProjectRoot(repositoryDir: string, docsDir?: string, warnings?: Array<MigrationWarning>): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasMintlifyConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n const candidates: Array<string> = []\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasMintlifyConfig(current.directory)) candidates.push(current.directory)\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({ directory: resolveWithin(current.directory, entry.name), depth: current.depth + 1 })\n }\n }\n if (candidates.length === 0) return null\n return pickPreferredDocsRoot(candidates, repositoryDir, 'Mintlify', warnings, (directory) => (\n existsSync(resolveWithin(directory, 'docs.json')) ? 1 : 0\n ))\n}\n\nfunction hasFernConfig(directory: string): boolean {\n return ['docs.yml', 'fern.config.json'].every((filename) => {\n const path = resolveWithin(directory, filename)\n return existsSync(path) && lstatSync(path).isFile()\n })\n}\n\nfunction findFernProjectRoot(repositoryDir: string, docsDir?: string): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasFernConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasFernConfig(current.directory)) return current.directory\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({ directory: resolveWithin(current.directory, entry.name), depth: current.depth + 1 })\n }\n }\n return null\n}\n\nfunction findDocusaurusProjectRoot(repositoryDir: string, docsDir?: string, warnings?: Array<MigrationWarning>): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasDocusaurusConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n\n const candidates: Array<string> = []\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasDocusaurusConfig(current.directory)) candidates.push(current.directory)\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({\n directory: resolveWithin(current.directory, entry.name),\n depth: current.depth + 1,\n })\n }\n }\n if (candidates.length === 0) return null\n return pickPreferredDocsRoot(candidates, repositoryDir, 'Docusaurus', warnings)\n}\n\nfunction readDocusaurusConfigSource(projectRoot: string): string {\n const path = DOCUSAURUS_CONFIG_FILENAMES\n .map((filename) => resolveWithin(projectRoot, filename))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile())\n if (!path || lstatSync(path).size > 1_000_000) return ''\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Scans forward from a `{` for its matching `}`, skipping over string,\n * template, and comment contents so braces inside them don't throw off the\n * depth count. Returns -1 if the object is never closed.\n */\nfunction matchingBraceIndex(source: string, openBraceIndex: number): number {\n let depth = 0\n for (let i = openBraceIndex; i < source.length; i++) {\n const ch = source[i]\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n const quote = ch\n i++\n while (i < source.length && source[i] !== quote) {\n if (source[i] === '\\\\') i++\n i++\n }\n continue\n }\n if (ch === '/' && source[i + 1] === '/') {\n const newline = source.indexOf('\\n', i)\n i = newline === -1 ? source.length : newline\n continue\n }\n if (ch === '/' && source[i + 1] === '*') {\n const end = source.indexOf('*/', i + 2)\n i = end === -1 ? source.length : end + 1\n continue\n }\n if (ch === '{') depth++\n else if (ch === '}') {\n depth--\n if (depth === 0) return i\n }\n }\n return -1\n}\n\n/** Finds a `key: 'value'` or `key: \"value\"` pair at the top level of an object body (not nested inside a further `{`, `[`, or `(`). */\nfunction topLevelStringProperty(objectBody: string, key: string): string | undefined {\n let depth = 0\n const keyPattern = new RegExp(`^${key}\\\\s*:\\\\s*(['\"])`)\n for (let i = 0; i < objectBody.length; i++) {\n const ch = objectBody[i]\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n const quote = ch\n i++\n while (i < objectBody.length && objectBody[i] !== quote) {\n if (objectBody[i] === '\\\\') i++\n i++\n }\n continue\n }\n if (ch === '/' && objectBody[i + 1] === '/') {\n const newline = objectBody.indexOf('\\n', i)\n i = newline === -1 ? objectBody.length : newline\n continue\n }\n if (ch === '/' && objectBody[i + 1] === '*') {\n const end = objectBody.indexOf('*/', i + 2)\n i = end === -1 ? objectBody.length : end + 1\n continue\n }\n if (ch === '{' || ch === '[' || ch === '(') {\n depth++\n continue\n }\n if (ch === '}' || ch === ']' || ch === ')') {\n depth--\n continue\n }\n if (depth === 0) {\n const match = keyPattern.exec(objectBody.slice(i))\n if (match) {\n const quote = match[1]\n const valueStart = i + match[0].length\n const valueEnd = objectBody.indexOf(quote, valueStart)\n if (valueEnd !== -1) return objectBody.slice(valueStart, valueEnd)\n }\n }\n }\n return undefined\n}\n\nfunction primaryDocusaurusDocsDirectory(projectRoot: string): string {\n const source = readDocusaurusConfigSource(projectRoot)\n // The classic preset's `docs: { ... }` object configures the primary docs\n // instance. Its `path` (when present) must come from directly inside that\n // object, not from a `path` belonging to a nested value (e.g. a versions\n // entry) or to an unrelated plugin's config further down the file — a\n // brace-blind regex can walk straight through the docs object's closing\n // brace into the next plugin's `path` (see the standalone content-docs\n // plugin case handled by `additionalDocusaurusPluginRoots`).\n const docsKeyMatch = source.match(/\\bdocs\\s*:\\s*\\{/)\n let configured: string | undefined\n if (docsKeyMatch?.index !== undefined) {\n const openBrace = docsKeyMatch.index + docsKeyMatch[0].length - 1\n const closeBrace = matchingBraceIndex(source, openBrace)\n if (closeBrace !== -1) {\n configured = topLevelStringProperty(source.slice(openBrace + 1, closeBrace), 'path')\n }\n }\n return trimTrailingSlashes(configured?.replace(/^\\.\\//, '') ?? '') || 'docs'\n}\n\n/** Discover archived docs and translations without evaluating project config. */\nfunction docusaurusArchiveRoots(projectRoot: string, repositoryDir: string, warnings: Array<MigrationWarning>): Array<DocusaurusArchiveRoot> {\n const archives: Array<DocusaurusArchiveRoot> = []\n const relativeRoot = relative(repositoryDir, projectRoot).replace(/\\\\/g, '/')\n const directoryNames = (directory: string): Array<string> => {\n const path = resolveWithin(projectRoot, directory)\n if (!existsSync(path) || !lstatSync(path).isDirectory()) return []\n return readdirSync(path, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())\n .map((entry) => entry.name).sort()\n }\n let versions = directoryNames('versioned_docs').filter((name) => /^version-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))\n const versionsPath = resolveWithin(projectRoot, 'versions.json')\n if (existsSync(versionsPath) && lstatSync(versionsPath).isFile()) {\n try {\n if (lstatSync(versionsPath).size > 100_000) throw new Error('file exceeds the 100 KB limit')\n const declared: unknown = JSON.parse(readFileSync(versionsPath, 'utf8'))\n if (!Array.isArray(declared) || !declared.every((value) => typeof value === 'string')) throw new Error('expected an array of version names')\n const declaredOrder = declared.map((value) => `version-${value}`)\n versions = [...declaredOrder.filter((name) => versions.includes(name)), ...versions.filter((name) => !declaredOrder.includes(name))]\n } catch (error) {\n warnings.push({ code: 'unsupported-config', message: `Docusaurus versions.json could not be read safely: ${error instanceof Error ? error.message : String(error)}` })\n }\n }\n const sidebarPath = (version: string): string | undefined => {\n const candidates = ['json', 'js', 'cjs', 'mjs', 'ts'].map((extension) => `versioned_sidebars/${version}-sidebars.${extension}`)\n return candidates.find((candidate) => {\n const path = resolveWithin(projectRoot, candidate)\n return existsSync(path) && lstatSync(path).isFile()\n })\n }\n const add = (directory: string, routePrefix: string, label: string, sidebar?: string): void => {\n const docsDir = [relativeRoot, directory].filter(Boolean).join('/')\n archives.push({ docsDir, routePrefix, label, ...(sidebar ? { sidebarPath: sidebar } : {}) })\n }\n for (const version of versions) add(`versioned_docs/${version}`, version.slice('version-'.length), `Version ${version.slice('version-'.length)}`, sidebarPath(version))\n for (const locale of directoryNames('i18n').filter((name) => /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8})*$/.test(name))) {\n const localizedRoot = `i18n/${locale}/docusaurus-plugin-content-docs`\n const current = resolveWithin(projectRoot, `${localizedRoot}/current`)\n if (existsSync(current) && lstatSync(current).isDirectory()) add(`${localizedRoot}/current`, locale, `${locale} Documentation`)\n // A translation can exist for a version no longer present in the default\n // language's versioned_docs tree; discover its files independently.\n const localizedVersions = directoryNames(localizedRoot)\n .filter((name) => /^version-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))\n for (const version of localizedVersions) {\n const path = resolveWithin(projectRoot, `${localizedRoot}/${version}`)\n if (existsSync(path) && lstatSync(path).isDirectory()) add(`${localizedRoot}/${version}`, `${locale}/${version.slice('version-'.length)}`, `${locale} Version ${version.slice('version-'.length)}`)\n }\n }\n // Each recursive import has its own 5,000-file scan cap. Bound the number\n // of roots too, so a hostile checkout cannot multiply work indefinitely.\n if (archives.length > 48) warnings.push({ code: 'limit-reached', message: `Only the first 48 Docusaurus archived or localized docs roots were imported (${archives.length} found).` })\n return archives.slice(0, 48)\n}\n\nfunction additionalDocusaurusPluginRoots(\n repositoryDir: string,\n projectRoot: string,\n warnings: Array<MigrationWarning>,\n): Array<DocusaurusPluginRoot> {\n const source = readDocusaurusConfigSource(projectRoot)\n const plugins: Array<DocusaurusPluginRoot> = []\n // Docusaurus resolves the bare shorthand ('content-docs') to the same\n // official plugin as the full package name, so both forms are matched.\n const matcher = /['\"](?:@docusaurus\\/plugin-)?content-docs['\"][\\s\\S]{0,3000}?\\bpath\\s*:\\s*(['\"])([^'\"]+)\\1[\\s\\S]{0,1000}?\\brouteBasePath\\s*:\\s*(['\"])([^'\"]+)\\3/g\n for (const match of source.matchAll(matcher)) {\n const localPath = trimTrailingSlashes(match[2].replace(/^\\.\\//, ''))\n const routePrefix = trimEdgeSlashes(match[4])\n if (!localPath || !routePrefix) continue\n // Docusaurus resolves a content-docs instance's `path` relative to the\n // site directory (where `docusaurus.config` lives, `projectRoot` here).\n // Some monorepo sites build by copying that project root's contents up\n // into the repository root before running the generator (Playwright's\n // own `cp -r nodejs/* .` step is a real example — see the identical\n // fallback in components.ts's `resolveDependency`), so a `path` that\n // isn't found under `projectRoot` is retried directly under\n // `repositoryDir`, still confined to the repository.\n let docsDir: string | undefined\n for (const base of [projectRoot, repositoryDir]) {\n let absolute: string\n try {\n absolute = resolveWithin(base, localPath)\n } catch {\n continue\n }\n if (existsSync(absolute) && lstatSync(absolute).isDirectory()) {\n docsDir = relative(repositoryDir, absolute).replace(/\\\\/g, '/')\n break\n }\n }\n if (docsDir) {\n plugins.push({ docsDir, routePrefix })\n } else {\n warnings.push({\n code: 'unsupported-config',\n message: `The \"${routePrefix}\" docs plugin instance's path (${JSON.stringify(match[2])}) could not be found in the repository and was skipped.`,\n })\n }\n }\n return plugins\n}\n\n/** Parse and validate a public GitHub repository URL. */\nexport function parseGitHubRepositoryUrl(rawUrl: string): GitHubRepositorySource {\n let url: URL\n try {\n url = new URL(rawUrl)\n } catch {\n throw new Error(`Invalid GitHub URL: ${rawUrl}`)\n }\n if (url.protocol !== 'https:' || url.hostname.toLowerCase() !== 'github.com') {\n throw new Error('Repository migrations require an https://github.com URL.')\n }\n if (url.username || url.password || url.port) {\n throw new Error('GitHub repository URLs cannot include credentials or custom ports.')\n }\n const segments = url.pathname.split('/').filter(Boolean).map(decodeURIComponent)\n const [owner, rawRepo] = segments\n const repo = rawRepo?.replace(/\\.git$/i, '')\n const safeName = /^[A-Za-z0-9_.-]+$/\n if (!owner || !repo || !safeName.test(owner) || !safeName.test(repo)) {\n throw new Error('GitHub URL must include a valid owner and repository name.')\n }\n let branch = 'HEAD'\n let docsDir = ''\n if (segments[2] === 'tree' && segments[3]) {\n branch = segments[3]\n docsDir = segments.slice(4).join('/')\n }\n return {\n owner,\n repo,\n branch,\n docsDir,\n cloneUrl: `https://github.com/${owner}/${repo}.git`,\n }\n}\n\nconst CLONE_RETRY_ATTEMPTS = 3\nconst CLONE_RETRY_DELAY_MS = 1_000\nconst DEFAULT_CLONE_TIMEOUT_MS = 10 * 60_000\n\n/** Transient network-class git failures a retry can plausibly recover from. Also covers this module's own timeout error below. */\nconst RETRYABLE_CLONE_ERROR = /RPC failed|Recv failure|early EOF|curl \\d+|Could not resolve host|Connection (?:reset|refused|timed out)|The remote end hung up|SSL[_ ]?(?:read|connect|write) error|timed out|network is unreachable/i\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => { setTimeout(resolve, ms) })\n}\n\n/** How long a single git subprocess may run before it's killed and treated as a (retryable) timeout. Configurable since a very large repository on a slow link may need longer than the generous 10-minute default. */\nfunction gitProcessTimeoutMs(): number {\n const raw = process.env.THALLY_MIGRATE_CLONE_TIMEOUT_MS\n const parsed = raw ? Number(raw) : NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CLONE_TIMEOUT_MS\n}\n\n/**\n * Run one git subprocess without a shell, with an overall timeout (a\n * stalled clone/fetch otherwise hangs forever — there is no `timeout`\n * binary to rely on) and per-process env overrides (never touching global\n * git/npm config, per this package's own rule).\n */\nfunction runGit(args: Array<string>, options: { cwd?: string; env?: Record<string, string>; label: string }): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = spawn('git', args, {\n stdio: ['ignore', 'ignore', 'pipe'],\n ...(options.cwd ? { cwd: options.cwd } : {}),\n env: { ...process.env, ...options.env },\n })\n let stderr = ''\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n child.kill('SIGKILL')\n }, gitProcessTimeoutMs())\n child.stderr.setEncoding('utf8')\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 16_000) stderr += chunk\n })\n child.on('error', (error) => {\n clearTimeout(timer)\n reject(error)\n })\n child.on('close', (code) => {\n clearTimeout(timer)\n if (code === 0) resolve()\n else if (timedOut) reject(new Error(`${options.label} timed out after ${gitProcessTimeoutMs()}ms and was killed.`))\n else reject(new Error(`${options.label}: ${stderr.trim() || `git exited ${code}`}`))\n })\n })\n}\n\n/**\n * Neutralize the `filter.lfs.*` smudge/clean/process filter driver for one\n * git process only — never the user's global git config — so a repository\n * tracked with Git LFS still clones when the host has no `git-lfs` binary.\n * `GIT_LFS_SKIP_SMUDGE=1` alone isn't enough: if this host ever had\n * `git lfs install` run and then had the `git-lfs` binary removed (as here),\n * `filter.lfs.smudge`/`.process` are still registered in the *global* git\n * config pointing at a command that no longer exists, and\n * `GIT_LFS_SKIP_SMUDGE` is only ever read by that (missing) binary — git\n * itself still fails outright trying to invoke it. `GIT_CONFIG_COUNT`/\n * `GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n` env pairs are the one config\n * source with higher precedence than the user's global config, so they can\n * override it per-process: `smudge`/`clean` become `cat` (pass the LFS\n * pointer text straight through — real content was never fetched anyway)\n * and `process` is cleared so git falls back to them; `filter.lfs.required\n * = false` keeps a filter hiccup on one path (an oversized fixture, say)\n * from failing the whole checkout. The result is the repository's own\n * files, with an LFS-tracked asset left as its pointer text — the\n * asset-copying step below warns when a copied file turns out to be one.\n */\nconst LFS_FILTER_OVERRIDE_ENV: Record<string, string> = {\n GIT_CONFIG_COUNT: '4',\n GIT_CONFIG_KEY_0: 'filter.lfs.smudge',\n GIT_CONFIG_VALUE_0: 'cat',\n GIT_CONFIG_KEY_1: 'filter.lfs.clean',\n GIT_CONFIG_VALUE_1: 'cat',\n GIT_CONFIG_KEY_2: 'filter.lfs.process',\n GIT_CONFIG_VALUE_2: '',\n GIT_CONFIG_KEY_3: 'filter.lfs.required',\n GIT_CONFIG_VALUE_3: 'false',\n}\n\nfunction cloneOnce(source: GitHubRepositorySource, targetDir: string): Promise<void> {\n // Submodules are deliberately not recursed here: `--recurse-submodules`\n // fails the *entire* clone if any one submodule can't be fetched (a\n // private or since-deleted submodule shouldn't take the whole migration\n // down). `initSubmodules`, run after a successful plain clone, is the\n // equivalent of `--recurse-submodules --shallow-submodules` (`--depth 1`\n // per submodule) but fault-tolerant per submodule.\n const args = ['clone', '--depth', '1', '--single-branch']\n if (source.branch !== 'HEAD') args.push('--branch', source.branch)\n args.push('--', source.cloneUrl, targetDir)\n return runGit(args, {\n label: `Failed to clone ${source.owner}/${source.repo}`,\n env: LFS_FILTER_OVERRIDE_ENV,\n })\n}\n\n/** Every submodule path declared in a cloned repository's `.gitmodules`, in file order. */\nexport function gitmodulePaths(targetDir: string): Array<string> {\n const gitmodulesPath = resolvePath(targetDir, '.gitmodules')\n if (!existsSync(gitmodulesPath) || !lstatSync(gitmodulesPath).isFile()) return []\n let content: string\n try {\n content = readFileSync(gitmodulesPath, 'utf8')\n } catch {\n return []\n }\n return [...content.matchAll(/^\\s*path\\s*=\\s*(.+?)\\s*$/gm)].map((match) => match[1]).filter(Boolean)\n}\n\n/**\n * Every submodule `url` in a cloned repository's `.gitmodules`, in the same\n * file order as `gitmodulePaths` (each `[submodule \"...\"]` block declares\n * `path` and `url` once, so index `i` here corresponds to index `i` there).\n */\nfunction gitmoduleUrls(targetDir: string): Array<string> {\n const gitmodulesPath = resolvePath(targetDir, '.gitmodules')\n if (!existsSync(gitmodulesPath) || !lstatSync(gitmodulesPath).isFile()) return []\n let content: string\n try {\n content = readFileSync(gitmodulesPath, 'utf8')\n } catch {\n return []\n }\n return [...content.matchAll(/^\\s*url\\s*=\\s*(.+?)\\s*$/gm)].map((match) => match[1]).filter(Boolean)\n}\n\n/**\n * `--recurse-submodules` on the main clone (above) fails the *entire* clone\n * if any one submodule can't be fetched, which is worse than not having\n * that submodule's content at all. So the main clone omits it and this\n * best-effort pass follows, per submodule path, so one broken/private\n * submodule doesn't take down the whole migration — it's just missing,\n * and named in a warning instead of silently absent.\n */\nasync function initSubmodules(targetDir: string, warnings: Array<MigrationWarning>): Promise<void> {\n const paths = gitmodulePaths(targetDir)\n if (paths.length === 0) return\n const urls = gitmoduleUrls(targetDir)\n const failed: Array<string> = []\n for (const [index, path] of paths.entries()) {\n // A path or url beginning with `-` would be read as a git option\n // rather than a pathspec/URL once it reaches argv (even after `--`,\n // git's own pathspec parser treats a leading `-` as a flag), and\n // `.gitmodules` is attacker-controlled content from the cloned repo.\n if (path.startsWith('-') || (urls[index]?.startsWith('-') ?? false)) {\n failed.push(path)\n continue\n }\n try {\n await runGit([\n '-c', 'protocol.file.allow=never',\n '-c', 'protocol.ext.allow=never',\n 'submodule', 'update', '--init', '--depth', '1', '--', path,\n ], {\n cwd: targetDir,\n env: LFS_FILTER_OVERRIDE_ENV,\n label: `Failed to initialize submodule ${path}`,\n })\n } catch {\n failed.push(path)\n }\n }\n if (failed.length > 0) {\n warnings.push({\n code: 'fetch-failed',\n message: `${failed.length} git submodule${failed.length === 1 ? '' : 's'} could not be fetched and ${failed.length === 1 ? 'is' : 'are'} missing from the migrated content: ${failed.join(', ')}.`,\n })\n }\n}\n\n/**\n * Clone a repository without a shell; callers own and remove `targetDir`. A\n * large repository on a flaky connection can drop mid-clone (`RPC failed`,\n * `Recv failure`, a `curl 56`, …) — retry a network-class failure a couple\n * of times with backoff instead of surfacing a hard failure on the first\n * blip. A partial checkout from the failed attempt is removed first, or\n * `git clone` refuses to reuse the (now non-empty) target directory. A\n * stalled clone/submodule-init is killed by `runGit`'s own timeout, which\n * surfaces as a retryable error. `warnings`, if given, collects a\n * submodule-fetch-failure warning (this function otherwise returns exactly\n * as before, so existing callers are unaffected).\n */\nexport async function cloneGitHubRepository(\n source: GitHubRepositorySource,\n targetDir: string,\n warnings?: Array<MigrationWarning>,\n): Promise<void> {\n for (let attempt = 1; attempt <= CLONE_RETRY_ATTEMPTS; attempt++) {\n try {\n await cloneOnce(source, targetDir)\n await initSubmodules(targetDir, warnings ?? [])\n return\n } catch (error) {\n const retryable = error instanceof Error && RETRYABLE_CLONE_ERROR.test(error.message)\n if (!retryable || attempt === CLONE_RETRY_ATTEMPTS) throw error\n rmSync(targetDir, { recursive: true, force: true })\n await delay(CLONE_RETRY_DELAY_MS * attempt)\n }\n }\n}\n\n/** Detect a supported repository docs platform from unambiguous config files. */\nexport function detectRepositoryPlatform(repositoryDir: string, docsDir?: string): MigrationPlatform {\n if (findMintlifyProjectRoot(repositoryDir, docsDir)) return 'mintlify'\n if (findFernProjectRoot(repositoryDir, docsDir)) return 'fern'\n const selectedRoot = docsDir === undefined ? repositoryDir : resolveWithin(repositoryDir, docsDir || '.')\n const docsJson = resolveWithin(selectedRoot, 'docs.json')\n if (existsSync(docsJson)) {\n try {\n const config = JSON.parse(readFileSync(docsJson, 'utf8')) as Record<string, unknown>\n if (Array.isArray(config.tabs)) return 'thally'\n } catch {\n // A malformed source config is reported later; platform detection falls through.\n }\n }\n if (['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'docusaurus'\n if (findDocusaurusProjectRoot(repositoryDir)) return 'docusaurus'\n if (existsSync(resolveWithin(repositoryDir, 'SUMMARY.md'))) return 'gitbook'\n if (existsSync(resolveWithin(repositoryDir, '.vitepress'))) return 'vitepress'\n if (['astro.config.mjs', 'astro.config.ts']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'starlight'\n if (['pages/_meta.json', '_meta.json']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'nextra'\n return 'unknown'\n}\n\nfunction containsMarkdown(directory: string, depth = 0): boolean {\n if (depth > 4) return false\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (isIgnoredDirectory(entry.name) || entry.isSymbolicLink()) continue\n const path = resolveWithin(directory, entry.name)\n if (entry.isFile() && ['.md', '.mdx'].includes(extname(entry.name).toLowerCase())) return true\n if (entry.isDirectory() && containsMarkdown(path, depth + 1)) return true\n }\n return false\n}\n\n/** Pick the first conventional content root containing Markdown. */\nexport function detectRepositoryDocsDir(repositoryDir: string): string {\n for (const candidate of ['docs', 'documentation', 'content', 'pages', 'src/content', 'src/pages', 'guide', 'guides', '']) {\n const path = resolveWithin(repositoryDir, candidate)\n if (existsSync(path) && lstatSync(path).isDirectory() && containsMarkdown(path)) return candidate\n }\n return ''\n}\n\ninterface ScannedFile {\n absolutePath: string\n relativePath: string\n}\n\n/**\n * Scan `root` for its files, following a symbolic link only when its\n * resolved real path stays inside `confinementRoot` (default `root`) — this\n * is how a submodule mounted as a symlink (Oasis's `docs/core ->\n * ../external/oasis-core/docs`, `docs/adrs -> ../external/adrs`) actually\n * gets its content walked, since a plain `git clone` (even with submodules\n * initialized) leaves those as real symlinks on disk that a naive walk\n * would otherwise always skip. `confinementRoot` is normally the whole\n * repository checkout, not just the docs root, because a submodule commonly\n * links out to a sibling directory outside it. `visitedRealPaths` guards\n * against a cycle (a symlink pointing at an ancestor, or two symlinks\n * pointing at each other).\n */\n/**\n * A generous ceiling on how many *directory entries* `scanFiles` will walk\n * when a `rank` function is supplied (see below) — far above\n * `MAX_SOURCE_FILES` so a repository the size of crewAI's (~28k files) is\n * walked in full, but still bounded so a pathologically huge tree can't\n * make discovery itself slow. Walking is cheap (no file content is read\n * here); only the final `MAX_SOURCE_FILES` selection is expensive to get\n * wrong.\n */\nconst MAX_RANKED_WALK_FILES = MAX_SOURCE_FILES * 20\n\n/**\n * Scan `root` for its files. When `rank` is given, the walk isn't cut off at\n * `MAX_SOURCE_FILES` — it continues (bounded by `MAX_RANKED_WALK_FILES`) so\n * every file's priority can be considered before any are dropped; the\n * caller is responsible for sorting by `rank` and trimming to\n * `MAX_SOURCE_FILES` afterward (see `selectFilesWithinBudget`). Without\n * `rank`, the walk stops as soon as `MAX_SOURCE_FILES` files are found, same\n * as before.\n */\nfunction scanFiles(root: string, confinementRoot: string = root, warnings?: Array<MigrationWarning>, rank?: (relativePath: string) => number): Array<ScannedFile> {\n const files: Array<ScannedFile> = []\n const walkCap = rank ? MAX_RANKED_WALK_FILES : MAX_SOURCE_FILES\n let confinementReal: string\n try {\n confinementReal = realpathSync(confinementRoot)\n } catch {\n confinementReal = confinementRoot\n }\n // Tracks every directory's real path, symlinked or not: a symlink into an\n // ancestor (or two symlinks pointing at each other) must not recurse\n // forever, and this also cheaply dedupes reaching the same real directory\n // through two different symlinks.\n const visitedRealPaths = new Set<string>()\n // `directory` is the real, physical path a symlink was already resolved\n // to (used for readdirSync/realpathSync); `logicalDirectory` is the path\n // as seen through the symlink from `root` (used only for `relativePath`,\n // so a page inside a symlinked submodule gets a sensible id like\n // `core/overview` instead of a `../../..`-laden physical path).\n function visit(directory: string, logicalDirectory: string = directory): void {\n if (files.length >= walkCap) return\n let directoryReal: string\n try {\n directoryReal = realpathSync(directory)\n } catch {\n return\n }\n if (visitedRealPaths.has(directoryReal)) return\n visitedRealPaths.add(directoryReal)\n let entries: Array<Dirent>\n try {\n entries = readdirSync(directory, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (files.length >= walkCap) return\n if (isIgnoredContentDirectory(entry.name)) {\n // Still skipped (`.git`, `node_modules`, ...) — but never silently:\n // warn if it turns out to hold real pages, since that's exactly the\n // shape of bug this content root is supposed to be free of.\n if (warnings && entry.isDirectory() && !entry.isSymbolicLink()\n && containsMarkdown(resolveWithin(directory, entry.name))) {\n warnings.push({\n code: 'unsupported-config',\n message: `The \"${entry.name}\" directory was skipped during migration but contains Markdown/MDX files; if any are real pages, move them out or pass --docs-dir to include them.`,\n source: relative(root, resolveWithin(directory, entry.name)).replace(/\\\\/g, '/'),\n })\n }\n continue\n }\n const path = resolveWithin(directory, entry.name)\n const logicalPath = resolveWithin(logicalDirectory, entry.name)\n if (entry.isSymbolicLink()) {\n let real: string\n try {\n real = realpathSync(path)\n } catch {\n continue // A broken symlink (e.g. an uninitialized submodule) has nothing to walk.\n }\n const withinConfinement = real === confinementReal || real.startsWith(`${confinementReal}${sep}`)\n if (!withinConfinement) continue\n let target: ReturnType<typeof statSync>\n try {\n target = statSync(real)\n } catch {\n continue\n }\n if (target.isDirectory()) visit(real, logicalPath)\n else if (target.isFile()) files.push({ absolutePath: real, relativePath: relative(root, logicalPath).replace(/\\\\/g, '/') })\n continue\n }\n if (entry.isDirectory()) visit(path, logicalPath)\n else if (entry.isFile()) files.push({ absolutePath: path, relativePath: relative(root, logicalPath).replace(/\\\\/g, '/') })\n }\n }\n visit(root)\n if (rank && files.length >= walkCap) {\n warnings?.push({\n code: 'limit-reached',\n message: `Stopped scanning after ${walkCap} files, so the rest of the repository was not looked at. Run the migration on a smaller part of the repository with --docs-dir.`,\n })\n }\n return files\n}\n\n/**\n * Applies the `MAX_SOURCE_FILES` budget to one homogeneous group (either\n * documentation pages or assets — see `selectFilesWithinBudget`), keeping\n * the highest-priority files and emitting one warning naming how many were\n * dropped and — for Mintlify — which versions they belonged to.\n */\nfunction selectGroupWithinBudget(\n scanned: Array<ScannedFile>,\n rank: (relativePath: string) => number,\n warnings: Array<MigrationWarning> | undefined,\n allVersionPrefixes: ReadonlySet<string>,\n label: 'file' | 'asset',\n): Array<ScannedFile> {\n if (scanned.length <= MAX_SOURCE_FILES) return scanned\n // Ties (unreferenced files sharing a ceiling) break by path, not by\n // directory-listing order, so the same repository always keeps the same files.\n const ranked = scanned\n .map((file) => ({ file, priority: rank(file.relativePath) }))\n .sort((left, right) => left.priority - right.priority\n || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0))\n const dropped = ranked.slice(MAX_SOURCE_FILES).map(({ file }) => file)\n if (warnings) {\n const droppedPages = label === 'file' ? dropped.filter((file) => isDocumentationExtension(file.relativePath)) : dropped\n const noun = label === 'file' ? 'page' : 'image or media file'\n const droppedVersions = new Set<string>()\n for (const file of dropped) {\n const firstSegment = file.relativePath.split('/', 1)[0]\n if (allVersionPrefixes.has(firstSegment)) droppedVersions.add(firstSegment)\n }\n const examples = droppedPages.slice(0, 3).map((file) => file.relativePath)\n const rest = droppedPages.length - examples.length\n warnings.push({\n code: 'limit-reached',\n message: `This repository has more than ${MAX_SOURCE_FILES} ${label === 'file' ? 'files' : 'assets'}, so only the first ${MAX_SOURCE_FILES} (in navigation order, default version first) were migrated. `\n + `${droppedPages.length} ${noun}(s) were left out`\n + (examples.length > 0 ? `: ${examples.join(', ')}${rest > 0 ? `, and ${rest} more` : ''}` : '')\n + (droppedVersions.size > 0 ? ` (versions: ${[...droppedVersions].slice(0, 5).join(', ')}${droppedVersions.size > 5 ? `, and ${droppedVersions.size - 5} more` : ''})` : '')\n + (label === 'file'\n ? '. To include them, run the migration on a smaller part of the repository with --docs-dir.'\n : '. Copy them into public/ manually if your pages use them.'),\n })\n }\n return ranked.slice(0, MAX_SOURCE_FILES).map(({ file }) => file)\n}\n\n/**\n * When a `scanFiles` walk (run with a `rank` function) found more than\n * `MAX_SOURCE_FILES` files, keep the highest-priority files and drop the\n * rest. `rank` comes from `referenceOrder` (navigation traversal order:\n * default version before non-default, newest non-default before older, per\n * `projectMintlifyNavigation`'s version sort), so referenced pages always\n * win over unreferenced ones, and within referenced pages the default\n * version's own pages always win over other versions'.\n *\n * Assets get their own `MAX_SOURCE_FILES` budget, separate from pages: a\n * repository with more than `MAX_SOURCE_FILES` navigation-referenced pages\n * (e.g. crewAI's ~40 Mintlify versions) would otherwise fill the entire\n * shared budget with pages before a single image is ever considered,\n * since `rank` only orders *pages* (assets always sort last, at\n * `Number.MAX_SAFE_INTEGER` — see `discoveryRank` in `migrateRepository`)\n * — starving every asset even though the asset budget\n * (`MAX_ASSET_BYTES`/`MAX_TOTAL_ASSET_BYTES`) was never reached.\n */\nfunction selectFilesWithinBudget(\n scanned: Array<ScannedFile>,\n rank: (relativePath: string) => number,\n warnings: Array<MigrationWarning> | undefined,\n allVersionPrefixes: ReadonlySet<string>,\n): Array<ScannedFile> {\n const isAsset = (file: ScannedFile): boolean => ASSET_EXTENSIONS.has(extname(file.relativePath).toLowerCase())\n const assetFiles = scanned.filter(isAsset)\n const otherFiles = scanned.filter((file) => !isAsset(file))\n return [\n ...selectGroupWithinBudget(otherFiles, rank, warnings, allVersionPrefixes, 'file'),\n ...selectGroupWithinBudget(assetFiles, rank, warnings, allVersionPrefixes, 'asset'),\n ]\n}\n\n/**\n * Mintlify excludes paths from the docs site with a gitignore-style\n * `.mintignore` at the project root (see Mintlify's docs). Honoring it keeps\n * internal tooling directories like `agent-context/` out of the migration\n * even though they aren't dotfile directories.\n */\nfunction readMintignoreMatcher(mintlifyRoot: string): IgnoreMatcher | null {\n const path = resolveWithin(mintlifyRoot, MINTIGNORE_FILENAME)\n if (!existsSync(path) || !lstatSync(path).isFile()) return null\n return createIgnoreMatcher().add(readFileSync(path, 'utf8'))\n}\n\n/**\n * Compile-check a page body with the same MDX compiler the scaffold's\n * runtime build uses (`@mdx-js/mdx`). A single malformed page must never\n * abort `scripts/build-runtime-sources.mts` for the whole project, so\n * migration excludes it up front instead and reports why.\n */\nfunction invalidMdxReason(body: string): string | null {\n try {\n compileSync(body, { outputFormat: 'program' })\n return null\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i\n\n/** Extract Mintlify's `colors.{primary,light,dark}` theme hexes, if valid. */\nfunction mintlifyThemeColors(value: unknown): { primary?: string; light?: string; dark?: string } | undefined {\n if (!value || typeof value !== 'object') return undefined\n const source = value as Record<string, unknown>\n const colors: { primary?: string; light?: string; dark?: string } = {}\n for (const key of ['primary', 'light', 'dark'] as const) {\n if (typeof source[key] === 'string' && HEX_COLOR.test(source[key])) colors[key] = source[key]\n }\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\n/**\n * Extract Fern's `colors.accent-primary` (a hex string, or `{light, dark}`),\n * if valid. Fern's `light`/`dark` are normal (each names the mode it\n * paints), unlike Mintlify's inverted schema that `site.colors` otherwise\n * follows, so they're swapped onto Mintlify's `{light, dark}` keys here to\n * give downstream consumers (`updateSiteConfig`) one consistent contract.\n */\nfunction fernThemeColors(value: unknown): { primary?: string; light?: string; dark?: string } | undefined {\n if (!value || typeof value !== 'object') return undefined\n const accent = (value as Record<string, unknown>)['accent-primary']\n if (typeof accent === 'string') return HEX_COLOR.test(accent) ? { primary: accent } : undefined\n if (!accent || typeof accent !== 'object') return undefined\n const source = accent as Record<string, unknown>\n const lightMode = typeof source.light === 'string' && HEX_COLOR.test(source.light) ? source.light : undefined\n const darkMode = typeof source.dark === 'string' && HEX_COLOR.test(source.dark) ? source.dark : undefined\n const colors: { light?: string; dark?: string } = {}\n if (darkMode) colors.light = darkMode\n if (lightMode) colors.dark = lightMode\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\nfunction normalizedReferenceKey(value: string): string {\n return value.split(/[?#]/, 1)[0]\n .replace(/^\\/+/, '')\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:mdx?|rst|txt)$/i, '')\n .replace(/\\/(?:index|readme)$/i, '')\n .replace(/^(?:index|readme)$/i, '') || 'introduction'\n}\n\nfunction exactReferenceKey(value: string): string {\n return value.split(/[?#]/, 1)[0]\n .replace(/^\\/+/, '')\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:mdx?|rst|txt)$/i, '')\n}\n\nfunction findOpenApi(files: Array<ScannedFile>): ScannedFile | null {\n return files.find((file) => OPENAPI_FILENAMES.has(basename(file.relativePath).toLowerCase())\n && classifyApiSpec(file.absolutePath) === 'openapi') ?? null\n}\n\n/** A familiar filename is insufficient: Fern repositories also keep AsyncAPI there. */\nfunction classifyApiSpec(path: string): 'openapi' | 'asyncapi' | 'unknown' {\n const buffer = Buffer.alloc(64_000)\n let bytesRead = 0\n try {\n const descriptor = openSync(path, 'r')\n try {\n bytesRead = readSync(descriptor, buffer, 0, buffer.length, 0)\n } finally {\n closeSync(descriptor)\n }\n } catch {\n return 'unknown'\n }\n const text = buffer.toString('utf8', 0, bytesRead)\n const topLevel = text.match(/^(?:openapi|swagger|asyncapi)\\s*:/m)?.[0]\n ?? text.match(/^\\s*\\{\\s*\"(?:openapi|swagger|asyncapi)\"\\s*:/m)?.[0]\n if (!topLevel) return 'unknown'\n return /asyncapi/i.test(topLevel) ? 'asyncapi' : 'openapi'\n}\n\n/** An OpenAPI/AsyncAPI spec resolved and ready to copy into `public/`, optionally bound to one tab. */\ninterface ResolvedApiSpec {\n filename: string\n content: Buffer\n tabLabel?: string\n /** Repository-relative path the spec was read from, used only to disambiguate a basename collision across tabs. */\n sourcePath: string\n /** Mintlify's object-form `{ source, directory }` scoping directory, if any — the prefix its auto-generated operation pages live under. */\n directory?: string\n}\n\nfunction mintlifyTopLevelApiReferences(config: Record<string, unknown> | null): Array<MintlifyApiSpecReference> {\n const api = config?.api && typeof config.api === 'object' && !Array.isArray(config.api)\n ? config.api as Record<string, unknown>\n : null\n if (!api) return []\n const references: Array<MintlifyApiSpecReference> = []\n for (const kind of ['openapi', 'asyncapi'] as const) {\n const value = api[kind]\n const values = typeof value === 'string'\n ? [value]\n : Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n for (const entry of values) references.push({ value: entry, kind })\n }\n return references\n}\n\n/**\n * Resolve every OpenAPI/AsyncAPI reference in a Mintlify config — the\n * top-level `api.openapi`/`api.asyncapi` plus every per-tab/group/anchor\n * `openapi`/`asyncapi` field in `navigation` — into copyable spec bytes\n * bound to the tab that referenced them. AsyncAPI has no Thally renderer,\n * so it only ever produces a warning naming the spec. A remote `https://`\n * reference is skipped with an actionable warning until the downloader can\n * validate the connected address on every request, including redirects.\n * Missing local files also produce warnings rather than disappearing.\n */\nfunction resolveMintlifyApiSpecs(\n mintlifyConfig: Record<string, unknown> | null,\n files: Array<ScannedFile>,\n warnings: Array<MigrationWarning>,\n remoteSpecs: Array<{ url: string; tabLabel?: string }>,\n): Array<ResolvedApiSpec> {\n if (!mintlifyConfig) return []\n const references = [\n ...mintlifyTopLevelApiReferences(mintlifyConfig),\n ...mintlifyNavigationApiReferences(mintlifyConfig),\n ]\n const seen = new Set<string>()\n const specs: Array<ResolvedApiSpec> = []\n for (const reference of references) {\n const dedupeKey = `${reference.kind}:${reference.value}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n const tabSuffix = reference.tabLabel ? ` (tab \"${reference.tabLabel}\")` : ''\n if (reference.kind === 'asyncapi') {\n warnings.push({\n code: 'unsupported-config',\n message: `AsyncAPI is not supported by Thally's API reference; the spec \"${reference.value}\"${tabSuffix} was not migrated.`,\n })\n continue\n }\n if (/^https:\\/\\//i.test(reference.value)) {\n remoteSpecs.push({ url: reference.value, ...(reference.tabLabel ? { tabLabel: reference.tabLabel } : {}) })\n warnings.push({\n code: 'unsupported-config',\n message: `The remote OpenAPI spec \"${reference.value}\"${tabSuffix} requires a network download before this import is complete.`,\n source: reference.value,\n })\n continue\n }\n if (/^http:\\/\\//i.test(reference.value)) {\n warnings.push({ code: 'unsupported-config', message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} uses insecure HTTP and was not imported.`, source: reference.value })\n continue\n }\n const key = reference.value.split(/[?#]/, 1)[0].replace(/^\\/+/, '').replace(/\\\\/g, '/')\n const match = files.find((file) => file.relativePath === key)\n if (!match) {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} could not be found in the repository and was not migrated.`,\n })\n continue\n }\n if (reference.directory) {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} was limited to pages under \"${reference.directory}\" in the source, but Thally's API reference always covers a whole tab, so it was migrated as the tab's full API reference. Update any links to \"${reference.directory}/...\" pages manually.`,\n })\n }\n specs.push({\n filename: basename(match.relativePath),\n content: readFileSync(match.absolutePath),\n tabLabel: reference.tabLabel,\n sourcePath: match.relativePath,\n directory: reference.directory,\n })\n }\n // Two specs bound to *different* tabs can share a basename (e.g.\n // \"qstash/openapi.yaml\" and \"workflow/openapi.yaml\" both resolve to\n // \"openapi.yaml\") — without disambiguation the second spec's asset\n // write collides with the first's, silently discarding its content\n // even though both tabs believe they have a working spec bound. Specs\n // that land on the *same* tab are left alone: only one of them ever\n // gets bound (see injectOpenApiSpecs's \"already has an OpenAPI spec\"\n // warning), so renaming there would produce an asset nothing points to.\n const filenameOwners = new Map<string, string>()\n for (const spec of specs) {\n const groupKey = spec.tabLabel ?? '\\0default'\n const owner = filenameOwners.get(spec.filename)\n if (owner !== undefined && owner !== groupKey) {\n let disambiguated = spec.sourcePath.replace(/\\//g, '-')\n while (filenameOwners.has(disambiguated) && filenameOwners.get(disambiguated) !== groupKey) {\n disambiguated = `${groupKey.replace(/\\W+/g, '-')}-${disambiguated}`\n }\n spec.filename = disambiguated\n }\n filenameOwners.set(spec.filename, groupKey)\n }\n return specs\n}\n\nconst OPENAPI_HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']\n\n/** NestJS's conventional CRUD controller method names, mapped to the REST-conventional slug Fern renders them under (confirmed against a live site). */\nconst FERN_CRUD_METHOD_NAMES: Record<string, string> = {\n findall: 'list',\n findone: 'get',\n remove: 'delete',\n}\n\n/** Kebab-case a label the way Mintlify slugs its auto-generated OpenAPI operation pages (tag folder, operation leaf). */\nfunction mintlifyOperationSlugSegment(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')\n}\n\n/**\n * Thally's own API operation route segment: path segments (braces stripped)\n * plus the HTTP method — never the summary. Mirrors `buildSlugSegments` in\n * src/lib/openapi/normalize.ts; duplicated rather than imported because\n * packages/migrate cannot depend on the Next.js app. Ceiling: webhook\n * operations (`x-webhooks`) aren't covered — normalize.ts prefixes those\n * with \"webhooks\", update this alongside it if that ever matters here.\n */\nexport function thallyOperationSlugSegments(path: string, method: string): Array<string> {\n const cleaned = path\n .split('/')\n .filter(Boolean)\n .map((segment) => segment.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9-]/g, '-').replace(/-+/g, '-').toLowerCase())\n if (!cleaned.length) cleaned.push('root')\n cleaned.push(method.toLowerCase())\n return cleaned\n}\n\n/** Mirrors `slugifyId` in src/data/docs.ts, which turns a tab label into its API spec id. */\nfunction slugifyApiSpecId(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9/]+/g, '-').replace(/(^-|-$)+/g, '').replace(/\\//g, '-') || value.toLowerCase()\n}\n\ninterface OpenApiOperationForLinking {\n method: string\n path: string\n tag?: string\n summary?: string\n operationId?: string\n}\n\n/** Read just enough of an OpenAPI document to match Mintlify's auto-generated operation pages. Malformed input yields no operations rather than throwing. */\nfunction parseOpenApiOperationsForLinking(content: Buffer): Array<OpenApiOperationForLinking> {\n let document: unknown\n try {\n document = parseYaml(content.toString('utf8'))\n } catch {\n return []\n }\n const paths = document && typeof document === 'object' ? (document as Record<string, unknown>).paths : null\n if (!paths || typeof paths !== 'object') return []\n const operations: Array<OpenApiOperationForLinking> = []\n for (const [path, pathItem] of Object.entries(paths as Record<string, unknown>)) {\n if (!pathItem || typeof pathItem !== 'object') continue\n for (const method of OPENAPI_HTTP_METHODS) {\n const operation = (pathItem as Record<string, unknown>)[method]\n if (!operation || typeof operation !== 'object') continue\n const op = operation as Record<string, unknown>\n const tags = Array.isArray(op.tags) ? op.tags.filter((tag): tag is string => typeof tag === 'string') : []\n operations.push({\n method,\n path,\n tag: tags[0],\n summary: typeof op.summary === 'string' ? op.summary : undefined,\n operationId: typeof op.operationId === 'string' ? op.operationId : undefined,\n })\n }\n }\n return operations\n}\n\n/**\n * Map Mintlify's auto-generated operation page path (e.g.\n * \"qstash/api-reference/messages/publish-a-message\", from the `directory`\n * an object-form `openapi: { source, directory }` reference scoped its\n * pages under) to Thally's actual operation route\n * (`/api/<specId>/<method+path slug>`), so in-content links to those\n * Mintlify-only pages can be rewritten instead of staying broken.\n *\n * `specId` mirrors buildApiReferenceConfig in src/config/api-reference.ts:\n * the first non-hidden tab with a bound spec is `'default'`, every other\n * one is keyed by its own tab id. Ceiling: matches by tag + (summary,\n * operationId, or \"method path\"), the same fields Mintlify's generator\n * itself falls back through — an operation whose tag Mintlify computed\n * differently still won't resolve, and stays a broken link as before.\n */\n/** A spec bound to a tab, plus the source-platform's own route prefix its auto-generated operation pages live under (Mintlify's `directory`, Fern's section route). */\ninterface ApiOperationLinkSource {\n filename: string\n content: Buffer\n /** Prefix path segment(s) the source platform served its auto-generated operation pages under (no leading/trailing slash); absent or empty means \"no known auto-generated prefix for this spec\" and it's skipped. */\n prefix?: string\n}\n\ninterface ApiOperationLinkMaps {\n /** Exact source-platform operation-page path (lowercased) -> Thally operation route. */\n operationLinks: Map<string, string>\n /**\n * Source-platform API-section route prefix (lowercased, no leading/trailing\n * slash) -> that spec's Thally landing route (`/api` for the first spec,\n * `/api/<specId>` for the rest). Used both for a bare tab-landing link\n * (the prefix on its own) and as the fallback for an operation link under\n * this prefix that didn't match any known operation.\n */\n prefixLandings: Map<string, string>\n}\n\nfunction apiOperationLinkMap(\n sources: Array<ApiOperationLinkSource>,\n docsConfig: MigrationDocsConfig,\n): ApiOperationLinkMaps {\n const map = new Map<string, string>()\n const prefixLandings = new Map<string, string>()\n const apiTabs = docsConfig.tabs.filter((tab) => !tab.hidden && tab.api)\n apiTabs.forEach((tab, index) => {\n const source = sources.find((entry) => tab.api?.source === `/${entry.filename}`)\n if (!source || !source.prefix) return\n const specId = index === 0 ? 'default' : slugifyApiSpecId(tab.tab)\n const prefix = source.prefix.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n if (prefix) prefixLandings.set(prefix, specId === 'default' ? '/api' : `/api/${specId}`)\n for (const operation of parseOpenApiOperationsForLinking(source.content)) {\n const thallyHref = `/api/${specId}/${thallyOperationSlugSegments(operation.path, operation.method).join('/')}`\n // Leaf candidates, tried in order of how likely a source generator is\n // to have used them: Mintlify slugs from the summary; Fern instead\n // prefers an SDK-style method name — confirmed against a live Fern\n // site, where `operationId: \"ToolController_create\"` (summary\n // \"Create Tool\") rendered its page at \".../tools/create\", the\n // operationId's segment after its last \"_\"/\".\", not the summary.\n const leafCandidates = new Set<string>()\n if (operation.operationId) {\n const parts = operation.operationId.split(/[_.]/).filter(Boolean)\n const lastPart = parts.at(-1) ?? operation.operationId\n // A NestJS-style controller method name (findOne/findAll/remove) is\n // common enough in real OpenAPI generators that Fern renders it\n // under its REST-conventional name instead — also confirmed live:\n // \"CallController_findOne\" rendered at \".../calls/get\", not\n // \".../calls/find-one\".\n const conventional = FERN_CRUD_METHOD_NAMES[lastPart.toLowerCase()]\n if (conventional) leafCandidates.add(conventional)\n leafCandidates.add(mintlifyOperationSlugSegment(lastPart))\n }\n if (operation.summary) leafCandidates.add(mintlifyOperationSlugSegment(operation.summary))\n if (operation.operationId) leafCandidates.add(mintlifyOperationSlugSegment(operation.operationId))\n leafCandidates.add(mintlifyOperationSlugSegment(`${operation.method} ${operation.path}`))\n // Two prefix conventions get registered for every leaf candidate:\n // Mintlify nests auto-generated pages under a tag folder\n // (\"<prefix>/<tag>/<leaf>\"); Fern's default layout serves them flat\n // under the section route (\"<prefix>/<leaf>\") instead. Registering\n // every combination costs nothing (an operation matches at most one\n // of them in practice) and avoids guessing which convention and\n // which leaf a given source actually used.\n const tagSegment = mintlifyOperationSlugSegment(operation.tag ?? 'default')\n for (const leaf of leafCandidates) {\n if (!leaf) continue\n const tagged = `${source.prefix}/${tagSegment}/${leaf}`.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n const flat = `${source.prefix}/${leaf}`.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n if (!map.has(tagged)) map.set(tagged, thallyHref)\n if (!map.has(flat)) map.set(flat, thallyHref)\n }\n }\n })\n return { operationLinks: map, prefixLandings }\n}\n\n/** Rewrite API operation links in every page body, with one capped warning for links that matched no operation. */\nfunction rewriteApiLinksInPages(\n pages: Array<MigrationPage>,\n operationLinks: Map<string, string>,\n prefixLandings: Map<string, string>,\n warnings: Array<MigrationWarning>,\n): void {\n if (operationLinks.size === 0 && prefixLandings.size === 0) return\n const unmatched = new Set<string>()\n for (const page of pages) {\n page.body = rewriteApiOperationLinks(page.body, operationLinks, prefixLandings, unmatched)\n }\n if (unmatched.size === 0) return\n const sorted = [...unmatched].sort()\n warnings.push({\n code: 'unsupported-config',\n message: `${sorted.length} link(s) to API endpoints matched no endpoint in the OpenAPI spec, so they now point to the API section's overview page instead: `\n + `${sorted.slice(0, 10).join(', ')}${sorted.length > 10 ? `, and ${sorted.length - 10} more` : ''}. Update those links if you want them to reach a specific endpoint.`,\n })\n}\n\n/**\n * Rewrite in-content links matching a source platform's auto-generated\n * OpenAPI operation pages to Thally's actual `/api/...` routes. A link\n * that is exactly a known API-section prefix (a bare tab-landing link, e.g.\n * \"/api-reference\") is rewritten to that spec's Thally landing route. A\n * link under a known prefix that doesn't match any specific operation\n * (renamed/removed operation, or a match this rewrite's heuristics missed)\n * falls back to the same landing route rather than staying broken, and its\n * original target is recorded into `unmatched` so the caller can emit one\n * aggregated warning instead of one per link. Links outside every known\n * prefix are left untouched — still broken, but no worse than before this\n * rewrite existed.\n */\nfunction rewriteApiOperationLinks(\n body: string,\n linkMap: Map<string, string>,\n prefixLandings: Map<string, string>,\n unmatched: Set<string>,\n): string {\n if (linkMap.size === 0 && prefixLandings.size === 0) return body\n // Longest prefix first, so a more specific API section (e.g.\n // \"api-reference/webhooks\") is preferred over a shorter one that happens\n // to also match (\"api-reference\").\n const orderedPrefixes = [...prefixLandings.entries()].sort((a, b) => b[0].length - a[0].length)\n let codeFence: string | null = null\n return body.split('\\n').map((line) => {\n const fence = line.match(/^\\s*(`{3,}|~{3,})/)\n if (fence) {\n if (!codeFence) codeFence = fence[1][0]\n else if (fence[1][0] === codeFence) codeFence = null\n return line\n }\n if (codeFence) return line\n const rewriteTarget = (target: string): string => {\n const suffixIndex = target.search(/[?#]/)\n const path = (suffixIndex >= 0 ? target.slice(0, suffixIndex) : target).replace(/^\\/+/, '').toLowerCase()\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n const mapped = linkMap.get(path)\n if (mapped) return `${mapped}${suffix}`\n for (const [prefix, landing] of orderedPrefixes) {\n if (path === prefix) return `${landing}${suffix}`\n if (path.startsWith(`${prefix}/`)) {\n unmatched.add(target)\n return `${landing}${suffix}`\n }\n }\n return target\n }\n return line\n .replace(/(\\]\\()\\/([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(`/${target}`)}`)\n .replace(/(\\bhref=\")\\/([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(`/${target}`)}${suffix}`)\n }).join('\\n')\n}\n\nconst MAX_FERN_GENERATORS_BYTES = 2_000_000\n\nfunction fernGeneratorsOpenApiPaths(config: Record<string, unknown>): Array<string> {\n const api = config.api\n if (typeof api === 'string') return [api]\n if (!api || typeof api !== 'object' || Array.isArray(api)) return []\n const specs = (api as Record<string, unknown>).specs\n if (!Array.isArray(specs)) return []\n return specs.flatMap((spec) => {\n if (typeof spec === 'string') return [spec]\n if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return []\n const openapi = (spec as Record<string, unknown>).openapi\n return typeof openapi === 'string' ? [openapi] : []\n })\n}\n\n/**\n * Fern's `generators.yml` can also point an `api.specs[]` entry at an\n * AsyncAPI or OpenRPC document instead of OpenAPI. Thally's API reference\n * only renders OpenAPI, so these are named here purely to produce a\n * specific warning (`fernGeneratorsOpenApiPaths` above never returns them,\n * so without this they'd otherwise look like a missing spec).\n */\nfunction fernGeneratorsUnsupportedSpecPaths(config: Record<string, unknown>): Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> {\n const api = config.api\n if (!api || typeof api !== 'object' || Array.isArray(api)) return []\n const specs = (api as Record<string, unknown>).specs\n if (!Array.isArray(specs)) return []\n return specs.flatMap((spec): Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> => {\n if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return []\n const record = spec as Record<string, unknown>\n if (typeof record.asyncapi === 'string') return [{ kind: 'asyncapi', path: record.asyncapi }]\n if (typeof record.openrpc === 'string') return [{ kind: 'openrpc', path: record.openrpc }]\n return []\n })\n}\n\nfunction readFernGeneratorsConfig(path: string): Record<string, unknown> | null {\n if (!existsSync(path) || !lstatSync(path).isFile() || lstatSync(path).size > MAX_FERN_GENERATORS_BYTES) return null\n const parsed = parseYaml(readFileSync(path, 'utf8'))\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null\n}\n\n/**\n * Resolve the OpenAPI spec Fern's `generators.yml` configures for an API:\n * modern `api.specs[].openapi`, or the legacy top-level `api:` string.\n * Multi-API repos keep a `generators.yml` per API under `fern/apis/<name>/`;\n * single-API repos keep one at the Fern project root.\n *\n * The root `generators.yml` belongs to a *different* API only in a multi-API\n * repo, which Fern lays out under `fern/apis/`. So the root config is skipped\n * only when an explicit `api-name` is set AND a `fern/apis/` directory\n * exists; a single-API repo whose docs.yml still names its API keeps its tab.\n */\nfunction fernOpenApiCandidateDirs(fernRoot: string, apiName: string | undefined, apiNameExplicit: boolean): Array<string> {\n const candidateDirs: Array<string> = []\n if (apiName) {\n try {\n candidateDirs.push(resolveWithin(fernRoot, `apis/${apiName}`))\n } catch {\n // Not a safe relative path (e.g. a display label, not a folder name).\n }\n }\n const apisDir = resolvePath(fernRoot, 'apis')\n const multiApi = existsSync(apisDir) && lstatSync(apisDir).isDirectory()\n if (!apiNameExplicit || !multiApi) candidateDirs.push(fernRoot)\n return candidateDirs\n}\n\n/** `findFernConfiguredOpenApi`'s result, plus any AsyncAPI/OpenRPC specs seen along the way (Thally has no renderer for either). */\ninterface FernOpenApiResolution {\n spec: ScannedFile | null\n unsupported: Array<{ kind: 'asyncapi' | 'openrpc'; path: string }>\n}\n\nfunction findFernConfiguredOpenApi(\n fernRoot: string,\n repositoryDir: string,\n apiName: string | undefined,\n apiNameExplicit: boolean,\n warnings: Array<MigrationWarning>,\n): FernOpenApiResolution {\n const candidateDirs = fernOpenApiCandidateDirs(fernRoot, apiName, apiNameExplicit)\n const unsupported: Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> = []\n for (const dir of candidateDirs) {\n let config: Record<string, unknown> | null = null\n let generatorsPath: string\n try {\n generatorsPath = resolveWithin(dir, 'generators.yml')\n config = readFernGeneratorsConfig(generatorsPath)\n } catch {\n continue\n }\n if (!config) continue\n for (const specPath of fernGeneratorsOpenApiPaths(config)) {\n if (/^(?:https?:)?\\/\\//i.test(specPath)) continue\n // `openapi:` in generators.yml is conventionally relative to that\n // file's own directory (a multi-API repo's `fern/apis/<name>/`), not\n // to the Fern root, so it commonly points outside `dir` (e.g. Cohere's\n // `../../../cohere-openapi.yaml`). The security boundary is still the\n // whole repository checkout, never anything above it.\n try {\n const absolute = resolveWithinRoot(dir, specPath, repositoryDir)\n if (!existsSync(absolute) || !lstatSync(absolute).isFile()) continue\n const kind = classifyApiSpec(absolute)\n if (kind === 'asyncapi') {\n unsupported.push({ kind: 'asyncapi', path: specPath })\n continue\n }\n if (kind !== 'openapi') continue\n return { spec: { absolutePath: absolute, relativePath: relative(repositoryDir, absolute).replace(/\\\\/g, '/') }, unsupported }\n } catch {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec path \"${specPath}\" in ${relative(repositoryDir, generatorsPath).replace(/\\\\/g, '/')} is outside the repository and was skipped.`,\n })\n }\n }\n unsupported.push(...fernGeneratorsUnsupportedSpecPaths(config))\n }\n return { spec: null, unsupported }\n}\n\n/** Whether a Fern Definition (as opposed to a plain OpenAPI/AsyncAPI spec) backs this API. */\nfunction fernDefinitionExists(fernRoot: string, apiName: string | undefined): boolean {\n const candidateDirs: Array<string> = []\n if (apiName) {\n try {\n candidateDirs.push(resolveWithin(fernRoot, `apis/${apiName}/definition`))\n } catch {\n // Not a safe relative path; skip.\n }\n }\n try {\n candidateDirs.push(resolveWithin(fernRoot, 'definition'))\n } catch {\n // Unreachable: 'definition' is always a safe relative segment.\n }\n return candidateDirs.some((dir) => existsSync(dir) && lstatSync(dir).isDirectory())\n}\n\nfunction withoutFrontmatter(value: string): string {\n return value.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, '').trim()\n}\n\nfunction staticSnippetProperties(attributes: string): Map<string, string> {\n const properties = new Map<string, string>()\n const matcher = /\\b([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{\\s*\"([^\"]*)\"\\s*\\}|\\{\\s*'([^']*)'\\s*\\})/g\n for (const match of attributes.matchAll(matcher)) {\n properties.set(match[1], match[2] ?? match[3] ?? match[4] ?? match[5] ?? '')\n }\n return properties\n}\n\nfunction interpolateSnippet(snippet: string, attributes: string, children?: string): string {\n const properties = staticSnippetProperties(attributes)\n if (children !== undefined) properties.set('children', children.trim())\n if (properties.size === 0) return snippet\n const isJsxSnippet = /<[A-Za-z][A-Za-z0-9]*/.test(snippet)\n let fence = ''\n return snippet.split('\\n').map((line) => {\n const marker = line.match(/^\\s*(`{3,}|~{3,})/)?.[1]\n if (marker) {\n if (!fence) fence = marker[0]\n else if (marker[0] === fence) fence = ''\n return line\n }\n if (fence) return line\n return line.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (original, name: string) => {\n const value = properties.get(name)\n // Preserve MDX expression syntax: a literal replacement inside JSX\n // would turn `<a href={url}>` into invalid `href=https://...`.\n if (value === undefined) return original\n if (name === 'children') return value\n return isJsxSnippet ? `{${JSON.stringify(value)}}` : value\n })\n }).join('\\n')\n}\n\n/** Extract JSX from a statically declared snippet component before inlining it. */\nfunction snippetComponentBody(source: string, componentName: string): string {\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== componentName) continue\n const initializer = declaration.initializer\n if (!initializer || !ts.isArrowFunction(initializer)) continue\n const returned = ts.isBlock(initializer.body)\n ? initializer.body.statements.find(ts.isReturnStatement)?.expression\n : initializer.body\n if (!returned) continue\n let expression: ts.Expression = returned\n while (ts.isParenthesizedExpression(expression)) expression = expression.expression\n if (ts.isJsxElement(expression) || ts.isJsxSelfClosingElement(expression) || ts.isJsxFragment(expression)) {\n return expression.getText(parsed)\n }\n }\n }\n return source\n}\n\n/** Keep a stateful snippet intact so its hooks and local values move with its JSX. */\nfunction statefulSnippetDeclaration(source: string, componentName: string): string | null {\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n if (parsed.statements.length !== 1) return null\n const statement = parsed.statements[0]\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n || statement.declarationList.declarations.length !== 1) return null\n const declaration = statement.declarationList.declarations[0]\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== componentName\n || !declaration.initializer || !ts.isArrowFunction(declaration.initializer)\n || !ts.isBlock(declaration.initializer.body)) return null\n const body = declaration.initializer.body.statements\n // A component with setup statements before its return cannot be flattened\n // to its returned JSX: that strands hooks, computed values, and handlers.\n if (body.length < 2 || !body.some(ts.isReturnStatement)) return null\n return source.trim()\n}\n\n/** Read only primitive named exports; source MDX is parsed, never executed. */\nfunction staticNamedSnippetValues(source: string): Map<string, string> {\n const values = new Map<string, string>()\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue\n const expression = declaration.initializer\n if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {\n values.set(declaration.name.text, JSON.stringify(expression.text))\n } else if (ts.isNumericLiteral(expression)) {\n values.set(declaration.name.text, expression.text)\n } else if (expression.kind === ts.SyntaxKind.TrueKeyword || expression.kind === ts.SyntaxKind.FalseKeyword) {\n values.set(declaration.name.text, expression.kind === ts.SyntaxKind.TrueKeyword ? 'true' : 'false')\n }\n }\n }\n return values\n}\n\n/** MDX imports from nested Markdown partials must live at page scope. */\nfunction hoistMdxImports(source: string): string {\n const imports = new Set<string>()\n const withoutImports = replaceOutsideCode(source, (body) => body.replace(\n /^[ \\t]*import\\s+(?:\\{[^}\\n]+\\}|[A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])[^'\"\\n]+\\1[ \\t]*;?/gm,\n (statement: string) => {\n imports.add(statement.trim().replace(/;?$/, ';'))\n return ''\n },\n ))\n if (imports.size === 0) return source\n const frontmatter = withoutImports.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/)\n const prefix = frontmatter?.[0] ?? ''\n return `${prefix}${[...imports].join('\\n')}\\n\\n${withoutImports.slice(prefix.length).replace(/^(?:\\r?\\n)*/, '')}`\n}\n\n/** Fern can publish a repository beneath a domain path such as `/skills`. */\nfunction fernSourceBasePath(config: Record<string, unknown>): string {\n const instance = Array.isArray(config.instances) ? config.instances[0] : null\n if (!instance || typeof instance !== 'object' || Array.isArray(instance)) return ''\n const value = instance as Record<string, unknown>\n const address = typeof value['custom-domain'] === 'string' ? value['custom-domain'] : value.url\n if (typeof address !== 'string') return ''\n try {\n const path = new URL(/^https?:\\/\\//i.test(address) ? address : `https://${address}`).pathname.replace(/\\/+$/, '')\n return path === '/' ? '' : path\n } catch {\n return ''\n }\n}\n\n/** The imported Fern version's URL prefix is omitted from Thally's routes. */\nfunction fernDefaultVersionPath(config: Record<string, unknown>): string {\n if (!Array.isArray(config.versions)) return ''\n const versions = config.versions.filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object' && !Array.isArray(entry))\n const chosen = versions.find((version) => version.default === true) ?? versions[0]\n return typeof chosen?.slug === 'string' && /^[A-Za-z0-9_-]+$/.test(chosen.slug) ? `/${chosen.slug}` : ''\n}\n\n/** Preserve the published Fern host for references outside the imported pages. */\nfunction fernSourceSiteUrl(config: Record<string, unknown>): string | undefined {\n const instance = Array.isArray(config.instances) ? config.instances[0] : null\n if (!instance || typeof instance !== 'object' || Array.isArray(instance)) return undefined\n const value = instance as Record<string, unknown>\n const address = typeof value['custom-domain'] === 'string' ? value['custom-domain'] : value.url\n if (typeof address !== 'string') return undefined\n try {\n const url = new URL(/^https?:\\/\\//i.test(address) ? address : `https://${address}`)\n return `${url.origin}${fernSourceBasePath(config)}${fernDefaultVersionPath(config)}`\n } catch {\n return undefined\n }\n}\n\n/** Keep unresolved root-relative links usable on the source site, with an explicit warning. */\nfunction externalizeMissingFernLinks(body: string, pageIds: ReadonlySet<string>, sourceSiteUrl: string, externalized: Set<string>): string {\n const rewrite = (target: string): string => {\n const path = target.split(/[?#]/, 1)[0].replace(/^\\//, '').replace(/\\/$/, '')\n // Only unresolved page routes belong on the source site. Fern pages may\n // reference copied public assets with root-relative Markdown links; an\n // image or download is not a missing docs page.\n if (!path || pageIds.has(path) || ASSET_EXTENSIONS.has(extname(path).toLowerCase())) return target\n try {\n const base = new URL(`${sourceSiteUrl}/`)\n const sourceLinkUrl = new URL(target.slice(1), base)\n if (sourceLinkUrl.origin !== base.origin) return target\n const sourceLink = sourceLinkUrl.toString()\n externalized.add(target)\n return sourceLink\n } catch {\n return target\n }\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()\\/(?!\\/)([^\\s)]+)(\\))/g, (_match, before: string, target: string, after: string) => `${before}${rewrite(`/${target}`)}${after}`)\n .replace(/(\\b(?:href|to)=(['\"]))\\/(?!\\/)([^'\"\\n]+)\\2/g, (_match, before: string, quote: string, target: string) => `${before}${rewrite(`/${target}`)}${quote}`))\n}\n\n/** Rewrite only root-relative Markdown/JSX links, never URLs or code examples. */\nfunction stripFernBasePathFromLinks(body: string, basePath: string): string {\n if (!basePath) return body\n const escaped = basePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return replaceOutsideCode(body, (text) => text\n .replace(new RegExp(`(\\\\]\\\\()${escaped}(?=\\\\/|[)#?])`, 'g'), (match, prefix: string, offset: number, source: string) => (\n prefix + (source[offset + match.length] === '/' ? '' : '/')\n ))\n .replace(new RegExp(`(\\\\b(?:href|to)=[\"'])${escaped}(?=\\\\/|[\"'#?])`, 'g'), (match, prefix: string, offset: number, source: string) => (\n prefix + (source[offset + match.length] === '/' ? '' : '/')\n )))\n}\n\n/** Remove a published Mintlify mount path only when its destination is an imported page. */\nfunction rewriteMintlifyMountedLinks(body: string, pageIds: ReadonlySet<string>): string {\n const rewrite = (target: string): string => {\n const suffixAt = target.search(/[?#]/)\n const pathname = suffixAt < 0 ? target : target.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : target.slice(suffixAt)\n if (!pathname.startsWith('/') || pathname.startsWith('//') || pathname.includes('\\\\')) return target\n const segments = pathname.slice(1).split('/')\n if (segments.some((segment) => !segment || segment === '.' || segment === '..')) return target\n if (pageIds.has(segments.join('/'))) return target\n // A source site may serve its docs below /docs or another mount. Limit\n // removal to a leading path prefix and prove the remaining route exists;\n // this leaves real /docs pages and non-page assets untouched.\n for (let count = 1; count < segments.length && count <= 3; count++) {\n const candidate = segments.slice(count).join('/')\n if (pageIds.has(candidate)) return `/${candidate}${suffix}`\n }\n return target\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()(\\/[^\\s)]+)(\\))/g, (_match, before: string, target: string, after: string) => `${before}${rewrite(target)}${after}`)\n .replace(/(\\b(?:href|to)=(['\"]))(\\/[^'\"\\n]+)\\2/g, (_match, before: string, quote: string, target: string) => `${before}${rewrite(target)}${quote}`))\n}\n\n/** Preserve source fragments that resolve to a unique heading or table row. */\nfunction preserveLinkedAnchors(pages: Array<MigrationPage>): void {\n const pageById = new Map(pages.map((page) => [page.id, page]))\n const requested = new Map<string, Set<string>>()\n const crossPageRequests = new Set<string>()\n const addTarget = (target: string, currentId: string): void => {\n const hash = target.indexOf('#')\n if (hash < 0) return\n let fragment: string\n try { fragment = decodeURIComponent(target.slice(hash + 1)) } catch { return }\n // Only HTML-attribute-safe fragments can become explicit IDs. Encoded\n // fragments are common in exported docs, including names with `$`.\n if (!/^[\\p{L}\\p{N}_.:$-]{1,120}$/u.test(fragment)) return\n const path = target.slice(0, hash).split('?')[0]\n const id = target.startsWith('#') ? currentId : path.startsWith('/') && !path.startsWith('//')\n ? path.replace(/^\\//, '').replace(/\\/$/, '') || 'introduction' : ''\n if (!pageById.has(id)) return\n if (!requested.has(id)) requested.set(id, new Set())\n requested.get(id)!.add(fragment)\n if (id !== currentId) crossPageRequests.add(`${id}#${fragment}`)\n }\n for (const page of pages) {\n replaceOutsideCode(page.body, (text) => {\n for (const match of text.matchAll(/\\]\\(([^)\\s]+)\\)/g)) addTarget(match[1], page.id)\n for (const match of text.matchAll(/\\b(?:href|to)=(['\"])([^'\"\\n]+)\\1/g)) addTarget(match[2], page.id)\n return text\n })\n }\n const comparable = (value: string): string => value\n .replace(/&(?:lt|gt|amp|quot);/g, ' ')\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, '')\n for (const page of pages) {\n const fragments = requested.get(page.id)\n if (!fragments?.size) continue\n const lines = page.body.split('\\n')\n let fence: string | undefined\n const tableCells: Array<{ index: number; text: string }> = []\n const headings = lines.map((line, index) => {\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = undefined\n return null\n }\n if (fence) return null\n const tableCell = line.match(/^ {0,3}\\|\\s*([^|]+?)\\s*\\|/)\n if (tableCell && !/^[:\\s-]+$/.test(tableCell[1])) tableCells.push({ index, text: tableCell[1] })\n const match = line.match(/^ {0,3}#{1,6}\\s+(.+?)\\s*#*\\s*$/)\n return match ? { index, text: match[1] } : null\n }).filter((entry): entry is { index: number; text: string } => entry !== null)\n const existing = new Set<string>()\n replaceOutsideCode(page.body, (text) => {\n for (const match of text.matchAll(/\\bid=(?:\"([^\"]+)\"|'([^']+)')/g)) existing.add(match[1] ?? match[2])\n return text\n })\n const candidateIndexes = new Map<string, Array<{ index: number; kind: 'heading' | 'table' }>>()\n for (const heading of headings) {\n const key = comparable(heading.text)\n candidateIndexes.set(key, [...(candidateIndexes.get(key) ?? []), { index: heading.index, kind: 'heading' }])\n }\n for (const cell of tableCells) {\n const key = comparable(cell.text)\n candidateIndexes.set(key, [...(candidateIndexes.get(key) ?? []), { index: cell.index, kind: 'table' }])\n }\n for (const heading of headings) existing.add(heading.text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''))\n const headingAliases = new Map<number, Array<string>>()\n const tableAliases = new Map<number, Array<string>>()\n for (const fragment of fragments) {\n if (existing.has(fragment)) continue\n const matches = candidateIndexes.get(comparable(fragment)) ?? []\n let match = matches.length === 1 ? matches[0] : undefined\n if (!match && matches.length > 1 && !crossPageRequests.has(`${page.id}#${fragment}`)) {\n // Repeated option names can occur in several tables. A same-page\n // reference after one of them refers to the nearest preceding option;\n // only add an alias when every real local link agrees on that row.\n const escaped = fragment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const linkPattern = new RegExp(`\\\\]\\\\(#${escaped}\\\\)|\\\\b(?:href|to)=[\"']#${escaped}[\"']`)\n const linkIndexes = lines.flatMap((line, index) => linkPattern.test(line) ? [index] : [])\n const selections = linkIndexes.map((index) => matches.filter((candidate) => candidate.index < index).at(-1))\n if (selections.length && selections.every((candidate) => candidate?.index === selections[0]?.index)) match = selections[0]\n }\n if (!match) continue\n const { index, kind } = match\n const aliases = kind === 'heading' ? headingAliases : tableAliases\n aliases.set(index, [...(aliases.get(index) ?? []), fragment])\n existing.add(fragment)\n }\n if (headingAliases.size || tableAliases.size) page.body = lines.flatMap((line, index) => [\n ...(headingAliases.get(index) ?? []).map((fragment) => `<a id=\"${fragment}\"></a>`),\n tableAliases.has(index)\n ? line.replace(/^( {0,3}\\|\\s*)/, (prefix) => `${prefix}${tableAliases.get(index)!.map((fragment) => `<a id=\"${fragment}\"></a>`).join('')}`)\n : line,\n ]).join('\\n')\n }\n}\n\n/** Prevent an entry's EOF-terminated fence from swallowing the next feed entry. */\nfunction closeOpenCodeFence(body: string): string {\n let open: { marker: string; length: number } | null = null\n for (const line of body.split(/\\r?\\n/)) {\n const match = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)\n if (!match) continue\n const marker = match[1][0]\n if (!open) {\n open = { marker, length: match[1].length }\n } else if (marker === open.marker && match[1].length >= open.length && !match[2].trim()) {\n open = null\n }\n }\n return open ? `${body}\\n\\n${open.marker.repeat(open.length)}` : body\n}\n\n/** Fern changelog fragments prefix each article heading with its date. */\nfunction addDatedHeadingAliases(body: string, date: string): string {\n let open: { marker: string; length: number } | null = null\n const existingIds = new Set([...body.matchAll(/<a\\s+id=[\"']([^\"']+)[\"']/g)].map((match) => match[1]))\n return body.split(/\\r?\\n/).flatMap((line) => {\n const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)\n if (fence) {\n const marker = fence[1][0]\n if (!open) open = { marker, length: fence[1].length }\n else if (marker === open.marker && fence[1].length >= open.length && !fence[2].trim()) open = null\n return [line]\n }\n if (open) return [line]\n const heading = line.match(/^#{2,6}\\s+(.+?)\\s*#*\\s*$/)\n if (!heading) return [line]\n const slug = heading[1]\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1')\n .replace(/[`*_]/g, '')\n .normalize('NFKD').toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s-]/gu, '')\n .trim().replace(/\\s+/g, '-')\n const id = `${date}-${slug}`\n if (!slug || existingIds.has(id)) return [line]\n existingIds.add(id)\n return [`<a id=\"${id}\" />`, '', line]\n }).join('\\n')\n}\n\nfunction resolveSnippetPath(\n sourcePath: string,\n currentFile: string,\n repositoryRoot: string,\n siteRoot: string,\n): string {\n // Markdown authors sometimes escape a leading underscore in an import\n // path; the repository filename itself is still unescaped.\n sourcePath = sourcePath.replace(/\\\\(?=_)/g, '')\n const repositoryRelative = sourcePath.startsWith('@site/')\n ? relative(repositoryRoot, resolveWithin(siteRoot, sourcePath.slice('@site/'.length))).replace(/\\\\/g, '/')\n : sourcePath.startsWith('/')\n ? relative(repositoryRoot, resolveWithin(siteRoot, sourcePath.replace(/^\\/+/, ''))).replace(/\\\\/g, '/')\n : relative(repositoryRoot, resolvePath(dirname(currentFile), sourcePath)).replace(/\\\\/g, '/')\n const candidate = resolveWithin(repositoryRoot, repositoryRelative)\n resolveWithin(repositoryRoot, relative(repositoryRoot, candidate))\n return candidate\n}\n\nfunction globalSnippetAliases(\n files: Array<ScannedFile>,\n repositoryRoot: string,\n siteRoot: string,\n): Map<string, string> {\n const aliases = new Map<string, string>()\n for (const file of files) {\n const segments = file.relativePath.split('/')\n if (!segments.some((segment) => SNIPPET_DIRECTORIES.has(segment.toLowerCase()))) continue\n const basenameWithoutExtension = basename(file.relativePath).replace(/\\.mdx?$/i, '')\n const conventionalAlias = basenameWithoutExtension\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n if (conventionalAlias) aliases.set(conventionalAlias, file.absolutePath)\n }\n for (const file of files) {\n if (!['.md', '.mdx'].includes(extname(file.relativePath).toLowerCase())) continue\n const raw = readFileSync(file.absolutePath, 'utf8')\n for (const match of raw.matchAll(SNIPPET_IMPORT_PATTERN)) {\n try {\n const componentName = match[1] ?? match[2]\n const candidate = resolveSnippetPath(match[3], file.absolutePath, repositoryRoot, siteRoot)\n if (existsSync(candidate) && lstatSync(candidate).isFile()) {\n aliases.set(componentName, candidate)\n }\n } catch {\n // The page-local inliner emits the actionable warning when it reaches\n // an unsafe or missing import. Global discovery is best-effort only.\n }\n }\n }\n return aliases\n}\n\nfunction repositoryAssetHref(\n value: string,\n currentFile: string,\n siteRoot: string,\n onReferenced?: (normalizedPath: string) => void,\n): string | null {\n const isBracketed = value.startsWith('<') && value.endsWith('>')\n const raw = isBracketed ? value.slice(1, -1) : value\n if (!raw || raw.startsWith('#') || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(raw)) return null\n const suffixIndex = raw.search(/[?#]/)\n const pathname = suffixIndex >= 0 ? raw.slice(0, suffixIndex) : raw\n const suffix = suffixIndex >= 0 ? raw.slice(suffixIndex) : ''\n let decodedPath: string\n try {\n decodedPath = decodeURIComponent(pathname)\n } catch {\n return null\n }\n if (!ASSET_EXTENSIONS.has(extname(decodedPath).toLowerCase())) return null\n try {\n const candidate = decodedPath.startsWith('/')\n ? resolveWithin(siteRoot, decodedPath.replace(/^\\/+/, ''))\n : resolveWithinRoot(dirname(currentFile), decodedPath, siteRoot)\n // Resolve every path component before accepting an asset. A repository\n // could contain a symlinked directory whose lexical path stays under\n // the docs root while its file contents live elsewhere on the host.\n const realRoot = realpathSync(siteRoot)\n const realCandidate = realpathSync(candidate)\n const realRelative = relative(realRoot, realCandidate)\n if (realRelative === '..' || realRelative.startsWith(`..${sep}`) || isAbsolute(realRelative)) return null\n // Mintlify's deploy root is the directory containing docs.json. Do not\n // copy or expose a relative reference that escapes that project boundary.\n const siteRelative = relative(siteRoot, candidate).replace(/\\\\/g, '/')\n resolveWithin(siteRoot, siteRelative)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) return null\n const normalized = normalizeAssetPath(siteRelative)\n if (!normalized) return null\n onReferenced?.(normalized)\n const rewritten = `/${normalized}${suffix}`\n // Markdown destinations containing parentheses must stay angle-bracketed;\n // removing the wrapper makes CommonMark terminate the URL too early.\n return isBracketed ? `<${rewritten}>` : rewritten\n } catch {\n return null\n }\n}\n\n/**\n * Rewrite links to a page whose Fern frontmatter `slug` replaced its docs.yml\n * hierarchy. Other pages still spell the link the \"natural\" nested way, so\n * this runs across every page's body, not just the renamed page's own.\n */\nfunction rewriteFernIdRenameLinks(body: string, renames: Map<string, string>): string {\n return replaceOutsideCode(body, (text) => {\n const rewriteTarget = (target: string): string => {\n const suffixIndex = target.search(/[?#]/)\n const path = (suffixIndex >= 0 ? target.slice(0, suffixIndex) : target).replace(/^\\/+/, '')\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n const renamed = renames.get(path)\n return renamed ? `/${renamed}${suffix}` : target\n }\n return text\n .replace(/(\\]\\()\\/([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(`/${target}`)}`)\n .replace(/(\\bhref=\")\\/([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(`/${target}`)}${suffix}`)\n })\n}\n\nfunction rewriteRepositoryAssetLinks(\n body: string,\n currentFile: string,\n siteRoot: string,\n onReferenced?: (normalizedPath: string) => void,\n): string {\n return body\n .replace(/(!?\\[[^\\]]*\\]\\()(<[^>]+>|[^)\\s]+)([^)]*\\))/g, (\n original,\n opening: string,\n destination: string,\n closing: string,\n ) => {\n const rewritten = repositoryAssetHref(destination, currentFile, siteRoot, onReferenced)\n return rewritten ? `${opening}${rewritten}${closing}` : original\n })\n .replace(/\\b(src|img|image|href)=(['\"])([^'\"]+)\\2/g, (\n original,\n property: string,\n quote: string,\n destination: string,\n ) => {\n const rewritten = repositoryAssetHref(destination, currentFile, siteRoot, onReferenced)\n return rewritten ? `${property}=${quote}${rewritten}${quote}` : original\n })\n}\n\nconst LOCAL_EXPORT_DECLARATION = /^\\s*export\\s+(?:const|let|var|function|class|async\\s+function)\\s+([A-Za-z_$][\\w$]*)/\n\n/**\n * Names a page declares itself with a top-level `export const/function/class`.\n * Mintlify treats every file under `/snippets/` as an implicitly available\n * global component keyed by its filename, so a page that happens to declare\n * an inline component with the same name (e.g. both `snippets/counter.mdx`\n * and a page's own `export const Counter = ...`) must keep its local\n * declaration: forcing the unrelated global snippet's source in over a\n * `<Counter />` usage duplicates the export and breaks the compiled module.\n */\nfunction locallyDeclaredNames(raw: string): Set<string> {\n const names = new Set<string>()\n let codeFence: string | null = null\n for (const line of raw.split('\\n')) {\n const codeMatch = line.match(/^\\s*(`{3,}|~{3,})/)\n if (codeMatch) {\n if (!codeFence) codeFence = codeMatch[1][0]\n else if (codeMatch[1][0] === codeFence) codeFence = null\n continue\n }\n if (codeFence) continue\n const declared = line.match(LOCAL_EXPORT_DECLARATION)?.[1]\n if (declared) names.add(declared)\n }\n return names\n}\n\nfunction inlineMdxSnippets(\n raw: string,\n currentFile: string,\n repositoryRoot: string,\n warnings: Array<MigrationWarning>,\n depth = 0,\n siteRoot = repositoryRoot,\n globalAliases: Map<string, string> = new Map(),\n): string {\n if (depth >= 8) return raw\n // Hoisting page imports must see indented JSX code examples as fenced code.\n // Otherwise imports shown in translated <Step> examples become live MDX\n // imports, disappear from the example, and can break the server build.\n raw = normalizeIndentedFences(raw)\n const snippets = new Map<string, string>()\n const preservedDeclarations = new Map<string, string>()\n let withoutImports = replaceOutsideCode(raw, (source) => source.replace(\n SNIPPET_IMPORT_PATTERN,\n (_statement, namedComponent: string | undefined, defaultComponent: string | undefined, sourcePath: string) => {\n const componentName = (namedComponent ?? defaultComponent) as string\n try {\n const candidate = resolveSnippetPath(sourcePath, currentFile, repositoryRoot, siteRoot)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) throw new Error('file not found')\n const nested = inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n const declaration = statefulSnippetDeclaration(nested, componentName)\n if (declaration) preservedDeclarations.set(componentName, declaration)\n else snippets.set(componentName, snippetComponentBody(nested, componentName))\n return ''\n } catch {\n warnings.push({\n code: 'missing-page',\n message: `Imported snippet ${sourcePath} could not be resolved and was left as a comment.`,\n source: relative(repositoryRoot, currentFile).replace(/\\\\/g, '/'),\n })\n snippets.set(componentName, `{/* Missing imported snippet: ${sourcePath} */}`)\n return ''\n }\n },\n ))\n withoutImports = replaceOutsideCode(withoutImports, (source) => source.replace(\n SNIPPET_VALUE_IMPORT_PATTERN,\n (statement: string, names: string, sourcePath: string) => {\n const bindings = names.split(',').map((name) => name.trim()).filter(Boolean).map((name) => {\n const parsed = name.match(/^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/)\n return parsed ? { exported: parsed[1], local: parsed[2] ?? parsed[1] } : null\n })\n if (bindings.length === 0 || bindings.some((binding) => !binding)) return statement\n try {\n const candidate = resolveSnippetPath(sourcePath, currentFile, repositoryRoot, siteRoot)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) return statement\n const snippetSource = readFileSync(candidate, 'utf8')\n const values = staticNamedSnippetValues(snippetSource)\n const declarations: Array<string> = []\n const components: Array<[string, string]> = []\n for (const binding of bindings) {\n const value = values.get(binding!.exported)\n if (value !== undefined) {\n declarations.push(`export const ${binding!.local} = ${value};`)\n continue\n }\n if (!/^[A-Z]/.test(binding!.exported)) return statement\n const body = snippetComponentBody(snippetSource, binding!.exported)\n if (body === snippetSource) return statement\n components.push([binding!.local, body])\n }\n for (const [name, body] of components) snippets.set(name, body)\n return declarations.join('\\n')\n } catch {\n return statement\n }\n },\n ))\n // Mintlify resolves snippet imports across its MDX compilation graph. Some\n // real sites consequently reuse an alias on a page that does not repeat the\n // import declaration. Recover those aliases deterministically from imports\n // elsewhere in the same docs project.\n const localNames = locallyDeclaredNames(withoutImports)\n for (const [componentName, candidate] of globalAliases) {\n if (snippets.has(componentName) || localNames.has(componentName)\n || !new RegExp(`<${componentName}(?:\\\\s|/?>)`).test(withoutImports)) continue\n const nested = inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n const declaration = statefulSnippetDeclaration(nested, componentName)\n if (declaration) preservedDeclarations.set(componentName, declaration)\n else snippets.set(componentName, snippetComponentBody(nested, componentName))\n }\n let result = withoutImports\n for (const [componentName, snippet] of snippets) {\n result = result\n .replace(new RegExp(`<${componentName}((?:\\\\s[^>]*)?)\\\\s*/>`, 'g'), (_tag, attributes: string) => {\n return interpolateSnippet(snippet, attributes)\n })\n .replace(new RegExp(`<${componentName}((?:\\\\s[^>]*)?)>([\\\\s\\\\S]*?)<\\\\/${componentName}>`, 'g'), (_tag, attributes: string, children: string) => {\n return interpolateSnippet(snippet, attributes, children)\n })\n }\n result = result.replace(SNIPPET_TAG_PATTERN, (_tag, doubleQuoted: string | undefined, singleQuoted: string | undefined) => {\n const filePath = (doubleQuoted ?? singleQuoted)!\n try {\n const candidate = resolveWithin(siteRoot, `snippets/${filePath}`)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) throw new Error('file not found')\n return inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n } catch {\n warnings.push({\n code: 'missing-page',\n message: `Snippet file=\"${filePath}\" could not be resolved and was left as a comment.`,\n source: relative(repositoryRoot, currentFile).replace(/\\\\/g, '/'),\n })\n return `{/* Missing snippet: ${filePath} */}`\n }\n })\n if (preservedDeclarations.size > 0) {\n const frontmatter = result.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/)\n const prefix = frontmatter?.[0] ?? ''\n result = `${prefix}${[...preservedDeclarations.values()].join('\\n\\n')}\\n\\n${result.slice(prefix.length)}`\n }\n return depth === 0 ? hoistMdxImports(result) : result\n}\n\n/**\n * Bind one or more resolved specs into their tabs. A spec with no\n * `tabLabel` (the common single-spec case) falls back to an existing\n * \"*api*\"-labelled tab, or gets a new \"API Reference\" tab of its own — the\n * original single-spec behavior. A spec with a `tabLabel` only ever binds\n * to that exact tab (creating it if the source tab had no other content\n * and so was dropped from `config.tabs` earlier), never the loose\n * substring fallback, so two specs from two different tabs can never both\n * land on the same tab by accident.\n */\nfunction injectOpenApiSpecs(\n config: MigrationDocsConfig,\n specs: Array<{ filename: string; tabLabel?: string }>,\n warnings?: Array<MigrationWarning>,\n): MigrationDocsConfig {\n let tabs = config.tabs.map((tab) => ({ ...tab }))\n for (const spec of specs) {\n const apiTab = spec.tabLabel\n ? tabs.find((tab) => tab.tab === spec.tabLabel)\n : tabs.find((tab) => tab.tab.toLowerCase().includes('api'))\n if (apiTab) {\n // Thally binds one API spec per tab; a second spec that resolves to\n // the same tab would otherwise silently replace the first one's\n // binding with no trace of it ever having existed.\n if (apiTab.api && warnings) {\n warnings.push({\n code: 'unsupported-config',\n message: `Tab \"${apiTab.tab}\" already uses another OpenAPI spec, and Thally supports one API spec per tab, so \"/${spec.filename}\" was not added. Put it in its own tab to include it.`,\n })\n continue\n }\n apiTab.api = {\n source: `/${spec.filename}`,\n // An API-only tab needs generated endpoint navigation; an authored\n // page tab keeps its own groups alongside the bound spec.\n ...((apiTab.groups?.length || apiTab.pages?.length) ? { navigation: false } : {}),\n }\n } else {\n tabs = [...tabs, { tab: spec.tabLabel ?? 'API Reference', api: { source: `/${spec.filename}` } }]\n }\n }\n return { ...config, tabs }\n}\n\n/** Identify component ownership independently of checkout paths and URL syntax. */\nfunction componentSourceIdentity(sourceUrl: string, repositoryDir: string, siteRoot: string): string {\n const url = new URL(sourceUrl)\n // A GitHub tree URL and the repository root identify the same source. Branch\n // changes should update its components, while separate monorepo sites must\n // retain independent namespaces even if their snippet filenames coincide.\n // Credentials, queries and fragments are not source identity and never feed\n // generated names; only the canonical origin/path and docs root participate.\n const repository = url.hostname.toLowerCase() === 'github.com'\n ? `https://github.com/${url.pathname.split('/').filter(Boolean).slice(0, 2).join('/').replace(/\\.git$/i, '').toLowerCase()}`\n : `${url.origin}${trimTrailingSlashes(url.pathname)}`\n return JSON.stringify([repository, relative(repositoryDir, siteRoot).replace(/\\\\/g, '/')])\n}\n\n/** Import an already-available repository directory into a canonical bundle. */\nexport function migrateRepository(options: RepositoryMigrationOptions): MigrationBundle {\n const repositoryDir = options.repositoryDir\n const platform = options.platform ?? detectRepositoryPlatform(repositoryDir, options.docsDir)\n const warnings: Array<MigrationWarning> = []\n const mintlifyProjectRoot = platform === 'mintlify'\n ? findMintlifyProjectRoot(repositoryDir, options.docsDir, warnings)\n : null\n const docusaurusProjectRoot = platform === 'docusaurus'\n ? findDocusaurusProjectRoot(repositoryDir, options.docsDir, warnings)\n : null\n const fernProjectRoot = platform === 'fern'\n ? findFernProjectRoot(repositoryDir, options.docsDir)\n : null\n const configuredDocsDir = (() => {\n if (options.docsDir !== undefined) {\n const selected = resolveWithin(repositoryDir, options.docsDir || '.')\n if (platform === 'docusaurus' && hasDocusaurusConfig(selected)) {\n const projectRelative = relative(repositoryDir, selected).replace(/\\\\/g, '/')\n return [projectRelative, primaryDocusaurusDocsDirectory(selected)].filter(Boolean).join('/')\n }\n return options.docsDir\n }\n if (docusaurusProjectRoot) {\n const projectRelative = relative(repositoryDir, docusaurusProjectRoot).replace(/\\\\/g, '/')\n return [projectRelative, primaryDocusaurusDocsDirectory(docusaurusProjectRoot)].filter(Boolean).join('/')\n }\n if (platform === 'mintlify' && mintlifyProjectRoot) {\n return relative(repositoryDir, mintlifyProjectRoot).replace(/\\\\/g, '/')\n }\n if (platform === 'fern' && fernProjectRoot) {\n return relative(repositoryDir, fernProjectRoot).replace(/\\\\/g, '/')\n }\n return platform === 'mintlify' ? '' : detectRepositoryDocsDir(repositoryDir)\n })()\n // A Docusaurus or Fern MDX page can import its own local components\n // (relative, or `@site/...` for Docusaurus) and bare npm packages the same\n // way a Mintlify page can; the same bounded component graph and\n // import-stripping logic applies to any source, rooted at whichever\n // project actually owns the pages. `@site/...` is Docusaurus' own alias\n // for its project root specifically (not the whole repository) and must\n // keep resolving there. A plain relative import (`../../components/X`),\n // though, is written relative to the *page*, which can live outside that\n // root in a monorepo where docs/ is a sibling of website/ (e.g. Redux) or\n // of a Fern project directory rather than nested under it — the\n // repository, not the narrower platform root, is the real confinement\n // boundary for those.\n const componentRoot = mintlifyProjectRoot ?? docusaurusProjectRoot ?? fernProjectRoot ?? repositoryDir\n const componentMigrator = platform === 'mintlify' || platform === 'docusaurus' || platform === 'fern'\n ? createComponentMigrator(componentRoot, repositoryDir, warnings, componentSourceIdentity(options.sourceUrl, repositoryDir, componentRoot))\n : undefined\n let docsConfig: MigrationDocsConfig = { tabs: [] }\n // Literal leading path segments (e.g. \"v1.15.22\") that identify a\n // Mintlify `versions` container's default version — see\n // `mintlifyDefaultVersionPrefixes`.\n let defaultVersionPrefixes: ReadonlySet<string> = new Set()\n // Every version identifier declared in the config (default and\n // non-default) — used only to name which versions' pages were dropped if\n // discovery exceeds MAX_SOURCE_FILES; see `selectFilesWithinBudget`.\n let allVersionPrefixes: ReadonlySet<string> = new Set()\n const referenceMap = new Map<string, { navigationId: string; locale?: string }>()\n const exactReferenceMap = new Map<string, { navigationId: string; locale?: string }>()\n const referenceOrder = new Map<string, number>()\n let docusaurusSidebars: DocusaurusSidebars | null = null\n let mintlifyConfig: Record<string, unknown> | null = null\n let fernRawConfig: Record<string, unknown> | null = null\n let fernBasePath = ''\n let fernVersionPath = ''\n let fernApiSections: Array<FernApiSection> = []\n // sourcePaths of Fern descriptors that resolve outside fern/ (from a\n // `versions:` file living in a sibling directory) — resolved directly,\n // below, since the ordinary fern/-rooted scan can't reach them.\n const fernExternalSourcePaths = new Set<string>()\n let fernChangelogIndexes: Array<{ route: string; entries: Array<string> }> = []\n const fernReferencedPaths = new Set<string>()\n const fernSourceLinkAliases = new Map<string, string>()\n const fernNavTitles = new Map<string, string>()\n const fernHiddenIds = new Set<string>()\n\n if (platform === 'mintlify') {\n try {\n const config = readMintlifyConfig(mintlifyProjectRoot ?? repositoryDir)\n if (config) {\n mintlifyConfig = config\n defaultVersionPrefixes = mintlifyDefaultVersionPrefixes(config)\n allVersionPrefixes = mintlifyAllVersionPrefixes(config)\n const projected = projectMintlifyNavigation(config)\n docsConfig = projected.docsConfig\n warnings.push(...projected.warnings)\n for (const [index, reference] of projected.pageReferences.entries()) {\n const key = normalizedReferenceKey(reference.ref)\n // Shared source pages may appear in several language menus. The\n // projector visits the default language first; retain that primary\n // file so other locales can use the runtime's content fallback.\n if (!referenceMap.has(key)) referenceMap.set(key, reference)\n const exactKey = exactReferenceKey(reference.ref)\n if (!exactReferenceMap.has(exactKey)) exactReferenceMap.set(exactKey, reference)\n if (!referenceOrder.has(key)) referenceOrder.set(key, index)\n }\n }\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Mintlify config could not be read: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n\n if (platform === 'fern' && fernProjectRoot) {\n try {\n const fernConfig = readFernConfig(fernProjectRoot)\n if (fernConfig) {\n fernRawConfig = fernConfig.config\n fernBasePath = fernSourceBasePath(fernConfig.config)\n fernVersionPath = fernDefaultVersionPath(fernConfig.config)\n const projected = projectFernNavigation({ config: fernConfig.config, fernRoot: fernProjectRoot, repositoryRoot: repositoryDir })\n docsConfig = projected.docsConfig\n warnings.push(...projected.warnings)\n fernApiSections = projected.apiSections\n fernChangelogIndexes = projected.changelogIndexes\n for (const [index, descriptor] of projected.descriptors.entries()) {\n fernReferencedPaths.add(descriptor.sourcePath)\n if (descriptor.navTitle && !fernNavTitles.has(descriptor.navigationId)) {\n fernNavTitles.set(descriptor.navigationId, descriptor.navTitle)\n }\n if (descriptor.hidden) fernHiddenIds.add(descriptor.navigationId)\n // Fern pages often link by their source directory while a section\n // title changes the published route (for example tts-vendors to\n // tts-vendor-settings). Resolve only unambiguous, tab-prefixed\n // source paths rather than guessing at arbitrary root links.\n const sourceTail = descriptor.sourcePath.match(/(?:^|\\/)pages\\/(.+)\\.mdx?$/i)?.[1]?.replace(/\\/index$/i, '')\n if (sourceTail) {\n const routeSegments = descriptor.navigationId.split('/')\n const sourceSegments = sourceTail.split('/')\n if (routeSegments.length === sourceSegments.length + 1) {\n const alias = `${routeSegments[0]}/${sourceTail}`\n if (alias !== descriptor.navigationId && !fernSourceLinkAliases.has(alias)) fernSourceLinkAliases.set(alias, descriptor.navigationId)\n }\n }\n const key = normalizedReferenceKey(descriptor.sourcePath)\n if (!referenceMap.has(key)) referenceMap.set(key, { navigationId: descriptor.navigationId })\n const exactKey = exactReferenceKey(descriptor.sourcePath)\n if (!exactReferenceMap.has(exactKey)) exactReferenceMap.set(exactKey, { navigationId: descriptor.navigationId })\n if (!referenceOrder.has(key)) referenceOrder.set(key, index)\n if (descriptor.sourcePath.startsWith('../')) fernExternalSourcePaths.add(descriptor.sourcePath)\n }\n }\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Fern config could not be read: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n\n if (platform === 'docusaurus') {\n try {\n docusaurusSidebars = options.docusaurusSkipSidebar || !docusaurusProjectRoot\n ? null\n : readDocusaurusSidebars(docusaurusProjectRoot, options.docusaurusSidebarPath)\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Docusaurus sidebar could not be read safely: ${error instanceof Error ? error.message : String(error)} Generated navigation will be used.`,\n })\n }\n }\n\n const contentRoot = resolveWithin(repositoryDir, configuredDocsDir)\n if (!existsSync(contentRoot) || !lstatSync(contentRoot).isDirectory()) {\n throw new Error(`Documentation directory does not exist: ${configuredDocsDir || '.'}`)\n }\n const mintignoreMatcher = platform === 'mintlify' && mintlifyProjectRoot\n ? readMintignoreMatcher(mintlifyProjectRoot)\n : null\n // Referenced files (found in the navigation config) are ranked ahead of\n // unreferenced ones, in navigation traversal order — which already puts a\n // Mintlify default version's pages before non-default versions' (and\n // newer non-default versions before older ones); see\n // `selectFilesWithinBudget`. Only meaningful when a nav was actually\n // parsed (Mintlify/Fern); Docusaurus has no pre-scan reference set.\n //\n // An *unreferenced* page (a real file Mintlify still serves by its own\n // file-based routing even though no sidebar entry points at it, e.g.\n // crewAI's `tools/web-scraping/firecrawlsearchtool.mdx`) used to get the\n // exact same flat lowest priority regardless of which version it belonged\n // to. Ranking it just after a single *global* floor (every referenced\n // page, from every version) isn't enough to fix that: a repository whose\n // total *referenced*-page count alone already exceeds the budget (e.g.\n // crewAI's ~40 versions x ~180 pages each) would still starve every\n // orphan, including the default version's own, since literally every\n // referenced page from every version would still outrank it. Instead,\n // each orphan is ranked right after the *last* referenced page found\n // under its own version+locale block — traversal is contiguous per\n // (language, version) pair (a whole version's pages, referenced and its\n // own orphans together, are visited before the next version starts, and\n // a whole language's versions before the next language's) — so grouping\n // by version alone (dropping the locale segment) would still pool an\n // English orphan's ceiling together with, say, Arabic's or Korean's much\n // later-traversed pages under the same version identifier. Keying by the\n // first two path segments (version, then locale) — rather than requiring\n // an exact match against `allVersionPrefixes` (the `version:` label\n // declared in config) — also keeps this working even when a version's\n // declared label and its actual directory prefix disagree in spelling or\n // case (e.g. crewAI's own `\"version\": \"Edge\"` label for its lowercase\n // `edge/` directory): what matters for contiguity is purely the directory\n // structure real pages were discovered under, not the label text. A\n // version's orphans land immediately behind that same version+locale's\n // own referenced pages, never behind another locale's or version's.\n const lastReferencedIndexByVersionLocale = new Map<string, number>()\n for (const [key, index] of referenceOrder) {\n const blockKey = key.split('/').slice(0, 2).join('/')\n const current = lastReferencedIndexByVersionLocale.get(blockKey)\n if (current === undefined || index > current) lastReferencedIndexByVersionLocale.set(blockKey, index)\n }\n const discoveryRank = referenceOrder.size > 0\n ? (relativePath: string): number => {\n const referencedIndex = referenceOrder.get(normalizedReferenceKey(relativePath))\n if (referencedIndex !== undefined) return referencedIndex\n const blockKey = relativePath.split('/').slice(0, 2).join('/')\n const versionCeiling = lastReferencedIndexByVersionLocale.get(blockKey)\n return versionCeiling !== undefined ? versionCeiling + 1 : Number.MAX_SAFE_INTEGER\n }\n : undefined\n const scannedFiles = scanFiles(contentRoot, repositoryDir, warnings, discoveryRank)\n const mintignoreFilteredFiles = mintignoreMatcher\n ? scannedFiles.filter((file) => !mintignoreMatcher.ignores(file.relativePath))\n : scannedFiles\n const discoveryBudgetApplied = discoveryRank !== undefined && mintignoreFilteredFiles.length > MAX_SOURCE_FILES\n const files = discoveryRank\n ? selectFilesWithinBudget(mintignoreFilteredFiles, discoveryRank, warnings, allVersionPrefixes)\n : mintignoreFilteredFiles\n // A Fern `versions:` file may live outside fern/ (a sibling `docs/`\n // directory) and its own pages resolve relative to it, so their\n // sourcePath (e.g. `../docs/pages/x.mdx`) falls outside the fern/-rooted\n // scan above. Resolve exactly those referenced files directly, rather\n // than rescanning the whole repository (which would also shift every\n // asset's firstSegment and break the fern/-relative asset-bucket\n // detection below).\n if (platform === 'fern' && fernProjectRoot) {\n const discovered = new Set(files.map((file) => file.relativePath))\n for (const sourcePath of fernExternalSourcePaths) {\n if (discovered.has(sourcePath)) continue\n try {\n const absolutePath = resolveWithinRoot(fernProjectRoot, sourcePath, repositoryDir)\n if (existsSync(absolutePath) && lstatSync(absolutePath).isFile()) {\n files.push({ absolutePath, relativePath: sourcePath })\n discovered.add(sourcePath)\n } else {\n warnings.push({ code: 'missing-page', message: 'A Fern navigation path could not be read within this repository.', source: sourcePath })\n }\n } catch {\n warnings.push({ code: 'missing-page', message: 'A Fern navigation path could not be read within this repository.', source: sourcePath })\n }\n }\n }\n const pages: Array<MigrationPage> = []\n const assets: Array<MigrationAsset> = []\n const remoteApiSpecs: Array<{ url: string; tabLabel?: string }> = []\n // Which pages reference which asset (by its normalized copy-destination\n // path), so the final asset-copy pass can prioritize referenced assets\n // over unreferenced ones when the budget is tight, and name the\n // referencing pages in the warning if one still gets dropped.\n const referencedAssetPaths = new Map<string, Set<string>>()\n const addAssetReference = (assetPath: string, referencingPage: string): void => {\n const referrers = referencedAssetPaths.get(assetPath)\n if (referrers) referrers.add(referencingPage)\n else referencedAssetPaths.set(assetPath, new Set([referencingPage]))\n }\n const docusaurusDescriptors: Array<DocusaurusPageDescriptor> = []\n const docusaurusDocCardRoutes = new Set<string>()\n const seenPageIds = new Set<string>()\n /** docs.yml-derived navigationId -> final id, when a page's frontmatter `slug` overrides it. */\n const fernIdRenames = new Map<string, string>()\n let skipped = 0\n let discovered = files.length\n\n const localeConfig = docsConfig.i18n\n const defaultPageIds = new Set([...referenceMap.values()]\n .filter((reference) => !reference.locale || reference.locale === localeConfig?.defaultLocale)\n .map((reference) => reference.navigationId))\n const routeAliases: NonNullable<MigrationDocsConfig['redirects']> = []\n const pageFiles = [...files].sort((left, right) => {\n const leftOrder = referenceOrder.get(normalizedReferenceKey(left.relativePath)) ?? Number.MAX_SAFE_INTEGER\n const rightOrder = referenceOrder.get(normalizedReferenceKey(right.relativePath)) ?? Number.MAX_SAFE_INTEGER\n return leftOrder - rightOrder || left.relativePath.localeCompare(right.relativePath)\n })\n const snippetAliases = platform === 'mintlify' && mintlifyProjectRoot\n ? globalSnippetAliases(files, repositoryDir, mintlifyProjectRoot)\n : new Map<string, string>()\n for (const file of pageFiles) {\n if (!isDocumentationExtension(file.relativePath)) continue\n // Unlike Mintlify/Docusaurus, Fern only ever serves pages reachable from\n // docs.yml (or a versions file); everything else is invisible on the\n // live site, so importing it as an \"orphan\" page would fabricate content\n // (and can crash a build on stray files that were never meant to render).\n if (platform === 'fern'\n && !exactReferenceMap.has(exactReferenceKey(file.relativePath))\n && !referenceMap.has(normalizedReferenceKey(file.relativePath))) {\n skipped++\n continue\n }\n const sourceSegments = file.relativePath.split('/')\n if (sourceSegments.some((segment) => SNIPPET_DIRECTORIES.has(segment.toLowerCase()))\n || (platform === 'docusaurus' && basename(file.relativePath).startsWith('_'))) {\n skipped++\n continue\n }\n const rootFilename = !file.relativePath.includes('/') ? basename(file.relativePath).toLowerCase() : ''\n if (REPOSITORY_ONLY_DOCUMENTS.has(rootFilename) && !exactReferenceMap.has(exactReferenceKey(file.relativePath))) {\n skipped++\n continue\n }\n if (!['.md', '.mdx'].includes(extname(file.relativePath).toLowerCase())) {\n skipped++\n warnings.push({ code: 'skipped-file', message: 'Only Markdown and MDX are imported without an explicit converter.', source: file.relativePath })\n continue\n }\n const size = lstatSync(file.absolutePath).size\n if (size > MAX_PAGE_BYTES) {\n skipped++\n warnings.push({ code: 'skipped-file', message: 'Page exceeded the 2 MB repository import limit.', source: file.relativePath })\n continue\n }\n const key = normalizedReferenceKey(file.relativePath)\n const referenced = exactReferenceMap.get(exactReferenceKey(file.relativePath)) ?? referenceMap.get(key)\n let locale = referenced?.locale\n let navigationId = referenced?.navigationId ?? pageIdFromReference(file.relativePath, platform === 'mintlify')\n if (!referenced && localeConfig) {\n for (const entry of localeConfig.locales) {\n const localized = mintlifyLocalizedReference(file.relativePath, entry.code, defaultPageIds)\n if (localized === file.relativePath) continue\n locale = entry.code\n navigationId = pageIdFromReference(localized, platform === 'mintlify')\n break\n }\n }\n if (!navigationId) {\n skipped++\n warnings.push({ code: 'invalid-page', message: 'Page path could not be normalized safely.', source: file.relativePath })\n continue\n }\n const isDefaultLocale = !locale || locale === localeConfig?.defaultLocale\n const id = isDefaultLocale ? navigationId : `${locale}/${navigationId}`\n let raw = inlineMdxSnippets(\n readFileSync(file.absolutePath, 'utf8'),\n file.absolutePath,\n repositoryDir,\n warnings,\n 0,\n mintlifyProjectRoot ?? docusaurusProjectRoot ?? fernProjectRoot ?? repositoryDir,\n snippetAliases,\n )\n if (platform === 'fern' || platform === 'mintlify' || platform === 'docusaurus') {\n // A heading's `{#custom-id}` anchor (`## Title {#custom-id}`) crashes\n // `@mdx-js/mdx`'s parser outright, so it must be converted to a\n // preceding `<a id=\"custom-id\"></a>` (see `normalizeExplicitHeadingIds`)\n // before ANY MDX parse of this page is attempted — including\n // `componentMigrator.transform` below, whose own early parse would\n // otherwise choke on it and skip the page's import analysis entirely.\n raw = normalizeExplicitHeadingIds(raw)\n }\n if (componentMigrator) {\n const warningsBeforeTransform = warnings.length\n raw = componentMigrator.transform(raw, file.absolutePath)\n // `transform` excludes a page itself (pushing a 'skipped-file' warning\n // for it) when it references an unsupported npm import outside JSX —\n // keeping that import would fail `next build` for the whole site. Skip\n // building this page too; `pruneMissingNavigationPages` below drops it\n // from navigation since it never joins `pages`.\n // `warning.source` is relative to `componentRoot`, which can differ\n // from `repositoryDir` (a nested Mintlify/Docusaurus project root);\n // compare absolute paths rather than the two relative forms directly.\n if (warnings.slice(warningsBeforeTransform).some((warning) => warning.code === 'skipped-file' && warning.source !== undefined\n && resolvePath(componentRoot, warning.source) === file.absolutePath)) {\n skipped++\n continue\n }\n }\n // A bare `{word}` in prose (e.g. Infisical's STYLE_GUIDE.md `{x}`) is\n // literal text on Mintlify and Docusaurus too, not just Fern — MDX\n // always evaluates `{...}` as a JS expression, so any platform's source\n // can hit the same `ReferenceError` at render. `escapeFernLiteralBraces`\n // is platform-agnostic (it only reads the page's own AST/ESM scope), so\n // run it for every platform Thally migrates from.\n if (platform === 'fern' || platform === 'mintlify' || platform === 'docusaurus') {\n // Math must be protected before the AST-based brace escaper runs:\n // `$$\\begin{align*}...\\end{align*}$$` crashes that parser outright\n // (see `protectMathBlocks`), which is what excluded these pages\n // before this ran. The heading-custom-id case that used to be\n // handled at this same point is now converted earlier, above, before\n // `componentMigrator.transform` gets a chance to choke on it too.\n const protectedMath = protectMathBlocks(raw)\n if (protectedMath.converted) {\n warnings.push({\n code: 'unsupported-config',\n message: \"Math (KaTeX '$$...$$') has no renderer in Thally yet; it was kept as a fenced code block instead of being dropped.\",\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n } else if (protectedMath.guardTriggered) {\n warnings.push({\n code: 'unsupported-config',\n message: 'A suspected math span looked like it needed converting, but doing so broke the page; the page was kept as originally authored instead.',\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n }\n raw = escapeFernLiteralBraces(protectedMath.body)\n }\n const hasDocusaurusDocCardList = platform === 'docusaurus' && /<DocCardList\\b[^>]*\\/>/.test(raw)\n if (hasDocusaurusDocCardList) {\n // A plain HTML placeholder survives the generic MDX normalizer while\n // retaining the card list's exact position relative to surrounding prose.\n raw = raw.replace(/<DocCardList\\b[^>]*\\/>/g, '<div data-thally-doc-card-list=\"\" />')\n }\n let docusaurusDescriptor: Omit<DocusaurusPageDescriptor, 'title'> | undefined\n const page = parseMarkdownPage({\n id,\n navigationId,\n ...(locale ? { locale } : {}),\n raw,\n platform,\n source: `${options.sourceUrl}#${relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/')}`,\n ...(platform === 'docusaurus' ? {\n resolveIdentity: (frontmatter, fallback) => {\n const resolved = resolveDocusaurusPageIdentity(file.relativePath, frontmatter, fallback)\n const routePrefix = options.docusaurusRoutePrefix === undefined\n ? undefined\n : trimEdgeSlashes(options.docusaurusRoutePrefix)\n if (!routePrefix) {\n docusaurusDescriptor = resolved.descriptor\n return resolved.identity\n }\n const prefixedNavigationId = resolved.identity.navigationId === 'introduction'\n ? routePrefix\n : `${routePrefix}/${resolved.identity.navigationId}`\n const prefixedStorageId = resolved.identity.id === 'introduction'\n ? routePrefix\n : `${routePrefix}/${resolved.identity.id}`\n docusaurusDescriptor = {\n ...resolved.descriptor,\n navigationId: prefixedNavigationId,\n }\n return {\n ...resolved.identity,\n id: prefixedStorageId,\n navigationId: prefixedNavigationId,\n }\n },\n } : {}),\n // A Fern page's own frontmatter `slug` replaces its whole section/folder\n // hierarchy (never just its own segment) and wins over a docs.yml slug.\n ...(platform === 'fern' ? {\n resolveIdentity: (frontmatter, fallback) => {\n const slug = typeof frontmatter.slug === 'string' ? frontmatter.slug.trim() : ''\n if (!slug) return fallback\n const overridden = pageIdFromReference(slug, true)\n if (!overridden) return fallback\n fernIdRenames.set(fallback.navigationId, overridden)\n return { ...fallback, id: overridden, navigationId: overridden }\n },\n } : {}),\n })\n if (!page) {\n skipped++\n continue\n }\n if (page.frontmatterError) {\n warnings.push({\n code: 'unsupported-config',\n message: `The page's frontmatter is not valid YAML (${page.frontmatterError}); the page was kept and as much of its metadata as could be read was used.`,\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n }\n if (platform === 'fern' && !page.navTitle) {\n const navTitle = fernNavTitles.get(navigationId)\n if (navTitle && navTitle !== page.title) page.navTitle = navTitle\n }\n if (platform === 'fern' && fernHiddenIds.has(navigationId)) page.hidden = true\n if (platform === 'mintlify' && mintlifyProjectRoot) {\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, mintlifyProjectRoot, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n }\n if (platform === 'fern' && fernProjectRoot) {\n // Fern can keep docs in a sibling `docs/` directory beside `fern/`.\n // The checkout, not the config directory, is the safe asset boundary.\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, fernProjectRoot, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, repositoryDir, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n page.body = stripFernBasePathFromLinks(page.body, fernBasePath)\n page.body = stripFernBasePathFromLinks(page.body, fernVersionPath)\n }\n if (platform === 'mintlify' || platform === 'docusaurus' || platform === 'fern') {\n // `<Link href=\"...\">` (common Mintlify/Docusaurus prose, e.g. mem0's\n // docs) has no Thally builtin; map it to a plain anchor before the\n // generic unknown-component fallback runs, so a real navigable link\n // survives instead of becoming a `<div>`. Runs on the fully normalized\n // body (after `parseMarkdownPage`'s `normalizeMdx`), so a tag that a\n // platform-specific rename still resolves (Docusaurus `TabItem` ->\n // `Tab`, Mintlify `Warn` -> `Warning`, ...) is never mistaken for\n // unknown. Fern-native components with no Thally equivalent\n // (`Markdown`, `Button`, `Download`, ...) fall into the same generic\n // path below — there is no separate Fern-specific detector, so each\n // unknown tag gets exactly one warning.\n page.body = replaceLinkWithAnchor(page.body)\n // Anything still capitalized and unresolved at this point (not a\n // Thally builtin, not declared/imported by the page, not already\n // handled by componentMigrator's copy/removal above) would otherwise\n // throw \"Expected component X to be defined\" at render. Warn once per\n // component name and neutralize it: keep a paired tag's children,\n // drop a self-closing one outright.\n page.body = replaceUnknownComponents(page.body, (name) => {\n warnings.push({\n code: 'unsupported-config',\n message: `Component <${name}> has no equivalent in Thally and wasn't found on this page; it was replaced with a plain <div> (or removed, if self-closing) so the page still builds. Add a matching component or edit the page.`,\n source: file.relativePath,\n })\n })\n }\n const mdxError = invalidMdxReason(page.body)\n if (mdxError) {\n skipped++\n warnings.push({\n code: 'skipped-file',\n message: `Page was excluded because it does not compile as MDX: ${mdxError}`,\n source: file.relativePath,\n })\n continue\n }\n // `hasAnyFunctionValuedProp` only proves a function value (a reference to\n // a page-declared function, or a function written inline) is passed as\n // *some* JSX prop; it does not know which tag receives it. A prop\n // landing on a component this migration actually extracted as\n // 'use client' (`Migrated<hash>`/`Inline<n>`) or on a Thally runtime\n // built-in already backed by a 'use client' module (`Accordion`, `Panel`,\n // `Tabs`, ... — see `CLIENT_BUILTIN_COMPONENT_TAGS` in components.ts) is\n // confirmed to cross the server/client boundary and throw at render — a\n // prop on any other tag (an unregistered/removed component) is not\n // confirmed either way, so exclusion (a last resort) is reserved for the\n // confirmed case; the unconfirmed case is warned instead, so it is never\n // silently dropped or silently shipped broken.\n const declaredNames = functionDeclaredNames(page.body)\n if (hasAnyFunctionValuedProp(page.body, declaredNames)) {\n if (propsTargetExtractedClientComponent(page.body, declaredNames)) {\n skipped++\n warnings.push({\n code: 'skipped-file',\n message: \"This page passes a function to an interactive component, which can't be rendered on the server. \"\n + 'Move the function into the component or edit the page manually.',\n source: file.relativePath,\n })\n continue\n }\n warnings.push({\n code: 'unsupported-config',\n message: \"This page might pass a function to an interactive component, which can't be rendered on the \"\n + 'server; review it manually if the built page fails to render.',\n source: file.relativePath,\n })\n }\n if (declarationsReferenceBrowserGlobal(page.body)) {\n warnings.push({\n code: 'unsupported-config',\n message: \"This page defines a component that uses `document`/`window`, which isn't available when pages \"\n + 'are rendered on the server. Move that code into a client component or edit the page manually.',\n source: file.relativePath,\n })\n }\n if (seenPageIds.has(page.id)) {\n skipped++\n warnings.push({ code: 'collision', message: `Multiple source files map to ${page.id}; the first file was kept.`, source: file.relativePath })\n continue\n }\n seenPageIds.add(page.id)\n pages.push(page)\n // MDX normalization removes DocCardList because Thally has no matching\n // component. Remember its authored route so the resolved sidebar can\n // supply the cards once every page and category has been discovered.\n if (hasDocusaurusDocCardList) {\n docusaurusDocCardRoutes.add(page.navigationId)\n }\n if (platform === 'mintlify') {\n const sourcePath = exactReferenceKey(file.relativePath)\n // Only literal portable paths become Next redirects: source filenames\n // must never introduce route patterns such as `:param` or wildcards.\n if (sourcePath !== page.id && /^[A-Za-z0-9_./-]+$/.test(sourcePath)) {\n routeAliases.push({ source: `/${sourcePath}`, destination: `/${page.id}`, permanent: false })\n }\n // The default version's own pages are also linked without the\n // version segment (the live Mintlify site 307s such a link to the\n // versioned page) — add the matching alias so those in-repo links\n // resolve instead of dead-ending. See `mintlifyDefaultVersionPrefixes`.\n const versionPrefix = [...defaultVersionPrefixes].find((prefix) => sourcePath === prefix || sourcePath.startsWith(`${prefix}/`))\n if (versionPrefix) {\n const unversioned = sourcePath.slice(versionPrefix.length).replace(/^\\/+/, '')\n if (unversioned && unversioned !== sourcePath && unversioned !== page.id\n && /^[A-Za-z0-9_./-]+$/.test(unversioned)\n && !routeAliases.some((redirect) => redirect.source === `/${unversioned}`)) {\n routeAliases.push({ source: `/${unversioned}`, destination: `/${page.id}`, permanent: false })\n }\n }\n }\n if (docusaurusDescriptor) {\n docusaurusDescriptors.push({ ...docusaurusDescriptor, title: page.title })\n }\n }\n\n const discoveredReferenceKeys = new Set(files.map((file) => normalizedReferenceKey(file.relativePath)))\n for (const [key] of referenceMap) {\n if (!discoveredReferenceKeys.has(key)) {\n warnings.push({ code: 'missing-page', message: 'A navigation entry did not resolve to a source page.', source: key })\n }\n }\n\n const docusaurusAssetRoot = docusaurusProjectRoot ?? repositoryDir\n const fernBrandAssetPaths = new Map<string, string>()\n const fernReferencedAssets: Array<ScannedFile> = []\n if (platform === 'fern' && fernProjectRoot) {\n const seen = new Set<string>()\n const addFernAsset = (candidate: string, source?: string): void => {\n try {\n const absolutePath = source\n ? resolveWithinRoot(fernProjectRoot, source.replace(/^\\/+/, ''), repositoryDir)\n : resolveWithin(repositoryDir, candidate)\n if (!existsSync(absolutePath) || !lstatSync(absolutePath).isFile()) return\n const realRoot = realpathSync(repositoryDir)\n const realPath = realpathSync(absolutePath)\n const confined = relative(realRoot, realPath)\n if (confined === '..' || confined.startsWith(`..${sep}`) || isAbsolute(confined)) return\n const withinFern = relative(fernProjectRoot, absolutePath)\n const assetRelative = withinFern !== '..' && !withinFern.startsWith(`..${sep}`) && !isAbsolute(withinFern)\n ? withinFern\n : relative(repositoryDir, absolutePath)\n const assetPath = normalizeAssetPath(assetRelative.replace(/\\\\/g, '/'))\n if (!assetPath || !ASSET_EXTENSIONS.has(extname(assetPath).toLowerCase())) return\n if (source) {\n fernBrandAssetPaths.set(source, assetPath)\n addAssetReference(assetPath, 'fern/docs.yml')\n }\n if (seen.has(absolutePath)) return\n seen.add(absolutePath)\n fernReferencedAssets.push({ absolutePath, relativePath: assetPath })\n } catch {\n // The existing missing-asset warning names any unresolved brand path.\n }\n }\n for (const path of referencedAssetPaths.keys()) addFernAsset(path)\n for (const value of [fernRawConfig?.logo, fernRawConfig?.favicon]) {\n if (typeof value === 'string') addFernAsset('', value)\n else if (value && typeof value === 'object' && !Array.isArray(value)) {\n const variants = value as Record<string, unknown>\n for (const candidate of [variants.light, variants.dark, variants.src, variants.srcDark]) {\n if (typeof candidate === 'string') addFernAsset('', candidate)\n }\n }\n }\n }\n const repositoryAssets = platform === 'docusaurus' && configuredDocsDir && !options.docusaurusSkipAssets\n ? ['static', 'public'].flatMap((directory) => {\n const root = resolveWithin(docusaurusAssetRoot, directory)\n if (!existsSync(root) || !lstatSync(root).isDirectory()) return []\n return scanFiles(root, repositoryDir).map((file) => ({\n ...file,\n relativePath: `${directory}/${file.relativePath}`,\n }))\n })\n : []\n interface AssetCandidate { file: ScannedFile; assetPath: string; size: number }\n const assetCandidates: Array<AssetCandidate> = []\n for (const file of [...files, ...repositoryAssets, ...fernReferencedAssets]) {\n const firstSegment = file.relativePath.split('/', 1)[0].toLowerCase()\n if (!ASSET_EXTENSIONS.has(extname(file.relativePath).toLowerCase())) continue\n if (platform !== 'mintlify' && !ASSET_DIRECTORIES.has(firstSegment)\n && !(platform === 'fern' && referencedAssetPaths.has(file.relativePath))) continue\n const isDocusaurusStatic = platform === 'docusaurus' && firstSegment === 'static'\n const assetPath = normalizeAssetPath(firstSegment === 'public'\n ? file.relativePath.slice('public/'.length)\n : isDocusaurusStatic\n ? file.relativePath.slice('static/'.length)\n : file.relativePath)\n if (!assetPath) continue\n assetCandidates.push({ file, assetPath, size: lstatSync(file.absolutePath).size })\n }\n // Copy assets that pages actually reference before unreferenced ones, so a\n // tight budget drops decorative/unused files first instead of screenshots\n // a page links to (each group keeps its original scan order).\n const isReferenced = (candidate: AssetCandidate): boolean => referencedAssetPaths.has(candidate.assetPath)\n const orderedAssetCandidates = [\n ...assetCandidates.filter((candidate) => isReferenced(candidate)),\n ...assetCandidates.filter((candidate) => !isReferenced(candidate)),\n ]\n let totalAssetBytes = 0\n for (const { file, assetPath, size } of orderedAssetCandidates) {\n if (size > MAX_ASSET_BYTES || totalAssetBytes + size > MAX_TOTAL_ASSET_BYTES) {\n const referencingPages = referencedAssetPaths.get(assetPath)\n warnings.push({\n code: 'limit-reached',\n message: 'This file was not copied because it is larger than 25 MB or the copied files would exceed 500 MB in total. Add it to public/ manually'\n + (referencingPages\n ? `; it is used by ${[...referencingPages].slice(0, 3).join(', ')}${referencingPages.size > 3 ? `, and ${referencingPages.size - 3} more` : ''}.`\n : '.'),\n source: file.relativePath,\n })\n continue\n }\n const content = readFileSync(file.absolutePath)\n if (isGitLfsPointer(content)) {\n warnings.push({\n code: 'unsupported-config',\n message: 'This asset is a Git LFS pointer, not its real content (Git LFS was skipped during clone because the host has no git-lfs binary). Install git-lfs and re-run the migration, or add the real file to public/ manually.',\n source: file.relativePath,\n })\n continue\n }\n assets.push({ path: assetPath, content })\n totalAssetBytes += size\n }\n\n // `selectFilesWithinBudget` already emitted a detailed warning (dropped\n // count + versions) when it ran; this generic fallback only covers the\n // case it couldn't run (no `discoveryRank`, e.g. Docusaurus) or the rare\n // case where later additions (Fern's external sourcePaths, above) pushed\n // the count back over budget after the event.\n if (!discoveryBudgetApplied && files.length >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Stopped scanning after ${MAX_SOURCE_FILES} files, so the rest of the repository was not looked at. Run the migration on a smaller part of the repository with --docs-dir.` })\n }\n if (platform === 'docusaurus') {\n const projected = projectDocusaurusNavigation({\n sidebars: docusaurusSidebars,\n descriptors: docusaurusDescriptors,\n contentRoot,\n sourceUrl: options.sourceUrl,\n routePrefix: options.docusaurusRoutePrefix,\n })\n docsConfig = projected.docsConfig\n expandDocusaurusDocCardLists(pages, docsConfig, docusaurusDocCardRoutes)\n warnings.push(...projected.warnings)\n for (const page of projected.generatedPages) {\n if (seenPageIds.has(page.id)) continue\n seenPageIds.add(page.id)\n pages.push(page)\n }\n const descriptorByNavigationId = new Map(\n docusaurusDescriptors.map((descriptor) => [descriptor.navigationId, descriptor]),\n )\n const sourceOrigin = docusaurusProjectRoot ? readDocusaurusSiteOrigin(docusaurusProjectRoot) : undefined\n const externalizedLinks = new Set<string>()\n for (const page of pages) {\n const descriptor = descriptorByNavigationId.get(page.navigationId)\n if (descriptor) page.body = rewriteDocusaurusLinks(page.body, descriptor, docusaurusDescriptors, {\n sourceOrigin,\n onExternalLink: (target) => externalizedLinks.add(target),\n assetPaths: new Set(assets.map((asset) => asset.path)),\n })\n }\n if (externalizedLinks.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalizedLinks.size} link(s) outside the imported Docusaurus docs still point to ${sourceOrigin}; migrate those sections separately if this site must be fully independent.`,\n })\n if (docusaurusProjectRoot && !options.docusaurusSkipRedirects) {\n const redirects = readDocusaurusRedirects(docusaurusProjectRoot, warnings)\n if (redirects.length > 0) docsConfig = { ...docsConfig, redirects: [...(docsConfig.redirects ?? []), ...redirects] }\n }\n }\n if (platform === 'fern' && fernIdRenames.size > 0) {\n const renamedRoute = (route: string): string => {\n const renamed = fernIdRenames.get(route.replace(/^\\//, ''))\n return renamed ? `/${renamed}` : route\n }\n const renamePages = (nodes: Array<string | MigrationNavigationGroup>): Array<string | MigrationNavigationGroup> =>\n nodes.map((node) => typeof node === 'string'\n ? fernIdRenames.get(node) ?? node\n : { ...node, pages: renamePages(node.pages) })\n for (const page of pages) {\n page.body = rewriteFernIdRenameLinks(page.body, fernIdRenames)\n }\n docsConfig = {\n ...docsConfig,\n tabs: docsConfig.tabs.map((tab) => ({\n ...tab,\n ...(tab.pages ? { pages: renamePages(tab.pages) } : {}),\n ...(tab.groups ? { groups: renamePages(tab.groups) as Array<MigrationNavigationGroup> } : {}),\n })),\n ...(docsConfig.redirects ? {\n redirects: docsConfig.redirects.map((redirect) => ({\n ...redirect,\n source: renamedRoute(redirect.source),\n destination: renamedRoute(redirect.destination),\n })),\n } : {}),\n }\n }\n if (platform === 'fern' && fernSourceLinkAliases.size > 0) {\n const imported = new Set(pages.map((page) => page.id))\n const aliases = new Map([...fernSourceLinkAliases]\n .map(([source, target]) => [source, fernIdRenames.get(target) ?? target] as const)\n .filter(([, target]) => imported.has(target)))\n for (const page of pages) page.body = rewriteFernIdRenameLinks(page.body, aliases)\n }\n if (docsConfig.tabs.length === 0) docsConfig = buildNavigationFromPages(pages)\n if (platform === 'fern' && fernProjectRoot) {\n // A repo-wide scan for *any* `openapi.yml`/`.json` file cannot tell one\n // API's spec from another's, so once an explicit `api-name` names a\n // specific API, that naive scan is never consulted as a fallback (the\n // root `generators.yml` rule is in `fernOpenApiCandidateDirs`). A docs.yml\n // with no `api:` node at all falls back to the naive scan, bound to\n // whatever tab `injectOpenApiSpecs` picks for an unbound spec.\n const sections: Array<{ name?: string; nameExplicit: boolean; tabLabel?: string; routeSegments?: Array<string> }> = fernApiSections.length > 0\n ? fernApiSections\n : [{ nameExplicit: false }]\n const resolvedSpecs: Array<{ filename: string; tabLabel?: string; content: Buffer; routeSegments: Array<string> }> = []\n // Two different multi-API specs commonly share a basename (Paradex's\n // prod_rest and testnet_rest both resolve to their own\n // apis/<name>/openapi/openapi.json) — track which absolute file a\n // filename already names so a second, genuinely different spec gets a\n // distinguishing prefix instead of silently reusing the first spec's\n // copied asset for both tabs.\n const specFilenameSources = new Map<string, string>()\n for (const section of sections) {\n const resolution = findFernConfiguredOpenApi(fernProjectRoot, repositoryDir, section.name, section.nameExplicit, warnings)\n const spec = resolution.spec ?? (!section.nameExplicit ? findOpenApi(files) : null)\n if (spec) {\n let filename = basename(spec.relativePath)\n const existingSource = specFilenameSources.get(filename)\n if (existingSource && existingSource !== spec.absolutePath) {\n const prefix = section.name ? `${section.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')}-` : `${specFilenameSources.size + 1}-`\n filename = `${prefix}${filename}`\n }\n specFilenameSources.set(filename, spec.absolutePath)\n const specContent = readFileSync(spec.absolutePath)\n if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: specContent })\n }\n resolvedSpecs.push({ filename, tabLabel: section.tabLabel, content: specContent, routeSegments: section.routeSegments ?? [] })\n continue\n }\n if (resolution.unsupported.length > 0) {\n const sectionLabel = section.name ? ` for the \"${section.name}\" API` : ''\n for (const entry of resolution.unsupported) {\n warnings.push({\n code: 'unsupported-config',\n message: `${entry.kind === 'asyncapi' ? 'AsyncAPI' : 'OpenRPC'} is not supported by Thally's API reference; the spec \"${entry.path}\"${sectionLabel} was not migrated.`,\n })\n }\n continue\n }\n if (section.name === undefined) continue\n if (fernDefinitionExists(fernProjectRoot, section.name)) {\n warnings.push({\n code: 'unsupported-config',\n message: `This API${section.name ? ` (\"${section.name}\")` : ''} is defined with a Fern Definition, not an OpenAPI/AsyncAPI document; generating a spec from a Fern Definition is not supported. Export an OpenAPI document and reference it from generators.yml, or add it manually.`,\n })\n continue\n }\n // Neither an OpenAPI/AsyncAPI spec nor a Fern Definition could be found\n // for this `api:` node — the API tab was silently dropped from the nav.\n // Name the node so the user knows which one to fix.\n const checked = fernOpenApiCandidateDirs(fernProjectRoot, section.name, section.nameExplicit)\n .map((dir) => relative(repositoryDir, resolvePath(dir, 'generators.yml')).replace(/\\\\/g, '/'))\n if (!section.nameExplicit) checked.push('any openapi or swagger file in the repository')\n warnings.push({\n code: 'unsupported-config',\n message: checked.length\n ? `No OpenAPI/AsyncAPI spec could be found for the \"${section.name}\" API. Checked: ${checked.join(', ')}. Point generators.yml at a spec file that exists.`\n : `No OpenAPI/AsyncAPI spec could be found for the \"${section.name}\" API, because its api-name is not a valid folder name. Add the spec manually.`,\n })\n }\n if (resolvedSpecs.length > 0) {\n docsConfig = injectOpenApiSpecs(docsConfig, resolvedSpecs, warnings)\n // Fern serves each api: section's auto-generated operation pages\n // under that section's own route (e.g. \"api-reference/messages/...\")\n // — the same shape Mintlify's `directory` scoping produces, so the\n // same rewrite applies, keyed by the section's route instead.\n const { operationLinks, prefixLandings } = apiOperationLinkMap(\n resolvedSpecs.map((spec) => ({ filename: spec.filename, content: spec.content, prefix: spec.routeSegments.join('/') })),\n docsConfig,\n )\n rewriteApiLinksInPages(pages, operationLinks, prefixLandings, warnings)\n }\n } else if (platform === 'mintlify') {\n const resolvedSpecs = resolveMintlifyApiSpecs(mintlifyConfig, files, warnings, remoteApiSpecs)\n for (const spec of resolvedSpecs) {\n if (!assets.some((asset) => asset.path === spec.filename)) {\n assets.push({ path: spec.filename, content: spec.content })\n }\n }\n if (resolvedSpecs.length > 0) {\n docsConfig = injectOpenApiSpecs(docsConfig, resolvedSpecs, warnings)\n const { operationLinks, prefixLandings } = apiOperationLinkMap(\n resolvedSpecs.map((spec) => ({ filename: spec.filename, content: spec.content, prefix: spec.directory })),\n docsConfig,\n )\n rewriteApiLinksInPages(pages, operationLinks, prefixLandings, warnings)\n } else {\n // No docs.json-configured spec at all: fall back to a naive repo scan,\n // matching every other platform's baseline behavior.\n const fallback = findOpenApi(files)\n if (fallback) {\n const filename = basename(fallback.relativePath)\n if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: readFileSync(fallback.absolutePath) })\n }\n docsConfig = injectOpenApiSpecs(docsConfig, [{ filename }])\n }\n }\n }\n if (platform === 'mintlify') {\n const sources = new Set((docsConfig.redirects ?? []).map((redirect) => redirect.source))\n const aliases = routeAliases.filter((redirect) => !sources.has(redirect.source))\n if (aliases.length > 0) docsConfig = { ...docsConfig, redirects: [...(docsConfig.redirects ?? []), ...aliases] }\n docsConfig = addMintlifyHomepageRedirects(addMintlifyDirectoryRedirects(docsConfig, pages), pages)\n // `index.mdx` pages often publish at their parent route while source\n // prose still links to `/docs/<locale>/section/index`. Route aliases are\n // known only after the page loop, so include them in this final rewrite.\n const reachablePaths = new Set([\n ...pages.map((page) => page.id),\n ...(docsConfig.redirects ?? []).map((redirect) => redirect.source.replace(/^\\//, '')),\n ])\n for (const page of pages) page.body = rewriteMintlifyMountedLinks(page.body, reachablePaths)\n }\n\n if (platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipPlugins) {\n const additionalRoots: Array<DocusaurusArchiveRoot> = [\n ...additionalDocusaurusPluginRoots(repositoryDir, docusaurusProjectRoot, warnings).map((plugin) => ({\n ...plugin,\n label: plugin.routePrefix.split(/[-_/]/).filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' '),\n })),\n ...docusaurusArchiveRoots(docusaurusProjectRoot, repositoryDir, warnings),\n ]\n for (const plugin of additionalRoots) {\n if (discovered >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Stopped importing Docusaurus docs plugins after ${MAX_SOURCE_FILES} files; the remaining plugin docs were not migrated.` })\n break\n }\n if (plugin.docsDir === configuredDocsDir) continue\n const pluginBundle = migrateRepository({\n ...options,\n docsDir: plugin.docsDir,\n platform: 'docusaurus',\n docusaurusRoutePrefix: plugin.routePrefix,\n docusaurusSkipPlugins: true,\n docusaurusSkipSidebar: !plugin.sidebarPath,\n docusaurusSidebarPath: plugin.sidebarPath,\n docusaurusSkipAssets: true,\n docusaurusSkipRedirects: true,\n })\n for (const page of pluginBundle.pages) {\n if (seenPageIds.has(page.id)) {\n skipped++\n warnings.push({ code: 'collision', message: `Docusaurus docs roots both map to ${page.id}; the first page was kept.`, source: page.source })\n continue\n }\n seenPageIds.add(page.id)\n pages.push(page)\n }\n const assetPaths = new Set(assets.map((asset) => asset.path))\n for (const asset of pluginBundle.assets) {\n if (assetPaths.has(asset.path)) continue\n assetPaths.add(asset.path)\n assets.push(asset)\n }\n const pluginLabel = plugin.label\n docsConfig.tabs.push(...pluginBundle.docsConfig.tabs.map((tab, index) => ({\n ...tab,\n tab: index === 0 ? pluginLabel : `${pluginLabel}: ${tab.tab}`,\n })))\n warnings.push(...pluginBundle.warnings)\n discovered += pluginBundle.stats.discovered\n skipped += pluginBundle.stats.skipped\n }\n }\n\n if (platform === 'docusaurus') {\n // Localized and archived docs are imported as separate roots, often with\n // asset copying disabled. Once all roots are merged, resolve their mounted\n // `/docs/...` references against the assets actually copied by the parent.\n const copiedAssets = new Set(assets.map((asset) => asset.path))\n for (const page of pages) {\n page.body = rewriteDocusaurusLinks(page.body, {\n sourcePath: page.source ?? page.navigationId,\n docId: page.navigationId,\n navigationId: page.navigationId,\n title: page.title,\n }, [], { assetPaths: copiedAssets })\n }\n const importedRoutes = new Set(pages.map((page) => page.navigationId))\n docsConfig.tabs = docsConfig.tabs.map((tab) => {\n if (tab.href) return tab\n const root = tab.tab.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-')\n if (!root || !importedRoutes.has(root)) return tab\n // Auto-generated Docusaurus sidebars can sort an `index.mdx` landing\n // page after alphabetic siblings. Keep the actual tab root as the\n // collection destination, and put it first when it is a direct child.\n return {\n ...tab,\n href: `/${root}`,\n ...(tab.pages ? { pages: tab.pages.map((node) => {\n if (typeof node === 'string') return node\n const index = node.pages.indexOf(root)\n return index > 0\n ? { ...node, pages: [root, ...node.pages.filter((page) => page !== root)] }\n : node\n }) } : {}),\n ...(tab.groups ? { groups: tab.groups.map((group) => {\n const index = group.pages.indexOf(root)\n return index > 0\n ? { ...group, pages: [root, ...group.pages.filter((page) => page !== root)] }\n : group\n }) } : {}),\n }\n })\n }\n\n // Pages skipped above (invalid MDX, a client-boundary function prop, an id\n // collision) never entered `pages`, but the nav was projected from the raw\n // source config and may still reference their ids. Drop those dangling\n // references so `thally check` never reports a nav entry with no MDX file.\n if (platform === 'fern') {\n const byId = new Map(pages.map((page) => [page.navigationId, page]))\n for (const changelog of fernChangelogIndexes) {\n let index = byId.get(changelog.route)\n const entries = changelog.entries\n .map((id) => byId.get(fernIdRenames.get(id) ?? id))\n .filter((page): page is MigrationPage => Boolean(page))\n .slice(0, 10)\n if (entries.length === 0) continue\n if (!index) {\n // A changelog directory may have no overview file at all. Fern still\n // publishes a feed at the tab route, so materialize that route before\n // pruning navigation entries which lack an imported source file.\n index = {\n id: changelog.route,\n navigationId: changelog.route,\n title: 'Release Notes',\n description: 'Latest release notes and product updates.',\n descriptionPlacement: 'body',\n keywords: [],\n body: '',\n source: entries[0].source,\n }\n pages.push(index)\n byId.set(index.navigationId, index)\n docsConfig.redirects = docsConfig.redirects?.filter((redirect) => redirect.source !== `/${changelog.route}`)\n }\n if (index.body.trim()) continue\n // Fern renders changelog directories as a dated feed at the bare tab\n // route. Its `overview.mdx` is often intentionally blank: leaving that\n // page blank strands the release notes even though every entry imports.\n // The feed contains the full articles, including code examples and\n // images. Entry bodies have already gone through normal MDX migration\n // and link/asset rewriting. Pages with module declarations need an\n // excerpt because imports cannot safely be concatenated into one MDX\n // document without renaming all their bindings.\n index.description ||= 'Latest release notes and product updates.'\n index.body = entries.map((entry) => {\n const date = entry.source.match(/\\d{4}-\\d{2}-\\d{2}/)?.[0]\n const escapeText = (value: string): string => value.replace(/([\\\\{}<>\\[\\]*_`])/g, '\\\\$1')\n // The runtime wraps headings in their own permalink anchor. A link\n // inside the heading would create nested anchors and break hydration.\n const body = /^(?:import|export)\\s.+(?:from\\s|\\{)/m.test(entry.body)\n ? escapeText(entry.description)\n : closeOpenCodeFence(date ? addDatedHeadingAliases(entry.body.trim(), date) : entry.body.trim()) || escapeText(entry.description)\n const dateAnchor = date ? `<a id=\"${date}T00:00:00.000Z\" />\\n\\n` : ''\n return `${dateAnchor}## ${escapeText(entry.title)}\\n\\n${date ? `**${date}** · ` : ''}[Read release note](/${entry.id})\\n\\n${body}`\n }).join('\\n\\n---\\n\\n')\n }\n }\n docsConfig = pruneMissingNavigationPages(docsConfig, new Set(pages.map((page) => page.navigationId)))\n if (platform === 'docusaurus') addDocusaurusTranslatedHeadingAliases(pages)\n if (platform === 'fern' && fernProjectRoot) {\n const sourcePath = (page: MigrationPage): string | null => {\n const fragment = page.source.split('#', 2)[1]\n if (!fragment) return null\n try {\n return relative(fernProjectRoot, resolveWithin(repositoryDir, decodeURIComponent(fragment))).replace(/\\\\/g, '/')\n } catch {\n return null\n }\n }\n const routes = new Map<string, string>()\n for (const page of pages) {\n const source = sourcePath(page)\n if (source) routes.set(source, page.id)\n }\n for (const page of pages) {\n const source = sourcePath(page)\n if (source) page.body = rewriteFernRelativePageLinks(page.body, source, routes)\n }\n }\n preserveLinkedAnchors(pages)\n if (platform === 'fern' && fernRawConfig) {\n const sourceSiteUrl = fernSourceSiteUrl(fernRawConfig)\n if (sourceSiteUrl) {\n const externalized = new Set<string>()\n const pageIds = new Set(pages.map((page) => page.id))\n for (const page of pages) page.body = externalizeMissingFernLinks(page.body, pageIds, sourceSiteUrl, externalized)\n if (externalized.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalized.size} unresolved Fern link(s) still point to ${sourceSiteUrl}; import those sections separately for a fully independent site.`,\n })\n }\n }\n if (docsConfig.redirects) {\n docsConfig = {\n ...docsConfig,\n redirects: docsConfig.redirects.filter((redirect) => {\n // A redirect back to the same literal route loops before the page can\n // render. Treat a trailing slash as the same route, while retaining\n // destinations with a query or fragment because they carry intent.\n const literalRoute = (route: string): string | null =>\n route.startsWith('/') && !/[?:*#()[\\]{}]/.test(route)\n ? route.replace(/\\/+$/, '') || '/'\n : null\n const sourceRoute = literalRoute(redirect.source)\n if (sourceRoute && sourceRoute === literalRoute(redirect.destination)) {\n warnings.push({\n code: 'unsupported-config',\n message: `Self-redirect from ${redirect.source} to ${redirect.destination} was omitted.`,\n })\n return false\n }\n // Next's route-pattern parser treats these as operators. Source\n // paths such as Mintlify's literal `/client/c++` must not make the\n // entire generated project fail to build.\n if (!/[+?()[\\]{}]/.test(redirect.source)) return true\n warnings.push({\n code: 'unsupported-config',\n message: `Redirect from ${redirect.source} contains route-pattern syntax Next.js cannot express literally and was omitted.`,\n })\n return false\n }),\n }\n }\n\n if (pages.length === 0) {\n const reasons = warnings.map((warning) => warning.message)\n throw new Error(reasons.length\n ? `No importable Markdown or MDX pages were found in the repository. Warnings encountered during migration:\\n${reasons.map((reason) => `- ${reason}`).join('\\n')}`\n : 'No importable Markdown or MDX pages were found in the repository.')\n }\n // Redirects and branding are global site config, extracted once at the\n // top-level Docusaurus call — `docusaurusSkipRedirects` already marks the\n // recursive per-plugin-instance sub-calls (community/mcp/agent-cli), which\n // would otherwise redundantly re-read (and re-warn about) the same config.\n const isTopLevelDocusaurus = platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipRedirects\n const docusaurusSettings = isTopLevelDocusaurus\n ? readDocusaurusSiteSettings(docusaurusProjectRoot!)\n : undefined\n if (docusaurusSettings) {\n const importedRoutes = new Set(pages.map((page) => page.navigationId))\n const sourceOrigin = readDocusaurusSiteOrigin(docusaurusProjectRoot!)\n const externalized = new Set<string>()\n const projectLink = (raw: string, sourceLiteral = false): string | undefined => {\n if (/^https?:\\/\\//i.test(raw)) return raw\n if (/^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(raw) || raw.includes('\\\\')) return undefined\n const suffixAt = raw.search(/[?#]/)\n const path = suffixAt < 0 ? raw : raw.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : raw.slice(suffixAt)\n const route = path.replace(/^\\.?\\//, '').replace(/\\/+$/, '')\n if (route === '..' || route.startsWith('../') || route.includes('/../')) return undefined\n const docsBase = docusaurusSettings.docsRouteBasePath.replace(/^\\/+|\\/+$/g, '')\n // Literal site links are routes in Docusaurus' URL space. A docs page\n // called \"blog\" must not capture the site's separate /blog section\n // when docs are mounted below /docs.\n const isOutsideDocs = sourceLiteral && docsBase\n && route !== docsBase && !route.startsWith(`${docsBase}/`)\n if (isOutsideDocs && sourceOrigin) {\n externalized.add(raw)\n return new URL(raw, `${sourceOrigin}/`).toString()\n }\n const strippedDocsRoute = docsBase && route.startsWith(`${docsBase}/`)\n ? route.slice(docsBase.length + 1) : route\n const candidates = [route, strippedDocsRoute, ...(route === docsBase ? ['introduction'] : [])]\n const imported = candidates.find((candidate) => importedRoutes.has(candidate))\n if (imported) return `/${imported}${suffix}`\n if (sourceOrigin) {\n externalized.add(raw)\n return new URL(raw, `${sourceOrigin}/`).toString()\n }\n return path.startsWith('/') ? `${path}${suffix}` : `/${route}${suffix}`\n }\n const firstNavigationPage = (nodes: Array<string | MigrationNavigationGroup>): string | undefined => {\n for (const node of nodes) {\n if (typeof node === 'string') return node\n const nested = firstNavigationPage(node.pages)\n if (nested) return nested\n }\n return undefined\n }\n const navbarLinks = docusaurusSettings.navbarLinks.flatMap((link) => {\n const docRoute = link.docId && !link.docsPluginId && docusaurusDescriptors.find((page) =>\n page.docId === link.docId)?.navigationId\n const sidebar = link.sidebarId && docsConfig.tabs.find((tab) =>\n tab.tab.toLowerCase() === link.sidebarId!.toLowerCase())\n const sidebarRoute = sidebar && firstNavigationPage(sidebar.pages ?? sidebar.groups ?? [])\n const pluginRoot = link.docsPluginId && importedRoutes.has(link.docsPluginId)\n ? link.docsPluginId : undefined\n const rawHref = link.href ?? (docRoute ? `/${docRoute}` : undefined)\n ?? (pluginRoot ? `/${pluginRoot}` : undefined)\n ?? (sidebarRoute ? `/${sidebarRoute}` : undefined)\n ?? (link.docsPluginId ? `/${link.docsPluginId}` : undefined)\n const href = rawHref && projectLink(rawHref, Boolean(link.href))\n return href ? [{ label: link.label, href }] : []\n })\n const footerLinks = docusaurusSettings.footerLinks?.flatMap((column) => {\n const items = column.items.flatMap((item) => {\n const href = projectLink(item.href, true)\n return href ? [{ label: item.label, href }] : []\n })\n return items.length > 0 ? [{ heading: column.heading, items }] : []\n })\n docsConfig = {\n ...docsConfig,\n ...(navbarLinks.length > 0 ? { navbar: { ...docsConfig.navbar, links: navbarLinks } } : {}),\n ...(footerLinks?.length || docusaurusSettings.copyright ? {\n footer: {\n ...docsConfig.footer,\n ...(footerLinks?.length ? { links: footerLinks } : {}),\n ...(docusaurusSettings.copyright ? { copyright: docusaurusSettings.copyright } : {}),\n },\n } : {}),\n }\n if (externalized.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalized.size} site navigation/footer link(s) point outside the imported docs and were kept on ${sourceOrigin}.`,\n })\n }\n // Dense version menus should fit in one header row. A dozen archived\n // Docusaurus releases otherwise turn the collection tabs into a tall wall\n // above every document.\n if (!docsConfig.navigation?.display && docsConfig.tabs.filter((tab) => !tab.hidden).length > 6) {\n docsConfig = { ...docsConfig, navigation: { display: 'dropdown' } }\n }\n const themeColors = mintlifyConfig\n ? mintlifyThemeColors(mintlifyConfig.colors)\n : fernRawConfig\n ? fernThemeColors(fernRawConfig.colors)\n : isTopLevelDocusaurus ? readDocusaurusThemeColor(docusaurusProjectRoot!) : undefined\n // Brand assets are copied as ordinary public files. Wire only assets that\n // were actually imported; a missing source file must not create a broken\n // header image or favicon. Admin uploads still override these fallbacks.\n const assetPaths = new Set(assets.map((asset) => asset.path))\n const publicBrandPath = (value: unknown): string | undefined => {\n if (typeof value !== 'string' || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(value)) return undefined\n const normalized = fernBrandAssetPaths.get(value) ?? normalizeAssetPath(value)\n return normalized && assetPaths.has(normalized) ? `/${normalized}` : undefined\n }\n const brandVariants = (value: unknown): { light?: string; dark?: string; showTitle?: boolean } => {\n if (typeof value === 'string') return { light: value }\n if (!value || typeof value !== 'object') return {}\n const source = value as Record<string, unknown>\n const light = source.light ?? source.src\n const dark = source.dark ?? source.srcDark\n return {\n ...(typeof light === 'string' ? { light } : {}),\n ...(typeof dark === 'string' ? { dark } : {}),\n ...(typeof source.showTitle === 'boolean' ? { showTitle: source.showTitle } : {}),\n }\n }\n const sourceLogo = mintlifyConfig?.logo ?? fernRawConfig?.logo ?? docusaurusSettings?.logo\n const sourceFavicon = mintlifyConfig?.favicon ?? fernRawConfig?.favicon ?? docusaurusSettings?.favicon\n const logo = brandVariants(sourceLogo)\n const favicon = brandVariants(sourceFavicon)\n const logoLight = publicBrandPath(logo.light)\n const logoDark = publicBrandPath(logo.dark)\n const faviconLight = publicBrandPath(favicon.light)\n const faviconDark = publicBrandPath(favicon.dark)\n if (logoLight) docsConfig = {\n ...docsConfig,\n navbar: {\n ...docsConfig.navbar,\n logo: {\n light: logoLight,\n ...(logoDark ? { dark: logoDark } : {}),\n showTitle: mintlifyConfig || fernRawConfig ? false : logo.showTitle !== false,\n ...(typeof (fernRawConfig?.logo as Record<string, unknown> | undefined)?.['right-text'] === 'string'\n ? { rightText: String((fernRawConfig!.logo as Record<string, unknown>)['right-text']).trim().slice(0, 40) }\n : {}),\n },\n },\n }\n if (platform === 'docusaurus' && docusaurusSettings?.navbarTitle && !logoLight) {\n // Docusaurus commonly uses a text-only navbar. Its commented-out logo\n // template must not become Thally's unrelated starter leaf mark.\n docsConfig = { ...docsConfig, navbar: { ...docsConfig.navbar, logo: null } }\n }\n if (mintlifyConfig) {\n const appearance = mintlifyConfig.appearance && typeof mintlifyConfig.appearance === 'object'\n ? mintlifyConfig.appearance as Record<string, unknown> : null\n const defaultMode = appearance?.default\n if (defaultMode === 'light' || defaultMode === 'dark' || defaultMode === 'system') {\n docsConfig = { ...docsConfig, appearance: { ...docsConfig.appearance, default: defaultMode } }\n }\n const background = mintlifyConfig.background && typeof mintlifyConfig.background === 'object'\n ? mintlifyConfig.background as Record<string, unknown> : null\n if (background) {\n const decoration = background.decoration\n const image = publicBrandPath(background.image)\n const imageDark = publicBrandPath(background.imageDark)\n docsConfig = {\n ...docsConfig,\n background: {\n ...docsConfig.background,\n ...(decoration === 'none' || decoration === 'grid' || decoration === 'gradient' ? { decoration } : {}),\n ...(image ? { image } : {}),\n ...(imageDark ? { imageDark } : {}),\n },\n }\n }\n }\n if (platform === 'docusaurus') {\n docsConfig = { ...docsConfig, appearance: { ...docsConfig.appearance, default: docusaurusSettings?.defaultColorMode ?? 'light' } }\n }\n if (faviconLight) docsConfig = {\n ...docsConfig,\n favicon: { light: faviconLight, ...(faviconDark ? { dark: faviconDark } : {}) },\n }\n const missingBrand = [\n ...[logo.light, logo.dark].filter((value): value is string => typeof value === 'string' && !publicBrandPath(value)),\n ...[favicon.light, favicon.dark].filter((value): value is string => typeof value === 'string' && !publicBrandPath(value)),\n ]\n if (missingBrand.length > 0) warnings.push({\n code: 'unsupported-config',\n message: `Brand asset(s) were referenced but not imported: ${[...new Set(missingBrand)].join(', ')}. Add these files under public/ or update docs.json.`,\n })\n if (fernRawConfig?.logo && !logoLight && !logo.light) warnings.push({\n code: 'unsupported-config',\n message: 'Fern supplied a logo through its global theme without a local asset; add a logo path to docs.json after import.',\n })\n return {\n sourceUrl: options.sourceUrl,\n sourceKind: 'repository',\n platform,\n pages,\n assets,\n ...(remoteApiSpecs.length > 0 ? { remoteApiSpecs } : {}),\n ...(componentMigrator ? { componentFiles: componentMigrator.files() } : {}),\n docsConfig,\n ...(mintlifyConfig ? {\n site: {\n ...(typeof mintlifyConfig.name === 'string' ? { name: mintlifyConfig.name } : {}),\n ...(typeof mintlifyConfig.description === 'string' ? { description: mintlifyConfig.description } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : fernRawConfig && (typeof fernRawConfig.title === 'string' || themeColors) ? {\n site: {\n ...(typeof fernRawConfig.title === 'string' ? { name: fernRawConfig.title } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : docusaurusSettings && (docusaurusSettings.name || docusaurusSettings.description || themeColors) ? {\n site: {\n ...(docusaurusSettings.navbarTitle || docusaurusSettings.name ? { name: docusaurusSettings.navbarTitle ?? docusaurusSettings.name } : {}),\n ...(docusaurusSettings.description ? { description: docusaurusSettings.description } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : themeColors ? {\n site: { colors: themeColors },\n } : {}),\n warnings,\n stats: { discovered, imported: pages.length, skipped },\n }\n}\n","/**\n * Move repository-owned MDX components into the customer component registry.\n * Source is parsed, never evaluated. Every dependency must remain inside the\n * documentation root and traverse only ordinary files (including its parents).\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, lstatSync, readFileSync } from 'node:fs'\nimport { basename, dirname, extname, relative, resolve } from 'node:path'\nimport postcss from 'postcss'\nimport selectorParser from 'postcss-selector-parser'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport ts from 'typescript'\nimport { unified } from 'unified'\n\nimport { parseFrontmatter } from './frontmatter.js'\nimport { functionDeclaredNames, isFunctionInitializer, normalizeHtmlComments, normalizeExplicitHeadingIds } from './mdx.js'\nimport { resolveWithin } from './path.js'\nimport type { MigrationWarning, RenderedMigrationFile } from './types.js'\n\ninterface MdxNode {\n type: string\n name?: string | null\n value?: string\n attributes?: Array<{\n name?: string\n type: string\n value?: string | { value?: string } | null\n position?: { start: { offset?: number }; end: { offset?: number } }\n }>\n children?: Array<MdxNode>\n position?: { start: { offset?: number }; end: { offset?: number } }\n}\n\ninterface Replacement { start: number; end: number; value: string }\ninterface Binding { local: string; imported: string; source: string }\n\n/** Make JSX-indented fences parse as code before MDX import analysis runs. */\nexport function normalizeIndentedFences(content: string): string {\n const lines = content.split('\\n')\n let active: { indent: string; marker: string } | undefined\n let ordinaryFence: string | undefined\n let indentedJsx: { tag: string; indent: string } | undefined\n let listIndent: number | undefined\n return lines.map((line) => {\n const trimmed = line.trimStart()\n // A fenced example inside list-indented JSX must move together with its\n // container. Unindenting only the fence leaves the tag unclosed; keeping\n // everything indented lets textual import passes mistake example imports\n // for live MDX imports.\n if (indentedJsx) {\n const normalized = line.startsWith(indentedJsx.indent) ? line.slice(indentedJsx.indent.length) : line\n if (normalized.trimStart().startsWith(`</${indentedJsx.tag}>`)) indentedJsx = undefined\n return normalized\n }\n if (ordinaryFence) {\n const closing = trimmed.match(/^(`{3,}|~{3,})\\s*$/)?.[1]\n if (closing && closing[0] === ordinaryFence[0] && closing.length >= ordinaryFence.length) ordinaryFence = undefined\n return line\n }\n if (!active) {\n const listItem = line.match(/^([ \\t]*)(?:[-*+]|\\d+[.)])\\s/)\n const indentation = line.length - trimmed.length\n if (listItem) listIndent = listItem[1].length\n else if (trimmed && listIndent !== undefined && indentation <= listIndent) listIndent = undefined\n const jsx = line.match(/^([ \\t]{2,})<([A-Z][\\w.]*)\\b[^>]*>\\s*$/)\n if (jsx && listIndent !== undefined && jsx[1].length > listIndent && !trimmed.endsWith('/>')) {\n indentedJsx = { tag: jsx[2], indent: jsx[1] }\n return line.slice(jsx[1].length)\n }\n const match = line.match(/^([ \\t]{4,})(`{3,}|~{3,})/)\n if (match) {\n active = { indent: match[1], marker: match[2] }\n return line.slice(match[1].length)\n }\n const ordinary = line.match(/^[ \\t]{0,3}(`{3,}|~{3,})/)\n if (ordinary) ordinaryFence = ordinary[1]\n return line\n }\n const normalized = line.startsWith(active.indent) ? line.slice(active.indent.length) : line\n const closing = normalized.trimStart().match(/^(`{3,}|~{3,})\\s*$/)?.[1]\n if (closing && closing[0] === active.marker[0] && closing.length >= active.marker.length) active = undefined\n return normalized\n }).join('\\n')\n}\n\n/** Lift a self-contained data helper out of a copied client module for server MDX expressions. */\nfunction staticServerHelper(path: string, imported: string, local: string): string | null {\n if (imported === 'default') return null\n const parsed = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n const isLiteral = (node: ts.Expression): boolean => {\n if (ts.isParenthesizedExpression(node)) return isLiteral(node.expression)\n if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isNumericLiteral(node)) return true\n if ([ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(node.kind)) return true\n if (ts.isPrefixUnaryExpression(node)) return [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken].includes(node.operator) && ts.isNumericLiteral(node.operand)\n if (ts.isArrayLiteralExpression(node)) return node.elements.every((element) => ts.isExpression(element) && isLiteral(element))\n if (ts.isObjectLiteralExpression(node)) return node.properties.every((property) => ts.isPropertyAssignment(property)\n && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name))\n && isLiteral(property.initializer))\n return false\n }\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== imported || !declaration.initializer || !ts.isArrowFunction(declaration.initializer)) continue\n const arrow = declaration.initializer\n if (arrow.parameters.length > 0) continue\n const result = ts.isBlock(arrow.body)\n ? arrow.body.statements.length === 1 && ts.isReturnStatement(arrow.body.statements[0]) ? arrow.body.statements[0].expression : undefined\n : arrow.body\n if (result && isLiteral(result)) return `export const ${local} = () => (${result.getText(parsed)});`\n }\n }\n return null\n}\n\n/** A bare `id`/`videoId`-style attribute value is safe to embed in an `iframe src` only when it looks like a real YouTube video id. */\nconst YOUTUBE_VIDEO_ID = /^[\\w-]{1,64}$/\n/** Packages known to take a literal YouTube video id prop (as opposed to a URL, or a non-YouTube player). */\nconst YOUTUBE_ID_PACKAGES = new Set(['react-lite-youtube-embed', 'react-youtube', '@justinribeiro/lite-youtube'])\nconst YOUTUBE_URL = /(?:youtube\\.com\\/(?:watch\\?v=|embed\\/|shorts\\/)|youtu\\.be\\/)([\\w-]{1,64})/i\n\n/**\n * Only a small, known set of YouTube embed packages get a working `<iframe>`\n * replacement; every other removed component (Vimeo, Loom, a bespoke\n * in-house player, or any package this doesn't recognize) falls back to the\n * plain comment stub, since guessing at an unfamiliar player's embed URL\n * shape would silently render the wrong video or nothing at all.\n */\nfunction youtubeEmbedVideoId(node: MdxNode, specifier: string): string | undefined {\n const attribute = (attributeName: string): string | undefined => {\n const raw = node.attributes?.find((entry) => entry.name === attributeName)?.value\n return typeof raw === 'string' ? raw : undefined\n }\n if (YOUTUBE_ID_PACKAGES.has(specifier)) {\n const id = attribute('id') ?? attribute('videoId')\n return id && YOUTUBE_VIDEO_ID.test(id) ? id : undefined\n }\n if (specifier === 'react-player') {\n const url = attribute('url')\n const match = url ? YOUTUBE_URL.exec(url) : null\n return match ? match[1] : undefined\n }\n return undefined\n}\n\nconst parser = unified().use(remarkParse).use(remarkMdx)\nconst CODE_EXTENSIONS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs'])\nconst DATA_EXTENSIONS = new Set(['.json', '.css', '.svg', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.woff', '.woff2'])\n/**\n * Binary asset types a failed component/module import can still be rescued\n * as: copied verbatim to `public/` and bound to its URL string, rather than\n * losing the reference outright. Includes types `DATA_EXTENSIONS` already\n * lets `copyGraph` copy as a JS-module asset (an image can still fail that\n * path for other reasons — budget, a symlink) and types it never would\n * (`.docx`, `.pdf`: not importable as a JS module, but a real static file).\n */\nconst RESCUABLE_ASSET_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.ico', '.docx', '.pdf'])\n\n/**\n * Tiny equivalents for the handful of Docusaurus theme/runtime imports a\n * copied component commonly uses, so the component still copies instead of\n * failing outright with \"external package requires manual installation\" —\n * the same reasoning as `SCAFFOLD_PROVIDED_IMPORTS`, just for names that\n * only exist inside a Docusaurus build. Deliberately small: anything else\n * Docusaurus-specific (`@docusaurus/Translate`, a theme-common hook, ...)\n * still fails copyGraph and is handled by the dead-import-removal fallback\n * (the catch block below) instead of growing this into a Docusaurus shim\n * layer.\n */\nconst DOCUSAURUS_THEME_SHIMS: Record<string, { filename: string; content: string }> = {\n '@theme/CodeBlock': {\n filename: 'docusaurus-code-block.tsx',\n content: [\n \"import type { ReactNode } from 'react'\",\n '',\n 'export default function CodeBlock({ children, className }: { children?: ReactNode; className?: string }) {',\n ' return (',\n ' <pre className={className}>',\n ' <code>{children}</code>',\n ' </pre>',\n ' )',\n '}',\n '',\n ].join('\\n'),\n },\n '@docusaurus/BrowserOnly': {\n filename: 'docusaurus-browser-only.tsx',\n content: [\n \"'use client'\",\n '',\n \"import { useEffect, useState, type ReactNode } from 'react'\",\n '',\n 'export default function BrowserOnly({ children, fallback = null }: { children: () => ReactNode; fallback?: ReactNode }) {',\n ' const [mounted, setMounted] = useState(false)',\n ' useEffect(() => { setMounted(true) }, [])',\n ' return mounted ? <>{children()}</> : <>{fallback}</>',\n '}',\n '',\n ].join('\\n'),\n },\n}\nconst SHARED_IMPORTS = new Set(['react', 'react/jsx-runtime', 'react/jsx-dev-runtime'])\n/**\n * Packages the standalone starter already installs as its own runtime\n * dependencies. An MDX page's import of one of these (or of a subpath such\n * as `next/navigation` or `lucide-react/dynamic`), even outside JSX, is not\n * \"unavailable\": the package is really there, so the page keeps the import\n * and any extracted client module gets a copy of it.\n *\n * `@/…` path aliases are deliberately absent: in a source repository they\n * point at that site's own code, not at Thally's.\n *\n * Drift-guarded by the \"SCAFFOLD_PROVIDED_IMPORTS drift guard\" test in\n * `packages/migrate/src/__tests__/components.test.ts`.\n */\nexport const SCAFFOLD_PROVIDED_IMPORTS: ReadonlySet<string> = new Set(['next', 'react-dom', 'clsx', 'lucide-react', 'tailwind-merge'])\nfunction isScaffoldProvidedImport(specifier: string): boolean {\n // Next aliases react-dom/server so renderToString/renderToStaticMarkup throw\n // at render; treat it like an unavailable package rather than keep the page.\n if (/^react-dom\\/server(?:[./]|$)/.test(specifier)) return false\n return [...SCAFFOLD_PROVIDED_IMPORTS].some((name) => specifier === name || specifier.startsWith(`${name}/`))\n}\n/** How a warning names an import that is not available in the migrated project. */\nfunction unavailableImportLabel(specifier: string): string {\n return specifier.startsWith('@/')\n ? `the path alias '${specifier}' (the source site's own code, which the migration does not copy)`\n : `the npm package '${specifier}'`\n}\nconst REACT_GLOBALS = new Set([\n 'useState', 'useEffect', 'useLayoutEffect', 'useMemo', 'useCallback', 'useRef',\n 'useReducer', 'useContext', 'useId', 'useTransition', 'useDeferredValue',\n 'useImperativeHandle', 'useSyncExternalStore', 'useInsertionEffect',\n 'useOptimistic', 'useActionState', 'use', 'createContext', 'forwardRef', 'memo',\n])\nconst MAX_COMPONENT_FILES = 300\nconst MAX_COMPONENT_BYTES = 20_000_000\nconst MAX_FILE_BYTES = 2_000_000\n\n/**\n * Where each Thally built-in MDX component actually lives, for building the\n * `MintlifyComponents` shim (below). This must import each leaf module\n * directly rather than the app's `mdx-components.tsx` registry: that\n * registry pulls in `src/mdx/custom-components.tsx`, which re-exports every\n * migrated component — including this very generated file — so importing\n * it here would be circular (`ReferenceError: Cannot access 'X' before\n * initialization` at build time). Kept in sync with\n * `src/components/mdx/mdx-components.tsx`'s own imports by hand; a drift\n * here only means `MintlifyComponents.<Name>` is `undefined` for a name\n * added there, not a crash.\n */\nconst MINTLIFY_COMPONENT_MODULES: ReadonlyArray<{ module: string; names: ReadonlyArray<string> }> = [\n { module: '@/components/mdx/note', names: ['Note'] },\n { module: '@/components/mdx/agent-prompt', names: ['AgentPrompt'] },\n { module: '@/components/mdx/code-blocks', names: ['CodeGroup'] },\n { module: '@/components/mdx/rich-content', names: ['Columns', 'Frame', 'Hero'] },\n { module: '@/components/mdx/accordion', names: ['Accordion', 'AccordionGroup'] },\n { module: '@/components/mdx/content-cards', names: ['Card', 'CardGroup', 'Tile', 'TileGroup'] },\n { module: '@/components/mdx/content-icon', names: ['Icon'] },\n { module: '@/components/mdx/content-inline', names: ['Badge', 'Tooltip'] },\n { module: '@/components/mdx/color', names: ['Color'] },\n { module: '@/components/mdx/content-metadata', names: ['Update'] },\n { module: '@/components/mdx/panel', names: ['Panel', 'ContentPanel', 'InlinePanel'] },\n { module: '@/components/mdx/examples', names: ['RequestExample', 'ResponseExample', 'InlineRequestExample', 'InlineResponseExample'] },\n { module: '@/components/mdx/prompt', names: ['Prompt', 'PromptAssistant', 'PromptUser', 'Terminal', 'TerminalInput', 'TerminalOutput'] },\n { module: '@/components/mdx/file-tree', names: ['Tree', 'Folder', 'File'] },\n { module: '@/components/mdx/api-fields', names: ['ResponseField', 'ParamField', 'Expandable'] },\n { module: '@/components/mdx/mermaid', names: ['Mermaid'] },\n { module: '@/components/mdx/view', names: ['Embed', 'LegacyView', 'View'] },\n { module: '@/components/mdx/github-card', names: ['GitHub'] },\n { module: '@/components/mdx/visibility', names: ['Agent', 'Human', 'Visibility'] },\n { module: '@/components/mdx/steps', names: ['Steps', 'Step'] },\n { module: '@/components/mdx/content-tabs', names: ['Tabs', 'Tab'] },\n]\n\n/** Builtins mapped straight through to their same-named import (aliased, see below). */\nconst MINTLIFY_DIRECT_COMPONENTS = [\n 'AccordionGroup', 'Hero', 'Card', 'CardGroup', 'Columns', 'Frame', 'Accordion', 'Tooltip',\n 'Icon', 'Steps', 'Step', 'Tabs', 'Tab', 'Badge', 'Update', 'RequestExample', 'ResponseExample',\n 'Panel', 'ContentPanel', 'InlinePanel', 'InlineRequestExample', 'InlineResponseExample',\n 'Tile', 'TileGroup', 'Prompt', 'PromptUser', 'PromptAssistant', 'Terminal', 'TerminalInput',\n 'TerminalOutput', 'AgentPrompt', 'Color', 'Tree', 'Folder', 'File', 'ResponseField',\n 'ParamField', 'Expandable', 'Mermaid', 'View', 'Embed', 'LegacyView', 'GitHub', 'Visibility',\n 'Human', 'Agent', 'CodeGroup',\n]\n\n/**\n * Mintlify's implicit `MintlifyComponents` global for a copied `.jsx`\n * snippet (`const { Card } = MintlifyComponents;`, no import) — an object\n * of Thally's built-in equivalents. Every import is aliased (`Card as\n * __mintlify_Card`) so none of ~50 bare names land in the snippet's own top\n * level scope and risk colliding with something it already declares; only\n * the single `MintlifyComponents` identifier is introduced unaliased.\n */\nfunction mintlifyComponentsShim(): string {\n const alias = (name: string) => `__mintlify_${name}`\n const imports = MINTLIFY_COMPONENT_MODULES\n .map(({ module, names }) => `import { ${names.map((name) => `${name} as ${alias(name)}`).join(', ')} } from '${module}';`)\n .join('\\n')\n const entries = [\n // The callout family all render through Note, whose `type` mdx-components.tsx\n // sets for each name; Callout and Latex mirror that file's own handling.\n `Info: (props) => <${alias('Note')} type=\"info\" {...props} />`,\n `Warning: (props) => <${alias('Note')} type=\"warning\" {...props} />`,\n `Check: (props) => <${alias('Note')} type=\"check\" {...props} />`,\n `Danger: (props) => <${alias('Note')} type=\"danger\" {...props} />`,\n `Error: (props) => <${alias('Note')} type=\"danger\" {...props} />`,\n `Note: (props) => <${alias('Note')} type=\"note\" {...props} />`,\n `Tip: (props) => <${alias('Note')} type=\"tip\" {...props} />`,\n `Callout: (props) => <${alias('Note')} {...props} />`,\n `Latex: ({ children }) => <code>{children}</code>`,\n ...MINTLIFY_DIRECT_COMPONENTS.map((name) => `${name}: ${alias(name)}`),\n `Github: ${alias('GitHub')}`,\n ]\n return `${imports}\\nconst MintlifyComponents = {\\n ${entries.join(',\\n ')},\\n};`\n}\n\nfunction applyReplacements(source: string, replacements: Array<Replacement>): string {\n return replacements.sort((a, b) => b.start - a.start).reduce(\n (text, edit) => text.slice(0, edit.start) + edit.value + text.slice(edit.end), source,\n )\n}\n\nfunction hash(value: string): string {\n return createHash('sha256').update(value).digest('hex').slice(0, 12)\n}\n\nfunction portableSpecifier(path: string): string {\n // Customer tsconfigs do not opt into allowImportingTsExtensions. Next's\n // bundler resolves these extensionless source imports without that flag.\n return path.replace(/\\.tsx?$/, '')\n}\n\n/**\n * Turbopack's CSS Modules loader requires every selector to contain at\n * least one class or id (\"pure\"): a copied `.module.css` file that targets\n * `:root`, an element, or an attribute at the top level (a common way to\n * key off a `data-theme` attribute, e.g. Docusaurus' `BrowserWindow`) fails\n * the whole build with `Selector \"...\" is not pure`, even though the\n * selector compiled and worked fine in its own Docusaurus build. Wrap only\n * the impure branches of each rule's selector list in `:global(...)`\n * (CSS Modules' own escape hatch) using a real selector parser — a\n * character-scanning approach can't tell a selector's structure (nesting,\n * combinators, pseudo-classes) from its text reliably enough to know where\n * a `:global(...)` wrapper legally starts and ends.\n */\nfunction wrapImpureCssModuleSelectors(css: string): string {\n const root = postcss.parse(css)\n root.walkRules((rule) => {\n rule.selector = selectorParser((selectors) => {\n selectors.each((selector) => {\n let hasClassOrId = false\n selector.walk((node) => {\n if (node.type === 'class' || node.type === 'id') hasClassOrId = true\n })\n if (hasClassOrId) return\n const nodes = selector.nodes.splice(0, selector.nodes.length)\n const container = selectorParser.selector({ value: '' })\n for (const node of nodes) container.append(node)\n const globalPseudo = selectorParser.pseudo({ value: ':global' })\n globalPseudo.append(container)\n selector.append(globalPseudo)\n })\n }).processSync(rule.selector)\n })\n return root.toString()\n}\n\nfunction sourceFile(source: string, filename: string): ts.SourceFile {\n return ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true,\n /\\.[cm]?ts$/.test(filename) ? ts.ScriptKind.TS : ts.ScriptKind.TSX)\n}\n\nfunction walk(node: MdxNode, visitor: (node: MdxNode) => void): void {\n visitor(node)\n for (const child of node.children ?? []) walk(child, visitor)\n}\n\nfunction implicitReactImports(source: ts.SourceFile): string {\n const bindings = new Set<string>()\n const references = new Set<string>()\n function bind(name: ts.BindingName): void {\n if (ts.isIdentifier(name)) bindings.add(name.text)\n else for (const element of name.elements) if (ts.isBindingElement(element)) bind(element.name)\n }\n for (const statement of source.statements) {\n if (ts.isImportDeclaration(statement) && statement.importClause) {\n const clause = statement.importClause\n if (clause.name) bindings.add(clause.name.text)\n if (clause.namedBindings) {\n if (ts.isNamespaceImport(clause.namedBindings)) bindings.add(clause.namedBindings.name.text)\n else for (const element of clause.namedBindings.elements) bindings.add(element.name.text)\n }\n }\n if (ts.isVariableStatement(statement)) for (const declaration of statement.declarationList.declarations) bind(declaration.name)\n if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) bindings.add(statement.name.text)\n }\n function visit(node: ts.Node): void {\n if (ts.isIdentifier(node) && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)\n && !(ts.isPropertyAssignment(node.parent) && node.parent.name === node)) references.add(node.text)\n ts.forEachChild(node, visit)\n }\n visit(source)\n const hooks = [...REACT_GLOBALS].filter((name) => references.has(name) && !bindings.has(name)).sort()\n // Mintlify's own snippet convention exposes its built-in MDX components as\n // an implicit global too (`const { Card } = MintlifyComponents;`, no\n // import).\n const usesMintlifyComponents = references.has('MintlifyComponents') && !bindings.has('MintlifyComponents')\n // Mintlify also makes built-ins available as bare JSX names inside snippet\n // modules. A copied module runs outside Mintlify's MDX scope, so explicitly\n // import every unbound name it uses before the destination build renders it.\n const implicitComponents = MINTLIFY_COMPONENT_MODULES.map(({ module, names }) => {\n const needed = names.filter((name) => references.has(name) && !bindings.has(name))\n return needed.length ? `import { ${needed.join(', ')} } from '${module}';` : ''\n }).filter(Boolean)\n return [\n references.has('React') && !bindings.has('React') ? \"import * as React from 'react';\" : '',\n hooks.length ? `import { ${hooks.join(', ')} } from 'react';` : '',\n ...implicitComponents,\n usesMintlifyComponents ? mintlifyComponentsShim() : '',\n ].filter(Boolean).join('\\n')\n}\n\nfunction imports(statement: ts.ImportDeclaration): Array<Binding> {\n if (!ts.isStringLiteral(statement.moduleSpecifier) || !statement.importClause) return []\n const clause = statement.importClause\n if (clause.isTypeOnly) return []\n const source = statement.moduleSpecifier.text\n const bindings: Array<Binding> = clause.name ? [{ local: clause.name.text, imported: 'default', source }] : []\n if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n if (!element.isTypeOnly) bindings.push({ local: element.name.text, imported: element.propertyName?.text ?? element.name.text, source })\n }\n }\n return bindings\n}\n\n/**\n * Every component this migrator actually renders in a client boundary — a\n * copied import (`register`, always prefixed 'use client' by `copyGraph`) or\n * an inline-extracted interactive block (`Inline<n>`) — is renamed to one of\n * these two shapes in the transformed body. No other JSX tag (a Thally\n * built-in, an unregistered/removed component) ever matches.\n */\nconst EXTRACTED_CLIENT_COMPONENT_TAG = /^(?:Migrated[0-9a-f]+|Inline\\d+)$/\n\n/**\n * Thally's own runtime `src/components/mdx/mdx-components.tsx` registry names\n * whose backing module is a 'use client' file under `src/components/mdx/`.\n * Passing a page-authored function as a prop into any of these also throws\n * \"Functions cannot be passed directly to Client Components\" at render, the\n * same as an extracted component — so they are confirmed exclusion targets\n * too, not just unconfirmed-and-warned.\n *\n * This list is a snapshot, not a live read of the app (a published migrate\n * package cannot import from the app's `src/`). It is drift-guarded by\n * `src/components/mdx/client-registry.test.ts`, which recomputes the same\n * set from `src/components/mdx/*.tsx` and `mdx-components.tsx` and fails CI\n * if this snapshot goes stale.\n *\n * Source file per name (all under `src/components/mdx/`):\n * Accordion, AccordionGroup -> accordion.tsx\n * AgentPrompt -> agent-prompt.tsx\n * ResponseField, ParamField,\n * Expandable -> api-fields.tsx\n * CodeGroup -> code-blocks.tsx\n * Badge, Tooltip -> content-inline.tsx\n * Tabs, Tab -> content-tabs.tsx\n * RequestExample, ResponseExample,\n * InlineRequestExample,\n * InlineResponseExample -> examples.tsx\n * Tree, Folder, File -> file-tree.tsx\n * Mermaid -> mermaid.tsx\n * Panel, ContentPanel,\n * InlinePanel -> panel.tsx\n * Prompt, PromptUser,\n * PromptAssistant, Terminal,\n * TerminalInput, TerminalOutput -> prompt.tsx\n * View, Embed, LegacyView -> view.tsx\n * Color, Color.Item -> color.tsx (server) spreads props into\n * color-item.tsx's 'use client'\n * ColorItemClient — a re-export, not a\n * direct 'use client' file, so it is\n * listed by hand (see the override map\n * in client-registry.test.ts)\n */\nexport const CLIENT_BUILTIN_COMPONENT_TAGS: ReadonlySet<string> = new Set([\n 'Accordion', 'AccordionGroup',\n 'AgentPrompt',\n 'ResponseField', 'ParamField', 'Expandable',\n 'CodeGroup',\n 'Badge', 'Tooltip',\n 'Tabs', 'Tab',\n 'RequestExample', 'ResponseExample', 'InlineRequestExample', 'InlineResponseExample',\n 'Tree', 'Folder', 'File',\n 'Mermaid',\n 'Panel', 'ContentPanel', 'InlinePanel',\n 'Prompt', 'PromptUser', 'PromptAssistant', 'Terminal', 'TerminalInput', 'TerminalOutput',\n 'View', 'Embed', 'LegacyView',\n 'Color', 'Color.Item',\n])\n\nfunction isConfirmedClientBoundaryTag(name: string): boolean {\n return EXTRACTED_CLIENT_COMPONENT_TAG.test(name) || CLIENT_BUILTIN_COMPONENT_TAGS.has(name)\n}\n\n/**\n * A JSX attribute's raw expression source (`prop={<this>}`), for the two\n * shapes that end up passing a function value: a bare reference to a\n * page-declared function (`declaredNames`), or a function written inline\n * right there (`() => ...`, `function () { ... }`). Only `mdxJsxAttribute`\n * nodes with an expression value carry a source string here; a string\n * literal attribute (`title=\"x\"`) or a spread (`mdxJsxExpressionAttribute`)\n * never does, so this returns `undefined` for those.\n */\nfunction functionValuedAttribute(node: MdxNode, declaredNames: ReadonlySet<string>): string | undefined {\n const isFunctionValue = (value: string) => declaredNames.has(value.trim()) || isFunctionInitializer(value.trim(), 0)\n for (const attribute of node.attributes ?? []) {\n const raw = attribute.value\n const value = raw && typeof raw === 'object' ? raw.value : undefined\n if (typeof value !== 'string') continue\n if (isFunctionValue(value)) return value\n }\n // Function-as-children (`<Accordion>{() => 'x'}</Accordion>`) is passed as\n // the `children` prop, so it crosses the same boundary. Inline children sit\n // inside a paragraph node; look one level into it.\n const children = (node.children ?? []).flatMap((child) => child.type === 'paragraph' ? child.children ?? [] : [child])\n for (const child of children) {\n if (['mdxFlowExpression', 'mdxTextExpression'].includes(child.type) && child.value && isFunctionValue(child.value)) return child.value\n }\n return undefined\n}\n\n/**\n * True when a name in `declaredNames` (typically a page's `export const`/\n * `export function` identifiers) is passed as a bare JSX prop\n * (`prop={Name}`), or a function is written inline as a prop value\n * (`prop={() => ...}`, `prop={function () { ... }}`), into a component\n * confirmed to cross the server/client boundary: one this migrator extracted\n * as a 'use client' module, or a Thally runtime built-in already backed by\n * one (`CLIENT_BUILTIN_COMPONENT_TAGS`). This is the only shape that really\n * throws \"Functions cannot be passed directly to Client Components\" at\n * render — the same check against an unconfirmed tag would over-fire and\n * drop pages that render just fine.\n *\n * JSX written inside a page's own `export const Name = () => <...>` (bound\n * for client extraction itself) is never visited here: `remark-mdx` parses\n * that whole declaration as a single `mdxjsEsm` text node, not as MDX JSX\n * element nodes, so `walk`'s `.children` traversal never reaches it — the\n * same reason fenced/inline code samples (parsed as `code`/`inlineCode` text\n * nodes) never reach it either.\n */\nexport function propsTargetExtractedClientComponent(body: string, declaredNames: ReadonlySet<string>): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n walk(tree, (node) => {\n if (found || !node.name || !isConfirmedClientBoundaryTag(node.name)) return\n if (functionValuedAttribute(node, declaredNames) !== undefined) found = true\n })\n return found\n}\n\n/**\n * Broader, unconfirmed signal: true when *any* JSX tag on the page (not\n * just a confirmed client boundary) receives a function-valued prop, the\n * same shapes `propsTargetExtractedClientComponent` looks for. Callers use\n * this to decide whether the page is worth a \"might throw at render, review\n * manually\" warning even when the receiving tag's own client/server status\n * cannot be confirmed.\n */\nexport function hasAnyFunctionValuedProp(body: string, declaredNames: ReadonlySet<string>): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n walk(tree, (node) => {\n if (found || !node.name) return\n if (functionValuedAttribute(node, declaredNames) !== undefined) found = true\n })\n return found\n}\n\n/**\n * True when a page's own inline `export const`/`export function` declaration\n * (kept in place, not extracted into a 'use client' module — see the\n * `mdxjsEsm` note above) references `document` or `window` as an identifier.\n * Next renders an MDX page as a Server Component by default, where neither\n * global exists; callers use this to warn rather than let the page fail at\n * render. Identifiers are found via the TS AST, so a string, comment, or\n * fenced code sample using the same words never counts.\n */\nexport function declarationsReferenceBrowserGlobal(body: string): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n function inspect(node: ts.Node): void {\n if (ts.isIdentifier(node) && (node.text === 'document' || node.text === 'window')) found = true\n ts.forEachChild(node, inspect)\n }\n for (const node of tree.children ?? []) {\n if (found || node.type !== 'mdxjsEsm' || node.value === undefined) continue\n for (const statement of sourceFile(node.value, 'inline.tsx').statements) {\n if (ts.isVariableStatement(statement) || ts.isFunctionDeclaration(statement)) inspect(statement)\n }\n }\n return found\n}\n\n/** Create one bounded component graph and registry for a repository migration. */\n/**\n * `siteRoot` (a Mintlify/Docusaurus project root, when one was detected —\n * `repositoryDir` otherwise) is what `@site/...`/root-relative (`/...`)\n * specifiers resolve against, matching Docusaurus' own alias semantics; a\n * warning's reported `source` and the generated destination paths stay\n * relative to it too, unchanged from before this parameter split. A plain\n * relative import (`../../components/X`), though, is written relative to\n * the importing *page*, which — in a monorepo where docs/ is a sibling of\n * website/ rather than nested under it (Redux) — can resolve outside\n * `siteRoot` even for a component the repository legitimately owns.\n * `confinementRoot` (always `repositoryDir`) is the actual security\n * boundary for that resolution and for `checkedFile`'s symlink safety walk,\n * so such an import still copies instead of throwing \"path escapes its\n * root\" for a component this migration should have imported.\n */\n\n/**\n * Text-only safety net for a page whose MDX can't be parsed at all (see the\n * catch below `transform`'s own `parser.parse` call): with no AST to drive a\n * real copy/removal, this only guarantees the page still builds by dropping\n * a `@site/...`/relative component import and blanking its JSX usage,\n * narrowly matching the single-binding default/named-as-default shape\n * `SNIPPET_IMPORT_PATTERN` (repository.ts) already uses for the same reason.\n * A bare npm-package import is left alone — that failure mode (\"module not\n * installed\") is unrelated to why this page's MDX didn't parse, and this\n * pass has no way to tell whether it is actually used anywhere.\n */\nfunction neutralizeUnresolvableImportsWithoutAst(content: string, currentFile: string, warn: (message: string, source: string) => void): string {\n const importPattern = /^import\\s+(?:\\{\\s*(?:default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}|([A-Z][A-Za-z0-9_]*))\\s+from\\s+(['\"])((?:@site\\/|\\.\\.?\\/|\\/)[^'\"]+)\\3\\s*;?[ \\t]*$/gm\n const dropped: Array<{ name: string; specifier: string }> = []\n let result = content.replace(importPattern, (_match, namedComponent: string | undefined, defaultComponent: string | undefined, _quote: string, specifier: string) => {\n dropped.push({ name: (namedComponent ?? defaultComponent) as string, specifier })\n return ''\n })\n for (const { name, specifier } of dropped) {\n warn(`Component import ${JSON.stringify(specifier)} could not be resolved because this page has invalid MDX (see the previous warning), so the import and its usage were removed to keep the site building.`, currentFile)\n result = result\n .replace(new RegExp(`<${name}(?:\\\\s[^>]*)?/>`, 'g'), `{/* Removed <${name}>: unresolved during fallback migration */}`)\n .replace(new RegExp(`<${name}(?:\\\\s[^>]*)?>[\\\\s\\\\S]*?<\\\\/${name}>`, 'g'), `{/* Removed <${name}>: unresolved during fallback migration */}`)\n }\n return result\n}\n\nexport function createComponentMigrator(siteRoot: string, confinementRoot: string, warnings: Array<MigrationWarning>, sourceIdentity: string): {\n transform: (raw: string, currentFile: string) => string\n files: () => Array<RenderedMigrationFile>\n} {\n const root = resolve(siteRoot)\n const confined = resolve(confinementRoot)\n // A destination can contain imports from several repositories with identical\n // snippet names. Stable source identity isolates their graphs without tying\n // registry names to a temporary checkout path or changing repeat imports.\n const destinationRoot = `src/mdx/migrated/${hash(sourceIdentity)}`\n const copied = new Map<string, RenderedMigrationFile>()\n const registrations = new Map<string, { path: string; imported: string }>()\n let copiedBytes = 0\n\n function warn(message: string, source: string): void {\n warnings.push({ code: 'unsupported-config', message, source: relative(root, source).replace(/\\\\/g, '/') })\n }\n\n function checkedFile(path: string): string {\n const local = relative(confined, path)\n resolveWithin(confined, local)\n let current = confined\n if (lstatSync(current).isSymbolicLink()) throw new Error('symbolic links are not imported')\n for (const segment of local.split(/[\\\\/]/)) {\n current = resolveWithin(current, segment)\n if (lstatSync(current).isSymbolicLink()) throw new Error('symbolic links are not imported')\n }\n if (!lstatSync(path).isFile()) throw new Error('dependency is not a regular file')\n return path\n }\n\n function expandCandidates(candidate: string): Array<string> {\n const candidates = [candidate]\n if (!extname(candidate)) {\n candidates.push(...['.tsx', '.jsx', '.ts', '.js', '.mjs', '.json'].map((extension) => candidate + extension))\n candidates.push(...['index.tsx', 'index.jsx', 'index.ts', 'index.js'].map((name) => resolve(candidate, name)))\n } else if (extname(candidate) === '.js') {\n candidates.push(candidate.slice(0, -3) + '.ts', candidate.slice(0, -3) + '.tsx')\n }\n return candidates\n }\n\n /**\n * `allowFlattenedMirror` gates the repository-root retry for a *plain\n * relative* specifier (`./x`, `../x`) below. It must stay narrow: a\n * relative import resolves relative to the importing file by standard\n * Node semantics, full stop — rebasing that resolution onto the\n * repository root for every project with a nested docs directory (the\n * ordinary case, not a monorepo) let a missing/broken import like\n * `./bogus` silently resolve to an unrelated same-named file that\n * happens to live at the mirrored repository-root path, instead of\n * being reported as unresolvable. The one real need for a mirror is\n * Playwright's own build (`cp -r nodejs/* .` flattens the `nodejs/`\n * project root's contents, including its shared `images/`, up into the\n * repository root before the site is generated), reached only through\n * the `require('../asset.ext')` idiom below — so only that call site\n * passes `true`. Every ordinary component/`import` resolution passes\n * `false` (the default) and never rebases.\n */\n function resolveDependency(specifier: string, importer: string, allowFlattenedMirror = false): string {\n if (specifier.includes('\\\\') || specifier.includes('\\0') || /[?#]/.test(specifier)) throw new Error('unsupported component dependency path')\n const candidates = specifier.startsWith('/')\n ? expandCandidates(resolveWithin(root, specifier.slice(1)))\n : expandCandidates(resolveWithin(confined, relative(confined, resolve(dirname(importer), specifier))))\n // A root-relative `@site/...`/`/...` specifier is Docusaurus' own alias\n // for its *project* root; when the shared component it names isn't\n // nested under the narrower detected project root, it can still be a\n // real, unambiguous repository-root path (Playwright's shared\n // `src/components` tree is a sibling of the `nodejs/` project, not\n // nested under it) — tried only after the direct, project-rooted path\n // fails. This is safe even outside a flattened-build layout: the\n // specifier itself names an absolute-from-some-root path, so the retry\n // can't be fooled into matching an unrelated file the way a *relative*\n // import's rebase (below) can.\n if (root !== confined && specifier.startsWith('/')) {\n candidates.push(...expandCandidates(resolveWithin(confined, specifier.slice(1))))\n }\n if (root !== confined && !specifier.startsWith('/') && allowFlattenedMirror) {\n try {\n const rebasedImporter = resolveWithin(confined, relative(root, importer))\n candidates.push(...expandCandidates(resolveWithin(confined, relative(confined, resolve(dirname(rebasedImporter), specifier)))))\n } catch {\n // Importer itself is outside the project root; nothing to rebase.\n }\n }\n for (const path of candidates) {\n if (existsSync(path) && lstatSync(path).isFile()) return checkedFile(path)\n }\n throw new Error(`component dependency ${specifier} was not found`)\n }\n\n function outputPath(path: string): string {\n // Must be `confined`, not `root`: a component reached via a relative\n // import from outside `root` (see `resolveDependency`) is still inside\n // `confined`, and a `../`-containing destination path would risk\n // writing outside `destinationRoot`.\n return `${destinationRoot}/source/${relative(confined, path).replace(/\\\\/g, '/')}`\n }\n\n function copyGraph(entry: string): string {\n // Stage the entire graph in memory. A missing leaf must not leave a partly\n // registered component or consume the successful-copy budget.\n const staged = new Map<string, RenderedMigrationFile>()\n let stagedBytes = 0\n /** Stage a small fixed-content shim module (see `DOCUSAURUS_THEME_SHIMS`) once, reused across every component that imports it. */\n function stageShim(filename: string, content: string): string {\n const shimDestination = `${destinationRoot}/shims/${filename}`\n if (!copied.has(shimDestination) && !staged.has(shimDestination)) staged.set(shimDestination, { path: shimDestination, content })\n return shimDestination\n }\n function visit(path: string): void {\n const destination = outputPath(path)\n if (copied.has(destination) || staged.has(destination)) return\n checkedFile(path)\n const size = lstatSync(path).size\n if (size > MAX_FILE_BYTES || copiedBytes + stagedBytes + size > MAX_COMPONENT_BYTES\n || copied.size + staged.size >= MAX_COMPONENT_FILES) throw new Error('component migration budget exceeded')\n const extension = extname(path).toLowerCase()\n if (!CODE_EXTENSIONS.has(extension) && !DATA_EXTENSIONS.has(extension)) throw new Error(`unsupported dependency file type ${extension}`)\n stagedBytes += size\n const content = readFileSync(path)\n staged.set(destination, { path: destination, content })\n if (!CODE_EXTENSIONS.has(extension)) {\n if (extension === '.css' && /@import\\b|url\\s*\\(/i.test(content.toString('utf8'))) throw new Error('CSS resource dependencies require manual migration')\n if (extension === '.css' && path.toLowerCase().endsWith('.module.css')) {\n // A parse failure here (malformed CSS, an SCSS-only construct that\n // isn't valid CSS, ...) is treated the same as any other copy\n // failure: throw, so the dead-import-removal fallback in the\n // caller can neutralize its usage instead of shipping CSS\n // Turbopack would reject anyway.\n let wrapped: string\n try {\n wrapped = wrapImpureCssModuleSelectors(content.toString('utf8'))\n } catch {\n throw new Error('CSS module could not be parsed to check for Turbopack-safe selectors')\n }\n staged.set(destination, { path: destination, content: wrapped })\n }\n return\n }\n const text = content.toString('utf8')\n const syntax = ts.transpileModule(text, { fileName: path, reportDiagnostics: true,\n compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext } })\n if (syntax.diagnostics?.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) throw new Error('component source contains unsupported JavaScript or TypeScript syntax')\n const ast = sourceFile(text, path)\n if (ast.statements.some((statement) => ts.isExpressionStatement(statement)\n && ts.isStringLiteral(statement.expression) && statement.expression.text === 'use server')) throw new Error('server-only component modules require manual migration')\n const edits: Array<Replacement> = []\n function dependency(literal: ts.StringLiteralLike, importDeclaration?: ts.ImportDeclaration): void {\n const specifier = literal.text\n if (SHARED_IMPORTS.has(specifier) || isScaffoldProvidedImport(specifier)) return\n // `@docusaurus/Link` maps onto `next/link` (already scaffold-provided)\n // rather than a shim module: same default export, only its `to` prop\n // is renamed to `href` wherever the copied file itself uses the tag.\n if (specifier === '@docusaurus/Link') {\n edits.push({ start: literal.getStart(ast), end: literal.end, value: '\"next/link\"' })\n const localName = importDeclaration?.importClause?.name?.text\n if (localName) {\n function renameToProp(node: ts.Node): void {\n if (ts.isJsxAttribute(node) && node.name.getText(ast) === 'to'\n && ts.isJsxOpeningLikeElement(node.parent.parent)\n && node.parent.parent.tagName.getText(ast) === localName) {\n edits.push({ start: node.name.getStart(ast), end: node.name.end, value: 'href' })\n }\n ts.forEachChild(node, renameToProp)\n }\n renameToProp(ast)\n }\n return\n }\n const shim = DOCUSAURUS_THEME_SHIMS[specifier]\n if (shim) {\n const shimPath = stageShim(shim.filename, shim.content)\n const nextPath = relative(dirname(destination), shimPath).replace(/\\\\/g, '/')\n edits.push({ start: literal.getStart(ast), end: literal.end, value: JSON.stringify(portableSpecifier(nextPath.startsWith('.') ? nextPath : `./${nextPath}`)) })\n return\n }\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n throw new Error(specifier.startsWith('@/')\n ? `path alias ${specifier} points to source-site code the migration does not copy`\n : `external package ${specifier} requires manual installation and review`)\n }\n const target = resolveDependency(specifier, path)\n visit(target)\n const nextPath = relative(dirname(destination), outputPath(target)).replace(/\\\\/g, '/')\n edits.push({ start: literal.getStart(ast), end: literal.end, value: JSON.stringify(portableSpecifier(nextPath.startsWith('.') ? nextPath : `./${nextPath}`)) })\n }\n function inspect(node: ts.Node): void {\n if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {\n dependency(node.moduleSpecifier, ts.isImportDeclaration(node) ? node : undefined)\n }\n if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword\n || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {\n const argument = node.arguments[0]\n if (node.arguments.length !== 1 || !argument || !ts.isStringLiteralLike(argument)) throw new Error('computed component imports require manual migration')\n dependency(argument)\n }\n ts.forEachChild(node, inspect)\n }\n inspect(ast)\n // Mark copied code as client-owned even when the source platform inferred\n // its client boundary. Browser hooks must never run in MDX's server scope.\n // The source site never ran `next build`'s full `tsc --noEmit` type\n // check (Docusaurus/Mintlify/Fern don't gate their own build on it),\n // so loose types, `window.ethereum`-style ambient globals, and\n // implicit `any` parameters that were fine there fail it here.\n // `@ts-nocheck` is valid in both `.ts(x)` and `.js(x)` files (a no-op\n // unless `checkJs` is on) and is the least invasive fix: it preserves\n // the component's real behavior instead of stripping or rewriting it.\n const replaced = applyReplacements(text, edits)\n // A `#!/...` shebang is only special on line 1 of the file (Node\n // strips it before parsing only there); inserting the `@ts-nocheck`\n // prologue above it would both break that and, since `// @ts-nocheck`\n // isn't itself a shebang, leave a dead shebang-looking comment mid\n // file. If the copied source starts with one, keep it first and\n // insert the prologue right after instead.\n const shebangMatch = /^#!.*\\r?\\n/.exec(replaced)\n const prologue = \"// @ts-nocheck\\n'use client';\\n\\n\"\n staged.set(destination, {\n path: destination,\n content: shebangMatch\n ? shebangMatch[0] + prologue + implicitReactImports(ast) + '\\n' + replaced.slice(shebangMatch[0].length)\n : prologue + implicitReactImports(ast) + '\\n' + replaced,\n })\n }\n visit(entry)\n for (const [path, file] of staged) copied.set(path, file)\n copiedBytes += stagedBytes\n return outputPath(entry)\n }\n\n /**\n * Copy a binary asset verbatim to a stable `public/` path (bypassing\n * `copyGraph`'s JS-module handling entirely — the asset is bound to its\n * URL string, never imported as a module) and return that URL. Used when\n * an import couldn't be copied as a component but names a real file the\n * page only ever references by URL (`src={Logo}`), never as a JSX tag.\n */\n function copyPublicAsset(path: string): string {\n checkedFile(path)\n const size = lstatSync(path).size\n if (size > MAX_FILE_BYTES || copiedBytes + size > MAX_COMPONENT_BYTES || copied.size >= MAX_COMPONENT_FILES) {\n throw new Error('component migration budget exceeded')\n }\n const publicName = `migrated-${hash(relative(confined, path))}${extname(path).toLowerCase()}`\n const destination = `public/${publicName}`\n if (!copied.has(destination)) {\n copied.set(destination, { path: destination, content: readFileSync(path) })\n copiedBytes += size\n }\n return `/${publicName}`\n }\n\n /**\n * Docusaurus ships SVGR out of the box, so `import Foo from './foo.svg';\n * <Foo />` renders the SVG as a real component there. The migrated\n * project has no SVGR loader, so importing an `.svg` file the ordinary\n * way (`copyGraph`'s ordinary path, used below) yields whatever the\n * bundler's default asset handling returns for it — a URL string or a\n * `{ src }` object, either way not a valid React element type — and\n * `<Foo />` throws \"Element type is invalid\" at render. Used only when\n * the import is actually rendered as a JSX tag (an attribute-only usage,\n * `src={Foo}`, needs no wrapper and is left as the plain import): stage a\n * tiny companion module next to the copied SVG that imports it as a URL\n * either way and renders a plain `<img>`, and register that instead of\n * the raw file.\n */\n function wrapSvgAsComponent(svgOutputPath: string): string {\n const wrapperPath = `${svgOutputPath}.component.tsx`\n if (!copied.has(wrapperPath)) {\n const content = [\n \"'use client'\",\n '',\n `import svgSource from ${JSON.stringify(`./${basename(svgOutputPath)}`)}`,\n '',\n 'export default function SvgImage(props: Record<string, unknown>) {',\n ' const src = typeof svgSource === \"string\" ? svgSource : (svgSource as { src: string }).src',\n ' // eslint-disable-next-line @next/next/no-img-element -- no SVGR loader is configured; this renders the raw file.',\n ' return <img src={src} alt=\"\" {...props} />',\n '}',\n '',\n ].join('\\n')\n copied.set(wrapperPath, { path: wrapperPath, content })\n }\n return wrapperPath\n }\n\n function register(path: string, imported: string): string {\n const name = `Migrated${hash(`${path}:${imported}`)}`\n registrations.set(name, { path, imported })\n return name\n }\n\n function transform(raw: string, currentFile: string): string {\n const parsedFrontmatter = parseFrontmatter(raw).content\n const frontmatter = raw.slice(0, raw.length - parsedFrontmatter.length)\n // remark-mdx does not parse a raw HTML comment (`<!-- ... -->`) at all —\n // a real source page commonly has one (Docusaurus' own\n // `<!-- prettier-ignore -->` ahead of a snippet import) and it\n // otherwise throws here before this pass ever runs, leaving whatever\n // import that comment sits near completely untouched. `normalizeMdx`\n // converts the same syntax later in the pipeline anyway, so doing it\n // here too (on this function's own working copy) is never wasted work.\n // Likewise a heading's explicit `{#custom-id}` suffix is never valid MDX\n // (a bare `{...}` in prose is always parsed as a JS expression, and no\n // JS expression starts with `#`) regardless of platform, so converting\n // it up front is always safe — and it must happen before this\n // function's own parse below, or that parse throws first and this\n // whole page's import analysis is skipped instead of just this one\n // page's expression.\n const content = normalizeExplicitHeadingIds(normalizeIndentedFences(normalizeHtmlComments(parsedFrontmatter)))\n let tree: MdxNode\n try {\n tree = parser.parse(content) as MdxNode\n } catch {\n warn('Custom component analysis could not parse this MDX; its source was preserved for manual migration.', currentFile)\n // The AST walk below is how every `@site/...`/relative component\n // import normally gets copied or removed; none of that runs on a page\n // that can't even be parsed. Left alone, an import like that survives\n // verbatim and breaks `next build` with \"Module not found\" for the\n // whole site, not just this page — the same failure mode the AST path\n // already guards against everywhere else. This is a text-only,\n // best-effort safety net (no AST here to drive a real copy), narrow by\n // design: only the single-binding default/named-as-default import\n // shape actually seen in practice, mirroring `SNIPPET_IMPORT_PATTERN`.\n return frontmatter + neutralizeUnresolvableImportsWithoutAst(content, currentFile, warn)\n }\n const aliases = new Map<string, string>()\n const unsupportedImports = new Map<string, string>()\n // Local names dropped by the lowercase-named `.mdx?` import case below\n // (Docusaurus' auto-generated per-file `toc` export, merged into\n // another page's own `toc` via `...viewsToc`) — collected here so the\n // spread-removal pass after the main walk can find every one of them,\n // regardless of which esmNode declared the import vs. used it.\n const droppedMdxDataBindings = new Set<string>()\n const edits: Array<Replacement> = []\n const declarations: Array<{ start: number; end: number; source: string }> = []\n const moduleImports: Array<string> = []\n const realPageImports: Array<string> = []\n const serverPageDeclarations: Array<string> = []\n const sharedImportEdits: Array<Replacement> = []\n let hasUnsupportedImports = false\n function hasExpressionReference(names: Set<string>, options: {\n excludedNodes?: Array<MdxNode>\n includeDeclarations?: boolean\n includeDirectTags?: boolean\n } = {}): boolean {\n let found = false\n function inspect(node: ts.Node): void {\n if (ts.isIdentifier(node) && names.has(node.text)) found = true\n ts.forEachChild(node, inspect)\n }\n walk(tree, (node) => {\n if (options.excludedNodes?.some((excluded) => node.position?.start.offset !== undefined\n && node.position.end.offset !== undefined\n && node.position.start.offset >= excluded.position!.start.offset!\n && node.position.end.offset <= excluded.position!.end.offset!)) return\n if (node.name && [...names].some((name) => node.name!.startsWith(`${name}.`)\n || (options.includeDirectTags && node.name === name))) found = true\n if (options.includeDeclarations !== false && node.type === 'mdxjsEsm' && node.value) {\n for (const statement of sourceFile(node.value, 'expression.tsx').statements) {\n if (!ts.isImportDeclaration(statement)) inspect(statement)\n }\n }\n const expressions = [\n ...(['mdxFlowExpression', 'mdxTextExpression'].includes(node.type) ? [node.value ?? ''] : []),\n ...(node.attributes ?? []).flatMap((attribute) => {\n if (attribute.type === 'mdxJsxExpressionAttribute' && typeof attribute.value === 'string') return [attribute.value]\n return attribute.value && typeof attribute.value === 'object' ? [attribute.value.value ?? ''] : []\n }),\n ]\n for (const expression of expressions) inspect(sourceFile(expression, 'expression.tsx'))\n })\n return found\n }\n /** True when `name` is ever a JSX tag's own root name (`<name ...>`), regardless of any other usage — narrower than `hasExpressionReference`'s combined signal, needed where a string binding (an asset's URL) is fine for any *other* usage but not this one. */\n function usedAsJsxTagName(name: string): boolean {\n let found = false\n walk(tree, (node) => { if (node.name === name) found = true })\n return found\n }\n // Docusaurus allows a real `import`/`export` ESM block anywhere in the\n // body, not just at the top of the file — a documentation page\n // demonstrating a live code example commonly nests one inside a JSX\n // wrapper (`<BrowserWindow>\\nimport Foo from './foo.svg'\\n\\n<Foo\n // /></BrowserWindow>`, straight from Docusaurus' own docs). remark-mdx\n // still parses each as its own `mdxjsEsm` node, just nested under that\n // wrapper's `children` instead of `tree.children` directly, so this\n // must walk the whole tree to find every one of them; a scan of only\n // `tree.children` silently skips a nested import, leaving the page\n // referencing a path the migrated project never has (\"Module not\n // found\") without any warning at all.\n const esmNodes: Array<MdxNode> = []\n walk(tree, (node) => { if (node.type === 'mdxjsEsm') esmNodes.push(node) })\n for (const node of esmNodes) {\n if (node.value === undefined || node.position?.start.offset === undefined) continue\n const ast = sourceFile(node.value, 'inline.tsx')\n for (const statement of ast.statements) {\n if (!ts.isImportDeclaration(statement)) {\n let unsupportedDependency = ts.isExportDeclaration(statement) && !!statement.moduleSpecifier\n function inspect(node: ts.Node): void {\n if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword\n || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) unsupportedDependency = true\n ts.forEachChild(node, inspect)\n }\n inspect(statement)\n if (unsupportedDependency) {\n hasUnsupportedImports = true\n warn('Inline MDX module dependencies require manual extraction; source was preserved.', currentFile)\n }\n declarations.push({\n start: node.position.start.offset + statement.getStart(ast),\n end: node.position.start.offset + statement.end,\n source: statement.getText(ast),\n })\n continue\n }\n const bindings = imports(statement)\n const rawSpecifier = ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : ''\n // `@site/...` is Docusaurus' and Mintlify's shared alias for the\n // project root; treat it exactly like the root-relative `/...` form\n // `resolveDependency` already understands, so a locally-owned\n // component copies the same way a relative import would.\n const specifier = rawSpecifier.startsWith('@site/') ? `/${rawSpecifier.slice('@site/'.length)}` : rawSpecifier\n if (isScaffoldProvidedImport(specifier)) {\n // Some translated Mintlify pages place a React hook import above a\n // fenced example. Keeping that unused import turns server MDX into\n // a module that illegally imports a client-only hook.\n if (specifier === 'react' && bindings.length > 0\n && bindings.every((binding) => REACT_GLOBALS.has(binding.imported))\n && !hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n continue\n }\n // Installed in the migrated project: keep it on the page (content\n // outside an extracted block may use it) and copy it into any\n // extracted client module, whose moved declarations may use it too.\n moduleImports.push(statement.getText(ast))\n continue\n }\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n if (SHARED_IMPORTS.has(specifier)) {\n const isUnusedReactHookImport = specifier === 'react' && bindings.length > 0\n && bindings.every((binding) => REACT_GLOBALS.has(binding.imported))\n && !hasExpressionReference(new Set(bindings.map((binding) => binding.local)))\n if (!isUnusedReactHookImport) moduleImports.push(statement.getText(ast))\n // A shared React import is normally retained in server MDX. An\n // unused hook import belongs only to a fenced example and would\n // cause Next's server-component build to reject the whole page.\n if (isUnusedReactHookImport) edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n else sharedImportEdits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } else if (specifier.startsWith('@theme/') || specifier.startsWith('@docusaurus/')) {\n // Docusaurus' own theme/runtime components (Tabs, TabItem, Link,\n // useBaseUrl, ...) are converted to Thally's equivalents by\n // normalizeMdx right after this pass; just drop the now-redundant\n // import and leave JSX usage untouched for that pass to rewrite.\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } else if (hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n // Only JSX usage (`<Widget />`) is rewritten below; a reference\n // in `{pkg.fn()}`, a prop, or an inline `export const` cannot be\n // rewritten the same way. Dropping the import would leave an\n // undefined identifier; keeping it imports a package that is not\n // installed in the migrated project, which fails `next build`\n // for the *whole* site with \"Module not found\" — not just this\n // page. Excluding the page is the only option that keeps the\n // rest of the site building; `pruneMissingNavigationPages` (see\n // repository.ts) then drops it from navigation too.\n warnings.push({\n code: 'skipped-file',\n message: `This page was excluded because it uses '${bindings.map((binding) => binding.local).join(', ')}' from ${unavailableImportLabel(rawSpecifier)} outside JSX (in an expression, prop, or inline declaration), and that import isn't available in the migrated project. Make '${rawSpecifier}' available and add the import back manually, or rewrite the page to avoid it.`,\n source: relative(root, currentFile).replace(/\\\\/g, '/'),\n })\n hasUnsupportedImports = true\n } else {\n // An npm package Thally's runtime does not ship is not installed\n // in the migrated project; leaving the import in place breaks\n // `next build` with \"Module not found\". Drop the import and\n // replace its JSX usage with a safe fallback instead (see the\n // `unsupportedImports` walk below) rather than shipping a page\n // that cannot compile.\n warn(`MDX import of ${unavailableImportLabel(rawSpecifier)} is not available in the migrated project; the import was removed and its usage replaced.`, currentFile)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n for (const binding of bindings) unsupportedImports.set(binding.local, rawSpecifier)\n }\n continue\n }\n if (/\\.mdx?$/.test(specifier)) {\n // A capitalized default/named import here is a JSX-usable\n // partial (`import Partial from './x.mdx'`, `<Partial />`) — the\n // earlier text-level snippet-inlining pass (`inlineMdxSnippets`,\n // repository.ts) already resolved and removed those before this\n // AST walk ever runs, so reaching this point with only lowercase\n // bindings means every one is a plain named value that pass\n // can't touch: Docusaurus' own convention of auto-generating a\n // `toc` export per `.mdx` file, commonly re-exported by spreading\n // it into another page's `toc` (`export const toc = [...viewsToc,\n // ...]`). The migrated project has no such module to import from\n // (\"Module not found\"), and no way to compute the value, so the\n // import and that one safe, common usage shape are both removed;\n // anything shaped differently is left for the npm-style\n // expression-reference check below to exclude the page instead of\n // guessing at a replacement.\n if (bindings.length > 0 && bindings.every((binding) => !/^[A-Z]/.test(binding.local))) {\n warn(`MDX named import of ${JSON.stringify(rawSpecifier)} isn't a component and has no equivalent in the migrated site (for example Docusaurus's generated 'toc' export), so it was removed, along with any '...${bindings.map((binding) => binding.local).join(\", '...\")}' spread of it.`, currentFile)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n for (const binding of bindings) droppedMdxDataBindings.add(binding.local)\n }\n continue\n }\n // A binary asset (`docusaurusLogo.svg`, a `.docx` handout, ...) is\n // never really \"a component\" — it's fine bound to any identifier\n // shape and referenced from an expression (`src={docusaurusLogo}`),\n // unlike the component-alias mechanism below, which can only\n // rewrite a literal JSX tag name, not an arbitrary expression\n // reference. Handle it before the component-shaped checks reject it\n // for the wrong reason (a lowercase local name, expression usage)\n // and leave a dead import behind. Only bail out of this path (to\n // the ordinary handling below, which removes the import either way)\n // when the same local name is *also* used as a JSX tag — a string\n // URL bound there would throw just as hard as the missing import.\n if (bindings.length && RESCUABLE_ASSET_EXTENSIONS.has(extname(specifier).toLowerCase())\n && !bindings.some((binding) => usedAsJsxTagName(binding.local))) {\n try {\n const href = copyPublicAsset(resolveDependency(specifier, currentFile))\n edits.push({\n start: node.position.start.offset + statement.getStart(ast),\n end: node.position.start.offset + statement.end,\n // `export`, not a bare `const`: this replaces an `import`\n // statement in place, and the final MDX compile (a fresh\n // parse of this text, not a reuse of this pass's own AST)\n // only recognizes a top-level JS block as ESM — evaluated and\n // its bindings put in scope — when it starts with `import` or\n // `export`. A bare `const` there is just prose to that parser\n // and renders as literal paragraph text instead, leaving\n // every reference to this binding a `ReferenceError` at\n // render (reproduced against hasura/graphql-engine's\n // databases/overview.mdx, which binds asset URLs this way).\n value: bindings.map((binding) => `export const ${binding.local} = ${JSON.stringify(href)};`).join('\\n'),\n })\n warn(`Asset import ${JSON.stringify(rawSpecifier)} was copied to ${href} and bound to that URL instead of importing it as a component.`, currentFile)\n continue\n } catch {\n // Not actually resolvable/copyable (missing file, budget) —\n // fall through to the ordinary handling below.\n }\n }\n if (!bindings.length || (statement.importClause?.namedBindings && ts.isNamespaceImport(statement.importClause.namedBindings))) {\n warn('Namespace or side-effect MDX imports require manual registration; the import was preserved.', currentFile)\n hasUnsupportedImports = true\n continue\n }\n // Unlike the unavailable-npm-package case above, a local/relative\n // import is fully owned by the migration: `copyGraph` below moves\n // the whole file (and its own local dependency graph) into the\n // project, and the statement it emits keeps every binding's original\n // local name (`as ${binding.local}`) — only the module specifier\n // changes. Nothing in the page body needs renaming, so it makes no\n // difference whether a binding is used as a bare JSX tag or only\n // referenced elsewhere (an enum member on a sibling prop, a member\n // tag, a wrapping declaration, ...): the copy is attempted either\n // way, and the page is excluded only if that copy genuinely fails\n // (an unsupported dependency inside the local graph — see the catch\n // below), not merely because of how the binding is used.\n try {\n const sourcePath = resolveDependency(specifier, currentFile)\n const path = copyGraph(sourcePath)\n const isSvgUsedAsTag = extname(path).toLowerCase() === '.svg' && bindings.some((binding) => usedAsJsxTagName(binding.local))\n for (const binding of bindings) {\n const registerPath = isSvgUsedAsTag ? wrapSvgAsComponent(path) : path\n const registerImported = isSvgUsedAsTag ? 'default' : binding.imported\n // MDX's own component-injection pass (recma-jsx-rewrite) only\n // rewrites a JSX tag it finds as a genuine, direct mdast JSX\n // node (`<Foo>` as its own markdown/JSX child) to pull from the\n // shared `_components` scope (the customComponents registry\n // below) — the alias-rename walk further down can likewise only\n // text-replace that same direct form. Any other shape —\n // `Capability.ToolUse` in a sibling prop's object literal,\n // `<Widget />` nested inside a `{...}` expression or an\n // `export const` declaration, a member tag `<Widget.Item />`,\n // a plain value passed as a prop (`as={Widget}`) — is invisible\n // to both, and registering it under an aliased key would leave\n // the literal reference an unresolved free variable\n // (`ReferenceError` at render; reproduced against a real\n // Cohere build for both an enum-in-a-prop and a component\n // nested in a `.map()` callback). Give any such binding a real\n // import instead, keeping its original local name and using the\n // project's `@/` alias so the specifier resolves regardless of\n // where the generated runtime module that embeds this page\n // ends up on disk.\n if (!isSvgUsedAsTag && hasExpressionReference(new Set([binding.local]))) {\n const helper = staticServerHelper(sourcePath, binding.imported, binding.local)\n if (helper) {\n serverPageDeclarations.push(helper)\n continue\n }\n const aliasSpecifier = portableSpecifier(`@/${registerPath.replace(/^src\\//, '').replace(/\\\\/g, '/')}`)\n realPageImports.push(`import { ${registerImported} as ${binding.local} } from ${JSON.stringify(aliasSpecifier)};`)\n continue\n }\n const name = register(registerPath, registerImported)\n aliases.set(binding.local, name)\n moduleImports.push(`import { ${registerImported} as ${binding.local} } from ${JSON.stringify(portableSpecifier(`./${relative(destinationRoot, registerPath).replace(/\\\\/g, '/')}`))};`)\n }\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } catch (error) {\n if (hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n warnings.push({\n code: 'skipped-file',\n message: `This page was excluded because local import ${JSON.stringify(rawSpecifier)} could not be copied and is used in an expression: ${error instanceof Error ? error.message : 'unsupported dependency'}.`,\n source: relative(root, currentFile).replace(/\\\\/g, '/'),\n })\n hasUnsupportedImports = true\n continue\n }\n const failedPackage = error instanceof Error\n ? error.message.match(/^external package (\\S+) requires manual installation and review$/)?.[1]\n : undefined\n if (failedPackage && YOUTUBE_ID_PACKAGES.has(failedPackage)) {\n // The local wrapper's own body just re-exports a known\n // YouTube-embed package one level down (Playwright's\n // `LiteYouTube` wraps `react-lite-youtube-embed` this way); the\n // wrapper itself can't be copied, but its usage is id-prop-shaped\n // exactly like a direct import of that package, so the same\n // working `<iframe>` fallback below applies instead of losing\n // the embed to the generic unknown-component neutralization.\n for (const binding of bindings) unsupportedImports.set(binding.local, failedPackage)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n continue\n }\n hasUnsupportedImports = true\n const importStart = node.position.start.offset + statement.getStart(ast)\n const importEnd = node.position.start.offset + statement.end\n // The component itself couldn't be copied (unsupported syntax, a\n // budget limit, a missing file, ...). Leaving the import in place\n // referenced a module that will never exist in the migrated\n // project, which fails `next build` for the *whole* site with\n // \"Module not found\" — not just this page (the same reasoning as\n // the unsupported-npm-import case above). Remove it. Its bindings\n // are known to be used only as JSX tags here (any expression/prop\n // usage already excluded this import from reaching this try, via\n // the `hasExpressionReference` check above), so a plain-page\n // rescan (`replaceUnknownComponents`, mdx.ts, run by repository.ts\n // after this transform) will find each now-undeclared tag and\n // neutralize it (a paired tag keeps its children in a `<div>`; a\n // self-closing one is removed) rather than leave a dangling\n // reference.\n let rescuedAssetHref: string | undefined\n if (RESCUABLE_ASSET_EXTENSIONS.has(extname(specifier).toLowerCase())) {\n // Only worth rescuing as a URL string when nothing ever renders\n // it as a JSX tag (`<Logo />`) — a string bound to a component\n // reference would throw just as hard as the missing import did.\n const usedAsJsxTag = bindings.some((binding) => hasExpressionReference(new Set([binding.local]), { includeDirectTags: true }))\n if (!usedAsJsxTag) {\n try {\n rescuedAssetHref = copyPublicAsset(resolveDependency(specifier, currentFile))\n } catch {\n rescuedAssetHref = undefined\n }\n }\n }\n if (rescuedAssetHref !== undefined) {\n edits.push({\n start: importStart,\n end: importEnd,\n // See the identical `export const` note on the other asset\n // rescue above — same reason.\n value: bindings.map((binding) => `export const ${binding.local} = ${JSON.stringify(rescuedAssetHref)};`).join('\\n'),\n })\n warn(`Asset import ${JSON.stringify(rawSpecifier)} could not be copied as a component; it was copied to ${rescuedAssetHref} and bound to that URL instead.`, currentFile)\n } else {\n edits.push({ start: importStart, end: importEnd, value: '' })\n warn(`Component import ${JSON.stringify(rawSpecifier)} could not be copied and was removed: ${error instanceof Error ? error.message : 'unsupported dependency'}. Its usage on this page was neutralized.`, currentFile)\n }\n }\n }\n }\n\n // Remove every `...name` spread of a dropped MDX data import (see the\n // lowercase-binding `.mdx?` case above) from any array literal it\n // appears in, so the export that merges it (`export const toc =\n // [...viewsToc, ...]`) stays valid instead of throwing on the now-\n // undefined identifier. Only the spread element itself is touched\n // (plus one adjacent comma, so the array literal it lived in stays\n // syntactically valid); a bare reference to the same name elsewhere is\n // intentionally left alone for `hasExpressionReference`'s excluded-page\n // path elsewhere in this function to catch instead of guessing at it.\n if (droppedMdxDataBindings.size > 0) {\n for (const node of esmNodes) {\n if (node.value === undefined || node.position?.start.offset === undefined) continue\n const nodeStart = node.position.start.offset\n const nodeText = node.value\n const ast = sourceFile(nodeText, 'inline.tsx')\n function stripDroppedSpreads(inner: ts.Node): void {\n if (ts.isSpreadElement(inner) && ts.isIdentifier(inner.expression) && droppedMdxDataBindings.has(inner.expression.text)) {\n const start = nodeStart + inner.getStart(ast)\n let end = nodeStart + inner.end\n const following = nodeText.slice(inner.end).match(/^\\s*,/)\n if (following) end += following[0].length\n edits.push({ start, end, value: '' })\n return\n }\n ts.forEachChild(inner, stripDroppedSpreads)\n }\n for (const statement of ast.statements) stripDroppedSpreads(statement)\n }\n }\n\n // Docusaurus' own docs teach `require('./relative/asset.ext').default`\n // as the idiom for linking a JSX attribute (`href={...}`) straight to a\n // static asset — real, working MDX on the source site, but a dangling\n // `require()` of a path the migrated project never has once copied\n // verbatim (\"Module not found\" at build time). Only a JSX *attribute*\n // expression is handled here (`mdxFlowExpression`/`mdxTextExpression`\n // bodies never hit this shape in practice and the ESM-import loop above\n // already covers a bare top-level `require()`); each attribute's own\n // `position` bounds the replacement to just that attribute's text, so\n // this can never match the identical-looking call inside a *fenced code\n // example* documenting the very same idiom (a real risk here, since\n // Docusaurus' own assets.mdx page shows both side by side).\n walk(tree, (node) => {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== 'mdxJsxAttribute' || !attribute.value || typeof attribute.value !== 'object') continue\n const start = attribute.position?.start.offset\n const end = attribute.position?.end.offset\n if (start === undefined || end === undefined) continue\n const attributeText = content.slice(start, end)\n const match = attributeText.match(/require\\(\\s*(['\"])((?:\\.\\.?\\/|\\/|@site\\/)[^'\"]+?\\.(?:svg|png|jpe?g|webp|gif|avif|ico|docx|pdf))\\1\\s*\\)(?:\\.default|\\.src)?/)\n if (!match || match.index === undefined) continue\n try {\n const specifier = match[2]\n const normalized = specifier.startsWith('@site/') ? `/${specifier.slice('@site/'.length)}` : specifier\n // `true`: this is exactly the Playwright `require('../images/...')`\n // idiom (a page under a flattened project root reaching a shared\n // asset that only exists at the mirrored repository-root path) —\n // see `resolveDependency`'s `allowFlattenedMirror` doc.\n const resolvedPath = normalized.startsWith('/') ? resolveWithin(root, normalized.slice(1)) : resolveDependency(normalized, currentFile, true)\n const href = copyPublicAsset(resolvedPath)\n const replaced = attributeText.slice(0, match.index) + JSON.stringify(href) + attributeText.slice(match.index + match[0].length)\n edits.push({ start, end, value: replaced })\n } catch {\n // Not actually resolvable/copyable, even after the repository-root\n // fallback above. Leaving the dangling `require()` in place would\n // break the whole site's build (\"Module not found\"), so replace it\n // with an empty string (a broken image is degraded, not fatal) and\n // warn instead.\n const replaced = attributeText.slice(0, match.index) + JSON.stringify('') + attributeText.slice(match.index + match[0].length)\n edits.push({ start, end, value: replaced })\n warn(`Asset require(${JSON.stringify(match[2])}) could not be resolved and was removed; the reference was replaced with an empty string.`, currentFile)\n }\n }\n })\n\n // A page-local declaration (not imported) that uses a hook or an event\n // handler must move to the client module along with its invocation: left\n // inline, it compiles into the page's own server-rendered module, where\n // `useState` and friends are never in scope (see `implicitReactImports`,\n // only applied to extracted client files).\n const statefulDeclarationNames = new Set(\n declarations\n .filter(({ source }) => /\\bon[A-Z]\\w*\\s*=|\\buse[A-Z]\\w*\\s*\\(/.test(source))\n .map(({ source }) => source.match(/^export const (\\w+)/)?.[1])\n .filter((name): name is string => !!name),\n )\n\n // Extract whole HTML JSX roots with event handlers. Markdown and global\n // built-ins remain server-rendered; React functions stay inside the client\n // module, so no function is serialized across a server/client boundary.\n const extracted: Array<{ node: MdxNode; name: string; jsx: string }> = []\n for (const candidate of tree.children ?? []) {\n const node = candidate.type === 'paragraph' && candidate.children?.length === 1 ? candidate.children[0] : candidate\n if (!['mdxJsxFlowElement', 'mdxJsxTextElement'].includes(node.type) || node.position?.start.offset === undefined || node.position.end.offset === undefined) continue\n let interactive = statefulDeclarationNames.has(node.name ?? '')\n let supported = true\n walk(node, (child) => {\n if (child.attributes?.some((attribute) => /^on[A-Z]/.test(attribute.name ?? ''))) interactive = true\n if (child.name && /^[A-Z]/.test(child.name) && !aliases.has(child.name) && !statefulDeclarationNames.has(child.name)) supported = false\n if (!['mdxJsxFlowElement', 'mdxJsxTextElement', 'mdxFlowExpression', 'mdxTextExpression', 'text', 'paragraph'].includes(child.type)) supported = false\n })\n if (!interactive) continue\n if (!supported || hasUnsupportedImports) {\n warn('Interactive MDX containing Markdown or unregistered components requires manual extraction; source was preserved.', currentFile)\n continue\n }\n const jsx = content.slice(node.position.start.offset, node.position.end.offset)\n // The JSX compiler is the final syntax gate: Markdown embedded in JSX\n // must not accidentally become JavaScript in the generated module.\n const result = ts.transpileModule(`export default function Inline() { return (${jsx}); }`, {\n fileName: 'inline.jsx', compilerOptions: { jsx: ts.JsxEmit.Preserve }, reportDiagnostics: true,\n })\n if (result.diagnostics?.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) {\n warn('Interactive MDX could not be safely extracted as JSX; source was preserved.', currentFile)\n continue\n }\n extracted.push({ node, name: `Inline${extracted.length}`, jsx })\n }\n if (extracted.length && declarations.length) {\n const declared = new Set<string>()\n function bind(name: ts.BindingName): void {\n if (ts.isIdentifier(name)) declared.add(name.text)\n else for (const element of name.elements) if (ts.isBindingElement(element)) bind(element.name)\n }\n for (const declaration of declarations) {\n for (const statement of sourceFile(declaration.source, 'declaration.tsx').statements) {\n if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) declared.add(statement.name.text)\n if (ts.isVariableStatement(statement)) for (const variable of statement.declarationList.declarations) bind(variable.name)\n }\n }\n const hasSharedDeclarations = hasExpressionReference(declared, {\n excludedNodes: extracted.map((entry) => entry.node),\n includeDeclarations: false,\n includeDirectTags: true,\n })\n if (hasSharedDeclarations) {\n warn('Interactive MDX shares declarations with remaining page content; source was preserved for manual extraction.', currentFile)\n extracted.length = 0\n }\n }\n if (extracted.length && (copied.size >= MAX_COMPONENT_FILES\n || Buffer.byteLength(content) > MAX_FILE_BYTES\n || copiedBytes + Buffer.byteLength(content) > MAX_COMPONENT_BYTES)) {\n warn('Interactive MDX exceeded the component migration budget; source was preserved.', currentFile)\n extracted.length = 0\n }\n if (extracted.length) {\n const path = `${destinationRoot}/inline-${hash(relative(root, currentFile))}.jsx`\n let declarationSource = [...new Set(declarations.map((entry) => entry.source))].join('\\n\\n')\n // Mintlify exposes this DOM id as its documented search trigger. Thally\n // opens search through the same keyboard event handled by CommandSearch.\n declarationSource = declarationSource.replace(/document\\.getElementById\\(\\s*(['\"])search-bar-entry\\1\\s*\\)\\.click\\(\\s*\\)/g,\n `document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', ctrlKey: true, bubbles: true }))`)\n const inlineSource = [\n ...moduleImports, '', declarationSource, '',\n ...extracted.map(({ name, jsx }) => `export function ${name}() {\\n return (${jsx});\\n}`), '',\n ].join('\\n')\n // A single leading directive: `inlineSource` no longer carries its own,\n // or Next rejects the file (\"use client\" must be the first statement).\n copied.set(path, { path, content: `'use client';\\n${implicitReactImports(sourceFile(inlineSource, 'inline.jsx'))}\\n${inlineSource}` })\n copiedBytes += Buffer.byteLength(inlineSource)\n for (const { node, name } of extracted) {\n edits.push({ start: node.position!.start.offset!, end: node.position!.end.offset!, value: `<${register(path, name)} />` })\n }\n edits.push(...declarations.map(({ start, end }) => ({ start, end, value: '' })), ...sharedImportEdits)\n }\n // A page-local callback cannot cross into a copied client component. Move\n // a self-contained JSX callback into a thin client adapter while keeping\n // the MDX children on the page. More complex callbacks remain passive.\n const pageFunctions = functionDeclaredNames(content)\n const passiveRoots: Array<MdxNode> = []\n const wrappedRoots = new Set<MdxNode>()\n walk(tree, (node) => {\n if (!node.name || !aliases.has(node.name) || !functionValuedAttribute(node, pageFunctions)\n || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n if (passiveRoots.some((root) => node.position!.start.offset! >= root.position!.start.offset!\n && node.position!.end.offset! <= root.position!.end.offset!)) return\n const functionAttributes = (node.attributes ?? []).filter((attribute) => {\n const value = attribute.value && typeof attribute.value === 'object' ? attribute.value.value?.trim() : undefined\n return !!value && pageFunctions.has(value)\n })\n if (functionAttributes.length === 1 && functionAttributes[0].name\n && functionAttributes[0].position?.start.offset !== undefined\n && functionAttributes[0].position.end.offset !== undefined) {\n const functionName = (functionAttributes[0].value as { value: string }).value.trim()\n const declaration = declarations.find((entry) => new RegExp(`^export const ${functionName}\\\\s*=`).test(entry.source))\n const safeDeclaration = declaration?.source.match(/^export const \\w+\\s*=\\s*\\(\\s*\\{\\s*children(?:\\s*,\\s*\\.\\.\\.props)?\\s*\\}\\s*\\)\\s*=>\\s*\\([\\s\\S]*\\)\\s*;?$/)\n && !/\\b(?:window|document|process|fetch|use[A-Z]\\w*)\\b/.test(declaration.source)\n && [...declaration.source.matchAll(/<([A-Z]\\w*)\\b/g)].every((match) => match[1] === 'CodeBlock')\n && [...declaration.source.matchAll(/\\{([^{}]*)\\}/g)].every((match) =>\n ['children', '...props', 'children, ...props'].includes(match[1].trim()))\n const binding = registrations.get(aliases.get(node.name)!)\n if (safeDeclaration && binding) {\n const fallbackDeclaration = declaration!.source.replace(/<CodeBlock\\b[^>]*>/g, '<pre><code>').replace(/<\\/CodeBlock>/g, '</code></pre>')\n const wrapperPath = `${destinationRoot}/callback-${hash(`${currentFile}:${node.position.start.offset}`)}.jsx`\n const imported = binding.imported === 'default' ? 'default' : binding.imported\n const importClause = imported === 'default' ? 'import Original' : `import { ${imported} as Original }`\n const specifier = portableSpecifier(`./${relative(destinationRoot, binding.path).replace(/\\\\/g, '/')}`)\n const wrapperName = register(wrapperPath, 'CallbackWrapper')\n copied.set(wrapperPath, { path: wrapperPath, content: [\n \"'use client';\", `${importClause} from ${JSON.stringify(specifier)};`,\n fallbackDeclaration,\n `export function CallbackWrapper({ children, ...props }) { return <Original {...props} ${functionAttributes[0].name}={${functionName}}>{children}</Original>; }`,\n ].join('\\n') })\n const start = node.position.start.offset\n const end = node.position.end.offset\n const source = content.slice(start, end)\n const opening = source.indexOf(`<${node.name}`)\n const closing = source.lastIndexOf(`</${node.name}`)\n if (opening >= 0) edits.push({ start: start + opening + 1, end: start + opening + 1 + node.name.length, value: wrapperName })\n if (closing >= 0) edits.push({ start: start + closing + 2, end: start + closing + 2 + node.name.length, value: wrapperName })\n edits.push({ start: functionAttributes[0].position!.start.offset!, end: functionAttributes[0].position!.end.offset!, value: '' })\n wrappedRoots.add(node)\n if (declaration!.source.includes('<CodeBlock')) warn(`Interactive <${node.name}> was retained with a basic code block in place of Mintlify's CodeBlock.`, currentFile)\n return\n }\n }\n const source = content.slice(node.position.start.offset, node.position.end.offset)\n const openingEnd = source.indexOf('>')\n const closingStart = source.lastIndexOf(`</${node.name}`)\n const children = openingEnd >= 0 && closingStart > openingEnd ? source.slice(openingEnd + 1, closingStart) : ''\n edits.push({ start: node.position.start.offset, end: node.position.end.offset,\n value: `<div data-migration-interactive-fallback=\"${node.name}\">${children}</div>` })\n passiveRoots.push(node)\n warn(`Interactive <${node.name}> passes a page-local function into a client component; its child content was retained without the interactive control. Move the callback into a client component to restore it.`, currentFile)\n })\n walk(tree, (node) => {\n const replacement = node.name ? aliases.get(node.name) : undefined\n if (!replacement || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n if (wrappedRoots.has(node)) return\n if (passiveRoots.some((root) => node.position!.start.offset! >= root.position!.start.offset!\n && node.position!.end.offset! <= root.position!.end.offset!)) return\n const start = node.position.start.offset\n const end = node.position.end.offset\n if (extracted.some((item) => start >= item.node.position!.start.offset! && end <= item.node.position!.end.offset!)) return\n const text = content.slice(start, end)\n const opening = text.indexOf(`<${node.name}`)\n if (opening >= 0) edits.push({ start: start + opening + 1, end: start + opening + 1 + node.name!.length, value: replacement })\n const closing = text.lastIndexOf(`</${node.name}`)\n if (closing >= 0) edits.push({ start: start + closing + 2, end: start + closing + 2 + node.name!.length, value: replacement })\n })\n // Every usage of a removed npm-package import is replaced whole (tag,\n // props, and children) rather than just its name: nothing in the\n // migrated project can render it. A video-embed-shaped usage (an `id`\n // prop, a name suggesting an embedded player) gets a trivial working\n // `<iframe>`; anything else becomes a visible, greppable MDX comment.\n walk(tree, (node) => {\n const specifier = node.name ? unsupportedImports.get(node.name) : undefined\n if (!specifier || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n const start = node.position.start.offset\n const end = node.position.end.offset\n const videoId = youtubeEmbedVideoId(node, specifier)\n const value = videoId\n ? `<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${videoId}\" title=\"Embedded video\" allowFullScreen />`\n : `{/* Removed <${node.name}>: unsupported import '${specifier}' */}`\n edits.push({ start, end, value })\n })\n const rendered = applyReplacements(content, edits)\n // Inserted after all offset-based edits (it has no position in the\n // original source) so it lands once, at the very top of the body.\n const pageStatements = [...new Set([...realPageImports, ...serverPageDeclarations])]\n const realImportsBlock = pageStatements.length ? `${pageStatements.join('\\n')}\\n\\n` : ''\n return frontmatter + realImportsBlock + rendered\n }\n\n function files(): Array<RenderedMigrationFile> {\n // A rescued asset (`copyPublicAsset`) lands in `copied` without ever\n // registering a component; it still needs emitting even when nothing\n // was registered.\n if (!copied.size) return []\n if (!registrations.size) return [...copied.values()]\n const entries = [...registrations.entries()].sort(([a], [b]) => a.localeCompare(b))\n return [...copied.values(), {\n path: 'src/mdx/custom-components.tsx',\n content: [\n '/** Repository components preserved by migration; this registry is customer-owned. */',\n \"import type { MDXComponents } from 'mdx/types'\", ...entries.map(([name, binding]) => {\n const path = portableSpecifier(`./${relative('src/mdx', binding.path).replace(/\\\\/g, '/')}`)\n return `import { ${binding.imported} as ${name} } from ${JSON.stringify(path)}`\n }), '',\n // Not every registered local binding is JSX-taggable — a companion\n // value from the same import (an enum used only as `Foo.Bar` inside\n // another component's prop, e.g.) is registered too, so the whole\n // MDX scope resolves it. `MDXComponents`' index signature expects a\n // component at every key, which such a value structurally is not;\n // cast rather than exclude it, since excluding it would leave a\n // dangling reference in the page that DOES need it.\n 'export const customComponents = {',\n ...entries.map(([name]) => ` ${name},`), '} as unknown as MDXComponents', '',\n ].join('\\n'),\n }]\n }\n return { transform, files }\n}\n\n/** Preserve an authored component registry while adding an isolated import map. */\nexport function mergeComponentRegistry(existing: string, incoming: string): Array<RenderedMigrationFile> {\n const fingerprint = hash(incoming)\n const name = `MigratedRegistry${fingerprint}`\n const registryPath = `./migrated-components-${fingerprint}`\n const source = sourceFile(existing, 'custom-components.tsx')\n const alreadyImported = source.statements.some((statement) => ts.isImportDeclaration(statement)\n && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === registryPath)\n let initializer: ts.Expression | undefined\n for (const statement of source.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === 'customComponents') initializer = declaration.initializer\n }\n }\n while (initializer && (ts.isAsExpression(initializer) || ts.isSatisfiesExpression(initializer) || ts.isParenthesizedExpression(initializer))) initializer = initializer.expression\n if (!initializer || !ts.isObjectLiteralExpression(initializer)) {\n throw new Error('Cannot safely merge src/mdx/custom-components.tsx: export customComponents as an object literal before importing components. The existing registry was preserved.')\n }\n const content = alreadyImported ? existing : applyReplacements(existing, [\n { start: source.statements.filter((statement) => ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)).at(-1)?.end ?? 0,\n end: source.statements.filter((statement) => ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)).at(-1)?.end ?? 0,\n value: `\\nimport { customComponents as ${name} } from ${JSON.stringify(registryPath)}\\n` },\n { start: initializer.getStart(source) + 1, end: initializer.getStart(source) + 1, value: `\\n ...${name},` },\n ])\n return [\n { path: `src/mdx/migrated-components-${fingerprint}.tsx`, content: incoming },\n { path: 'src/mdx/custom-components.tsx', content },\n ]\n}\n","/**\n * The one frontmatter parser for authored content in this package.\n *\n * Only YAML is supported. Parsing delimiters locally keeps legacy JavaScript\n * engines out of migration processes and treats language-tagged blocks as\n * opaque metadata rather than executable third-party input.\n *\n * Internal module — deliberately not part of the package's public API. The\n * app-side original is `src/lib/frontmatter.ts`; the packages keep their own\n * copies because they cannot import from the app.\n */\n\nimport { parse as parseYaml } from 'yaml'\n\ninterface ParsedFrontmatter {\n content: string\n data: Record<string, unknown>\n /** Set when the frontmatter block was invalid YAML; `data` is a best-effort salvage. */\n error?: string\n}\n\n/**\n * Best-effort recovery for frontmatter that failed to parse as a whole block:\n * try each top-level `key: value` line on its own. A line that is itself\n * invalid YAML (e.g. an unescaped reserved character) is skipped rather than\n * aborting the whole page.\n */\nfunction salvageFrontmatterLines(matter: string): Record<string, unknown> {\n const data: Record<string, unknown> = {}\n for (const line of matter.split(/\\r?\\n/)) {\n if (!/^[A-Za-z_][\\w-]*:\\s?/.test(line)) continue\n try {\n const parsedLine = parseYaml(line)\n if (parsedLine && typeof parsedLine === 'object' && !Array.isArray(parsedLine)) {\n Object.assign(data, parsedLine)\n }\n } catch {\n // Line is unrecoverable on its own; drop just that field.\n }\n }\n return data\n}\n\n/** Parse frontmatter without any path that can execute the content. */\nexport function parseFrontmatter(raw: string): ParsedFrontmatter {\n const source = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw\n const opening = /^---([^\\r\\n]*)\\r?\\n/.exec(source)\n if (!opening || opening[1].startsWith('-')) return { content: source, data: {} }\n\n const language = opening[1].trim().toLowerCase()\n const remainder = source.slice(opening[0].length)\n const closing = /^---[ \\t]*\\r?$/m.exec(remainder)\n const matter = closing ? remainder.slice(0, closing.index) : remainder\n let content = closing ? remainder.slice(closing.index + closing[0].length) : ''\n if (content.startsWith('\\r\\n')) content = content.slice(2)\n else if (content.startsWith('\\n')) content = content.slice(1)\n\n if (matter.trim() === '' || !['', 'yaml', 'yml'].includes(language)) {\n return { content, data: {} }\n }\n try {\n const parsed = parseYaml(matter)\n return {\n content,\n data: parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {},\n }\n } catch (err) {\n return {\n content,\n data: salvageFrontmatterLines(matter),\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n","/** Markdown/MDX normalization that preserves every component Thally supports. */\n\nimport type * as acorn from 'acorn'\nimport { posix } from 'node:path'\nimport { compileSync } from '@mdx-js/mdx'\nimport { nameToEmoji } from 'gemoji'\nimport remarkGfm from 'remark-gfm'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport { unified } from 'unified'\n\nimport { isThallyBuiltinComponent } from './builtin-components.js'\nimport { parseFrontmatter } from './frontmatter.js'\nimport type { MigrationPage, MigrationPlatform } from './types.js'\n\nexport interface MarkdownPageIdentity {\n id: string\n navigationId: string\n locale?: string\n}\n\nfunction titleFromId(id: string): string {\n const value = id.split('/').at(-1) ?? id\n if (value === 'introduction') return 'Introduction'\n return value\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\ninterface DescriptionNode {\n type: string\n value?: string\n alt?: string | null\n children?: Array<DescriptionNode>\n}\n\nconst descriptionParser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx)\n\nfunction firstParagraph(content: string): string {\n function plainText(node: DescriptionNode): string {\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'image') return node.alt ?? ''\n if (node.type === 'break') return ' '\n return (node.children ?? []).map(plainText).join('')\n }\n function findParagraph(node: DescriptionNode): string {\n if (node.type === 'paragraph') {\n const value = plainText(node).replace(/\\s+/g, ' ').trim()\n if (value) return value.slice(0, 240)\n }\n for (const child of node.children ?? []) {\n const value = findParagraph(child)\n if (value) return value\n }\n return ''\n }\n // Component wrappers, imports, expressions, and code fences are syntax, not\n // description copy. Reading paragraph nodes also finds prose nested inside\n // accordions without leaking their closing tags into page metadata.\n try {\n return findParagraph(descriptionParser.parse(content) as DescriptionNode)\n } catch {\n // Unparseable source is already retained for the migration validator. An\n // empty generated description is safer than exposing source-code fragments.\n return ''\n }\n}\n\nfunction docusaurusAdmonitionTag(kind: string): 'Error' | 'Info' | 'Note' | 'Warning' {\n if (kind === 'danger') return 'Error'\n if (kind === 'info') return 'Info'\n if (kind === 'caution' || kind === 'warning') return 'Warning'\n return 'Note'\n}\n\n/**\n * Convert Docusaurus' colon-fence admonitions without interpreting code-fence\n * contents. Longer delimiters support nested admonitions in the same way as\n * the source renderer.\n */\nfunction normalizeDocusaurusAdmonitions(body: string): string {\n const lines = body.split('\\n')\n const openAdmonitions: Array<{ delimiter: string; tag: string; openedAt: number }> = []\n const headingLines: Array<number> = []\n let codeFence: string | null = null\n\n const output = lines.map((line, index) => {\n const codeMatch = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (codeMatch) {\n if (!codeFence) codeFence = codeMatch[1]\n else if (codeMatch[1][0] === codeFence[0] && codeMatch[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(codeMatch[0].length))) codeFence = null\n return line\n }\n if (codeFence) return line\n if (/^#{1,6}\\s/.test(line)) headingLines.push(index)\n\n const opening = line.match(/^\\s*(:{3,})(note|tip|info|warning|caution|danger)(?:\\[([^\\]]+)\\]|\\s+(.+))?\\s*$/i)\n if (opening) {\n const tag = docusaurusAdmonitionTag(opening[2].toLowerCase())\n openAdmonitions.push({ delimiter: opening[1], tag, openedAt: index })\n const title = (opening[3] ?? opening[4])?.trim()\n return title ? `<${tag}>\\n**${title}**` : `<${tag}>`\n }\n\n const closing = line.match(/^\\s*(:{3,})\\s*$/)\n const current = openAdmonitions.at(-1)\n if (closing && current?.delimiter === closing[1]) {\n openAdmonitions.pop()\n return `</${current.tag}>`\n }\n return line\n })\n // Docusaurus tolerates an unterminated admonition in some archived docs.\n // Close it before the next top-level heading (or at EOF) so an otherwise\n // complete page remains importable instead of being discarded by MDX.\n const closingByLine = new Map<number, Array<string>>()\n for (const open of openAdmonitions.reverse()) {\n const at = headingLines.find((line) => line > open.openedAt) ?? output.length\n closingByLine.set(at, [...(closingByLine.get(at) ?? []), `</${open.tag}>`])\n }\n for (const [at, closing] of [...closingByLine].sort(([left], [right]) => right - left)) output.splice(at, 0, ...closing)\n return output.join('\\n')\n}\n\n/**\n * Docusaurus' `mdx-code-block` fence is an escape hatch for live MDX syntax,\n * often used to open a JSX element around ordinary Markdown and code blocks.\n * Remove only the special fence itself; its contents must pass through the\n * same component and link normalization as the rest of the page.\n */\nfunction unwrapDocusaurusMdxCodeBlocks(body: string): string {\n const output: Array<string> = []\n let fence: string | undefined\n let isMdxCodeBlock = false\n for (const line of body.split('\\n')) {\n const opening = !fence && line.match(/^ {0,3}(`{3,}|~{3,})mdx-code-block\\s*$/)\n if (opening) {\n fence = opening[1]\n isMdxCodeBlock = true\n continue\n }\n if (fence) {\n const closing = line.match(/^ {0,3}(`{3,}|~{3,})\\s*$/)\n if (closing && closing[1][0] === fence[0] && closing[1].length >= fence.length) {\n if (!isMdxCodeBlock) output.push(line)\n fence = undefined\n isMdxCodeBlock = false\n continue\n }\n // These blocks may be Docusaurus' only declaration of a theme or\n // npm component used later on the page. Opening just the JSX would\n // promote an unresolved import into Thally's server build, so leave\n // the entire page's source-specific fences intact.\n if (isMdxCodeBlock && /^\\s*(?:import|export)\\b/.test(line)) return body\n output.push(line)\n continue\n }\n const ordinaryFence = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (ordinaryFence) {\n fence = ordinaryFence[1]\n isMdxCodeBlock = false\n }\n output.push(line)\n }\n // An unmatched source fence remains visible to the MDX compiler, which\n // reports the malformed page rather than silently deleting its contents.\n return isMdxCodeBlock ? body : output.join('\\n')\n}\n\n/** Keep explicit heading anchors without leaving `{#id}` as an MDX expression. Frontmatter is left untouched. */\nexport function normalizeExplicitHeadingIds(raw: string): string {\n const { front, body } = splitFrontmatterBlock(raw)\n return front + replaceOutsideCode(body, (segment) => segment.split('\\n').map((line) => {\n if (!/^[ \\t]{0,3}#{1,6}[ \\t]+/.test(line)) return line\n const trimmed = line.trimEnd()\n // Check suffixes from the end instead of matching unbounded whitespace\n // against unbounded heading text; that combination backtracks on long\n // headings with no valid anchor.\n if (trimmed.endsWith('}')) {\n const marker = trimmed.lastIndexOf(' {#')\n if (marker >= 0) {\n const id = trimmed.slice(marker + 3, -1)\n if (/^[A-Za-z][A-Za-z0-9_-]*$/.test(id)) {\n return `<a id=\"${id}\"></a>\\n${trimmed.slice(0, marker).trimEnd()}`\n }\n }\n }\n // Docusaurus' heading plugin also accepts a trailing MDX comment.\n if (trimmed.endsWith('*/}')) {\n const marker = trimmed.lastIndexOf(' {/*')\n if (marker >= 0) {\n const comment = trimmed.slice(marker + 4, -3).trim()\n const id = comment.startsWith('#') ? comment.slice(1) : ''\n if (/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(id)) {\n return `<a id=\"${id}\"></a>\\n${trimmed.slice(0, marker).trimEnd()}`\n }\n }\n }\n return line\n }).join('\\n'))\n}\n\nconst GLOBAL_DOCUSARUS_COMPONENTS = new Set([\n 'Tabs',\n 'TabItem',\n 'Link',\n 'DocCardList',\n 'TOCInline',\n])\n\n/** Match the one simple import form Docusaurus injects without backtracking. */\nfunction removeGlobalDocusaurusImports(body: string): string {\n return replaceOutsideCode(body, (segment) => segment.replace(\n /\\bimport\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])(@(?:theme|docusaurus)\\/[^'\"]+)\\2\\s*;?/g,\n (statement: string, component: string) => GLOBAL_DOCUSARUS_COMPONENTS.has(component) ? '' : statement,\n ))\n}\n\nconst JS_LITERAL_KEYWORDS = new Set(['true', 'false', 'null', 'undefined'])\n// A leading identifier segment (`x` in `x.y.z`) may be any valid JS/Unicode\n// identifier, not just ASCII — `{café}`, `{$var}` are both real bare\n// references a page's own ESM could bind, and Fern's literal-brace prose\n// (the thing this whole pass is trying to leave alone) never happens to\n// look like one, so escaping stays conservative either way.\nconst BARE_IDENTIFIER_PATH = /^[\\p{ID_Start}$_][\\p{ID_Continue}$]*(?:\\.[\\p{ID_Start}$_][\\p{ID_Continue}$]*)*$/u\n// Double-mustache templating syntax (`{{now}}`, `{{customer}}`) is common in\n// prose copied from other platforms (Liquid/Handlebars-style variable\n// interpolation). MDX parses the outer `{...}` as an expression container and\n// the inner `{now}` as a JS object-literal shorthand property, so the node's\n// value looks like `{now}` — a single bare identifier wrapped in its own\n// braces — never a real JSX prop (which appears inside an attribute, not\n// standalone body/flow text). Matching this shape lets the same \"leave a\n// $ref alone unless we can hint an undeclared reference\" caution apply to\n// double-brace template text as it already does to single-brace text.\nconst BARE_OBJECT_SHORTHAND = /^\\{\\s*([\\p{ID_Start}$_][\\p{ID_Continue}$]*)\\s*\\}$/u\n/**\n * Pure JS built-ins that exist identically in the server and browser render.\n * Only a dotted path rooted at one (`{Math.PI}`, `{Number.MAX_SAFE_INTEGER}`)\n * is left as a live expression. A bare name (`{window}`, `{Date}`,\n * `{console}`) is always escaped: it would render an object/function (a\n * React crash or silently empty text), and host globals such as `window`,\n * `document`, `navigator`, or `process` do not exist on both sides at all.\n */\nconst SAFE_BUILTIN_ROOTS = new Set([\n 'Math', 'JSON', 'Number', 'String', 'Object', 'Array', 'Intl', 'Boolean', 'Symbol', 'BigInt', 'Reflect',\n])\n\ninterface MdxOffsetNode {\n type: string\n depth?: number\n value?: string\n name?: string | null\n data?: { estree?: acorn.Program | null }\n children?: Array<MdxOffsetNode>\n position?: { start: { offset?: number }; end: { offset?: number } }\n}\n\n/** Use a page's leading H1 as its title without rendering it twice. */\nfunction leadingPageHeading(body: string): { title: string; start: number; end: number } | undefined {\n try {\n const root = descriptionParser.parse(body) as MdxOffsetNode\n const first = root.children?.find((node) => node.type !== 'mdxjsEsm' && node.type !== 'html')\n if (first?.type !== 'heading' || first.depth !== 1) return undefined\n const text = (node: MdxOffsetNode): string => node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression'\n ? ''\n : node.value ?? (node.children ?? []).map(text).join('')\n const title = text(first).replace(/\\s+/g, ' ').trim()\n const start = first.position?.start.offset\n const end = first.position?.end.offset\n return title && start !== undefined && end !== undefined ? { title, start, end } : undefined\n } catch {\n return undefined\n }\n}\n\n/** Recursively collects every name a binding pattern introduces (`{a, b: {c}}`, `[p, ...rest]`, `x = 1`). */\nfunction collectPatternNames(pattern: acorn.AnyNode, names: Set<string>): void {\n switch (pattern.type) {\n case 'Identifier':\n names.add((pattern as acorn.Identifier).name)\n break\n case 'ObjectPattern':\n for (const property of (pattern as acorn.ObjectPattern).properties) {\n collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, names)\n }\n break\n case 'ArrayPattern':\n for (const element of (pattern as acorn.ArrayPattern).elements) {\n if (element) collectPatternNames(element, names)\n }\n break\n case 'AssignmentPattern':\n collectPatternNames((pattern as acorn.AssignmentPattern).left, names)\n break\n case 'RestElement':\n collectPatternNames((pattern as acorn.RestElement).argument, names)\n break\n default:\n break\n }\n}\n\n/** Adds the name(s) a single top-level declaration statement introduces (`const`/`let`/`var`, `function`, `class`). */\nfunction collectDeclarationNames(node: acorn.AnyNode | null | undefined, names: Set<string>): void {\n if (!node) return\n if (node.type === 'VariableDeclaration') {\n for (const declarator of (node as acorn.VariableDeclaration).declarations) collectPatternNames(declarator.id, names)\n } else if ((node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') && (node as acorn.FunctionDeclaration | acorn.ClassDeclaration).id) {\n names.add(((node as acorn.FunctionDeclaration | acorn.ClassDeclaration).id as acorn.Identifier).name)\n }\n}\n\n/**\n * Bind every name a page's own ESM statement introduces — an import\n * (default, namespace, or named/destructured, however deeply nested its\n * destructuring goes), or a top-level `const`/`let`/`var`/`function`/`class`\n * — so a prose brace referencing one of them is treated as real,\n * already-bound code rather than ambiguous Fern prose. Read from the ESTree\n * remark-mdx attaches to the `mdxjsEsm` node (real ESM syntax including JSX,\n * not a regex approximation), so `export const a = 1, b = 2`, nested\n * destructuring, and multi-declarator statements all resolve\n * correctly. `export { x } from './y'` (a re-export) and a local `export {\n * x }` (which only re-exposes an already-declared local) never introduce a\n * new binding, so neither is added here — matching real JS module\n * semantics, since referencing `x` in prose is exactly as undefined as it\n * would be in the compiled component.\n */\nfunction collectEsmBindings(node: MdxOffsetNode, declared: Set<string>): void {\n // remark-mdx already parsed this ESM (with JSX support) and keeps the\n // result on the node; re-parsing it with plain acorn fails on any JSX.\n const program = node.data?.estree\n if (!program) {\n collectEsmBindingsByPattern(node.value ?? '', declared)\n return\n }\n for (const statement of program.body) {\n if (statement.type === 'ImportDeclaration') {\n for (const specifier of statement.specifiers) declared.add(specifier.local.name)\n } else if (statement.type === 'ExportNamedDeclaration') {\n collectDeclarationNames(statement.declaration, declared)\n } else if (statement.type === 'ExportDefaultDeclaration') {\n collectDeclarationNames(statement.declaration, declared)\n } else {\n collectDeclarationNames(statement, declared)\n }\n }\n}\n\n/**\n * Fallback when no parsed ESM tree is available: collect simple declared and\n * imported names by pattern, so the page's own bindings are still recognized.\n * Approximate (destructuring is not followed, nested declarations are\n * included), but never records nothing for a page that does bind names.\n */\nfunction collectEsmBindingsByPattern(source: string, declared: Set<string>): void {\n for (const match of source.matchAll(/\\b(?:const|let|var|class|function\\s*\\*?)\\s+([\\p{ID_Start}$_][\\p{ID_Continue}$]*)/gu)) declared.add(match[1])\n for (const match of source.matchAll(/\\bimport\\s+([^'\";]*?)\\s+from\\b/g)) {\n const clause = match[1]\n for (const name of clause.replace(/\\{[^}]*\\}/, '').matchAll(/(?:\\*\\s+as\\s+)?([\\p{ID_Start}$_][\\p{ID_Continue}$]*)/gu)) declared.add(name[1])\n for (const entry of clause.match(/\\{([^}]*)\\}/)?.[1].split(',') ?? []) {\n const local = entry.trim().split(/\\s+as\\s+/).at(-1)?.trim()\n if (local) declared.add(local)\n }\n }\n}\n\n/**\n * Fern's own MDX renderer tolerates a bare `{word}` in prose as literal text\n * (e.g. `\"connection to {vendor} failed\"`, `<Note>connection to {vendor}\n * failed</Note>`); Thally's MDX pipeline evaluates `{...}` as a JS expression\n * and throws `ReferenceError` when the identifier isn't defined. `{vendor}`\n * is syntactically valid MDX either way — a text expression — so the fix\n * isn't a character scan but telling real code from prose: parse the page,\n * then escape a bare identifier/dotted-path text expression\n * (`mdxTextExpression`/`mdxFlowExpression`) anywhere in the body tree,\n * including inside a JSX element's children (a `<Note>`/`<Tabs>` callout is\n * the common Fern case) — but never a JSX *attribute* expression\n * (`prop={x}`, which lives on the node's `attributes`, not its `children`,\n * and this walk never visits it), never ESM, never code. Real component\n * code — `{items.map((item) => <li>{item}</li>)}` — parses as a single\n * expression node whose JSX lives only in its `estree`, not as further mdast\n * children, so this walk cannot (and must not) descend into it and escape\n * the inner `{item}`; only a leaf expression node with every mdast ancestor\n * being JSX/markdown is ever a candidate. `props` (MDX's implicit prop) and\n * anything the page's own ESM imports or declares are exempt. A page whose\n * source doesn't parse is left untouched; the migration's MDX-compile check\n * reports the real problem instead.\n */\n/** Trimmed line begins a fenced code block (```` ``` ```` or `~~~`, 3+ characters). */\nconst FENCE_OPEN = /^(`{3,}|~{3,})/\n\n/**\n * KaTeX-style `$$...$$` math (block, on its own lines, or inline mid-\n * paragraph) is common in Fern docs (and any other Markdown source) but has\n * no Thally renderer (no `remark-math`/`rehype-katex`) — worse, the raw\n * LaTeX inside (`\\begin{align*}`, bare `{...}`) crashes the MDX parser\n * before `escapeFernLiteralBraces` below even gets a chance to run, so the\n * whole page fails to compile and is silently excluded. Content is\n * preserved, never dropped: a block becomes a fenced ` ```math ` code\n * block, an inline span becomes an inline code span — both opaque to MDX's\n * `{...}` expression parsing. This is a plain line scan (not an MDX parse,\n * which is exactly what the source can't survive yet) that tracks fenced\n * code blocks so a real code sample's own `$$` is never touched, and must\n * run before any MDX-aware pass.\n */\n/**\n * Mask, within a single line, every backtick code span and every JSX/HTML\n * tag (open, close, or self-closing — including its attribute values) so\n * `protectMathBlocks`'s inline `$...$` scan below can never mistake a `$`\n * inside either for a math delimiter, and a matched math span can never\n * straddle a masked region (the placeholder has no `$` in it, so the regex\n * simply can't span across one). A JSX tag never spans a `$...$` scan's own\n * line here because `protectMathBlocks` processes text line by line; a tag\n * split across lines is already opaque to it for other reasons.\n */\nfunction maskInlineSpansForMath(line: string): { masked: string; unmask: (text: string) => string } {\n const blocks: Array<string> = []\n const stash = (text: string): string => {\n blocks.push(text)\n return `\\u0000${blocks.length - 1}\\u0000`\n }\n const codeMasked = line.split(/(`[^`]*`)/).map((segment, index) => (\n index % 2 === 1 ? stash(segment) : segment\n )).join('')\n const tagMasked = codeMasked.replace(/<\\/?[a-zA-Z][^<>]*>/g, stash)\n // Also mask a JSX expression container (`{...}`), one level of nesting\n // deep, so `$` inside one (e.g. a prop value built from a template\n // literal that isn't itself backtick-quoted) is never read as a math\n // delimiter. Two passes handle one level of `{...{...}...}` nesting; a\n // line-local regex can't balance further than that, which is fine here —\n // anything left over simply isn't masked, the conservative default. A\n // `{` immediately after `$` is deliberately left unmasked: that is a\n // template-literal interpolation (`${...}`), not a JSX container, and the\n // caller's own `$(?!{)` guard needs to see the literal `{` to reject it.\n const masked = [tagMasked, tagMasked].reduce((text) => text.replace(/(?<!\\$)\\{[^{}]*\\}/g, stash), tagMasked)\n return {\n masked,\n unmask: (text) => text.replace(/\\u0000(\\d+)\\u0000/g, (_match, index: string) => blocks[Number(index)]),\n }\n}\n\n/**\n * Whether `content` (the real, unmasked text between a matched pair of\n * inline `$...$`) looks like actual TeX rather than two unrelated dollar\n * amounts or a stray currency symbol: a backslash command (`\\times`,\n * `\\text{...}`), `^`/`_` (super/subscript), or a brace group. A bare\n * variable-style token with no space and no digit (`$S$`, `$x$`) is also\n * accepted without any of those — KaTeX/Pandoc's own convention for a\n * single-symbol inline reference, and the shape of the paradex-docs repro.\n */\nconst TEX_SIGNAL = /\\\\[a-zA-Z]|[\\^_{]/\nfunction hasTexSignal(content: string): boolean {\n return TEX_SIGNAL.test(content) || (!/\\s/.test(content) && !/\\d/.test(content))\n}\n\n/**\n * Net count of `{`, `(`, `[` minus their closers on `line` — a lazy,\n * string/comment-unaware bracket count (not a real JS parse) used only to\n * tell when a multi-line `import`/`export` ESM statement has closed. Real\n * component source rarely has an unbalanced bracket inside a string on the\n * same line as an ESM statement's own delimiters, and this is a heuristic\n * for skipping a scan, not a correctness-critical parse.\n * TODO: raw character count, ignores strings/comments; a real AST pass\n * would be exact, add one if this heuristic misfires on real content.\n */\nfunction bracketDelta(line: string): number {\n let delta = 0\n for (const ch of line) {\n if (ch === '{' || ch === '(' || ch === '[') delta += 1\n else if (ch === '}' || ch === ')' || ch === ']') delta -= 1\n }\n return delta\n}\n\n/** Trimmed line opens a top-level `import`/`export` ESM statement (Docusaurus/MDX allow one anywhere a block can start, not just at the top of the file). */\nconst ESM_OPEN = /^(?:import|export)\\b/\n\nexport function protectMathBlocks(raw: string): { body: string; converted: boolean; guardTriggered?: boolean } {\n const { front, body } = splitFrontmatterBlock(raw)\n const lines = body.split(/\\r\\n|\\r|\\n/)\n const output: Array<string> = []\n let inFence = false\n let fenceToken = ''\n // Fern also allows a block delimited by a bare `$` alone on its own line\n // (not just `$$`), e.g. `$\\n\\text{...}\\n$`; a block must close on the\n // same delimiter that opened it.\n let mathBlockDelimiter: '$$' | '$' | null = null\n let mathLines: Array<string> = []\n let converted = false\n // Depth of an open `import`/`export` ESM statement (counted in\n // `bracketDelta`): while positive, every line belongs to page-authored\n // JS/JSX source (e.g. an inlined snippet's `export const X = () => {...}`\n // component body), not markdown/math prose, and is copied through\n // untouched — never scanned for `$`, so a template literal's `${expr}`\n // inside it can never be misread as a math delimiter.\n let esmDepth = 0\n for (const line of lines) {\n const trimmed = line.trim()\n if (mathBlockDelimiter) {\n if (trimmed === mathBlockDelimiter) {\n output.push('```math', ...mathLines, '```')\n mathBlockDelimiter = null\n mathLines = []\n converted = true\n } else {\n mathLines.push(line)\n }\n continue\n }\n if (inFence) {\n if (trimmed.startsWith(fenceToken)) inFence = false\n output.push(line)\n continue\n }\n if (esmDepth > 0) {\n output.push(line)\n esmDepth = Math.max(0, esmDepth + bracketDelta(line))\n continue\n }\n const fenceOpen = FENCE_OPEN.exec(trimmed)\n if (fenceOpen) {\n inFence = true\n fenceToken = fenceOpen[1].slice(0, 3)\n output.push(line)\n continue\n }\n if (trimmed === '$$' || trimmed === '$') {\n mathBlockDelimiter = trimmed\n continue\n }\n if (ESM_OPEN.test(trimmed)) {\n output.push(line)\n esmDepth = Math.max(0, bracketDelta(line))\n continue\n }\n if (line.includes('$')) {\n // Mask inline code spans (`` `$FOO` ``), JSX/HTML tags (including\n // their attribute values, e.g. `<Badge color=\"$primary\">`), and a\n // JSX expression container (`{...}`) before scanning for math, so\n // none of them can be mistaken for a math delimiter and a math span\n // can never cross into one — a masked placeholder has no `$` in it,\n // so the scan below simply can't see inside one or pair a `$`\n // outside it with one that was inside it. What's left unmasked is\n // ordinary prose/JSX text content.\n const { masked, unmask } = maskInlineSpansForMath(line)\n // One combined pass, `$$...$$` tried before single-`$...$` at each\n // position: doing these as two sequential passes let the second\n // (single-`$`) regex re-match dollar signs the first pass had just\n // wrapped in backticks, corrupting its own output. Single-`$` inline\n // math (the other half of the KaTeX convention, e.g. `$F = S \\times\n // e^{\\,f\\,T}$`, or a bare `$S$`) only counts when its content\n // doesn't start/end with whitespace, holds no further `$`, and looks\n // like real TeX (`hasTexSignal`) — the same rule KaTeX/Pandoc use to\n // tell real inline math from an ordinary sentence mentioning two\n // dollar amounts (`$50 and $100`, whose span content ends in a space\n // and so never matches). Neither alternative ever opens on `${`\n // (a template-literal interpolation, not a math delimiter). An\n // author-escaped `\\$` (a literal dollar sign) is never treated as a\n // delimiter.\n const updatedMasked = masked.replace(\n /\\$\\$(?!\\{)([^\\n]+?)\\$\\$|(?<!\\\\)\\$(?!\\{)([^\\s$](?:[^$\\n]*[^\\s$])?)\\$/g,\n (whole: string, block: string | undefined, inline: string | undefined) => {\n if (block !== undefined) {\n converted = true\n return `\\`$$${block}$$\\``\n }\n if (inline !== undefined && hasTexSignal(unmask(inline))) {\n converted = true\n return `\\`$${inline}$\\``\n }\n return whole\n },\n )\n output.push(unmask(updatedMasked))\n continue\n }\n output.push(line)\n }\n // An unterminated `$$` block means the source was malformed to begin\n // with; leave it untouched rather than eating the rest of the page into\n // one giant fenced block.\n if (mathBlockDelimiter) return { body: raw, converted: false }\n const protectedBody = front + output.join('\\n')\n if (!converted) return { body: protectedBody, converted }\n // Math conversion must never turn a page that used to compile into one\n // that doesn't (e.g. a false-positive match that corrupts real code).\n // If the protected body fails to compile as MDX but the untouched\n // original did, the conversion made things worse — keep the original and\n // let the caller warn, rather than silently excluding the page later.\n try {\n compileSync(protectedBody, { outputFormat: 'program' })\n return { body: protectedBody, converted }\n } catch {\n try {\n compileSync(raw, { outputFormat: 'program' })\n return { body: raw, converted: false, guardTriggered: true }\n } catch {\n // The original didn't compile either (the usual case math protection\n // exists for) — the protected attempt is still the better bet.\n return { body: protectedBody, converted }\n }\n }\n}\n\nexport function escapeFernLiteralBraces(raw: string): string {\n // Never touch the YAML frontmatter block: its `{...}` values (e.g. a\n // description containing a literal brace) are YAML scalars, not MDX\n // expressions, and running the MDX parser over them corrupts the block.\n // Split it off first — mirroring `parseFrontmatter`'s own delimiter\n // handling, including a leading BOM and CRLF line endings, which a naive\n // `/^---\\n/` guard misses and lets the frontmatter get parsed as MDX.\n const { front, body } = splitFrontmatterBlock(raw)\n\n let root: MdxOffsetNode\n try {\n root = descriptionParser.parse(body) as MdxOffsetNode\n } catch {\n return raw\n }\n\n const declared = new Set<string>(['props'])\n const collectEsm = (node: MdxOffsetNode) => {\n if (node.type === 'mdxjsEsm') collectEsmBindings(node, declared)\n for (const child of node.children ?? []) collectEsm(child)\n }\n collectEsm(root)\n\n const edits: Array<{ start: number; end: number; value: string }> = []\n const visit = (node: MdxOffsetNode) => {\n if (node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression') {\n const value = (node.value ?? '').trim()\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n const root = value.split('.')[0]\n const safeBuiltinPath = value.includes('.') && SAFE_BUILTIN_ROOTS.has(root)\n const isBareIdentifier = BARE_IDENTIFIER_PATH.test(value) && !JS_LITERAL_KEYWORDS.has(value)\n && !declared.has(root) && !safeBuiltinPath\n const shorthandMatch = value.match(BARE_OBJECT_SHORTHAND)\n const isDoubleBraceTemplate = shorthandMatch !== null && !declared.has(shorthandMatch[1])\n const isIssueList = /^[A-Za-z][A-Za-z0-9]*-\\d+(?:\\s*,\\s*[A-Za-z][A-Za-z0-9]*-\\d+)*$/.test(value)\n if ((isBareIdentifier || isDoubleBraceTemplate || isIssueList) && start !== undefined && end !== undefined) {\n // Escape every literal brace in the matched span rather than\n // rebuilding it from `value`, so this handles both `{name}` and\n // `{{name}}` (and any other brace nesting) the same way.\n const rawSpan = body.slice(start, end)\n edits.push({ start, end, value: rawSpan.replace(/\\\\/g, '\\\\\\\\').replace(/[{}]/g, '\\\\$&') })\n }\n // A leaf node: mdast never gives it further `children` (its JSX, if\n // any, lives only inside `data.estree`), so there is nothing to recurse into.\n return\n }\n for (const child of node.children ?? []) visit(child)\n }\n visit(root)\n if (edits.length === 0) return raw\n\n const escapedBody = edits\n .sort((left, right) => right.start - left.start)\n .reduce((result, edit) => `${result.slice(0, edit.start)}${edit.value}${result.slice(edit.end)}`, body)\n return front + escapedBody\n}\n\n/**\n * Split `raw` into its untouched YAML frontmatter block (including a leading\n * BOM, if present) and the remaining MDX body, using the same delimiter\n * rules as `parseFrontmatter` (BOM-aware, CRLF-safe) so the two always agree\n * on where the frontmatter ends. Unlike `parseFrontmatter`, this returns the\n * frontmatter block verbatim (not parsed) because callers here only need to\n * avoid rewriting it, not read its values.\n */\nfunction splitFrontmatterBlock(raw: string): { front: string; body: string } {\n const hasBom = raw.charCodeAt(0) === 0xfeff\n const bom = hasBom ? raw[0] : ''\n const source = hasBom ? raw.slice(1) : raw\n const opening = /^---([^\\r\\n]*)\\r?\\n/.exec(source)\n if (!opening || opening[1].startsWith('-')) return { front: bom, body: source }\n const remainder = source.slice(opening[0].length)\n const closing = /^---[ \\t]*\\r?$/m.exec(remainder)\n if (!closing) return { front: bom, body: source }\n const end = opening[0].length + closing.index + closing[0].length\n return { front: bom + source.slice(0, end), body: source.slice(end) }\n}\n\n/**\n * `components.ts`'s `createComponentMigrator` renames a successfully copied\n * or extracted component's JSX tag to `Migrated<12-hex-char-hash>` and\n * registers it in the project-wide `src/mdx/custom-components.tsx` (merged\n * into every page by `mdx-components.tsx`, not imported per-page) — so a\n * page's own ESM never mentions it, even though it does resolve. Recognize\n * the naming convention rather than re-deriving it from `components.ts`,\n * which would need this module to depend on that one's private `hash()`.\n */\nconst MIGRATED_COMPONENT_TAG = /^Migrated[0-9a-f]{12}$/\n\n/** True when the JSX span itself (not merely its opening tag) is self-closing, e.g. `<Foo />`. */\nfunction isSelfClosingJsx(text: string): boolean {\n return /\\/>\\s*$/.test(text)\n}\n\n/** Replace the leading `<name` / trailing `</name` occurrences of a tag with `newName`, for a tag with no children to preserve (self-closing, or an empty pair). */\nfunction renameTagOccurrences(text: string, name: string, newName: string): string {\n let result = text\n const openIndex = result.indexOf(`<${name}`)\n if (openIndex >= 0) result = `${result.slice(0, openIndex + 1)}${newName}${result.slice(openIndex + 1 + name.length)}`\n const closeIndex = result.lastIndexOf(`</${name}`)\n if (closeIndex >= 0) result = `${result.slice(0, closeIndex + 2)}${newName}${result.slice(closeIndex + 2 + name.length)}`\n return result\n}\n\n/**\n * Reconstructs `body.slice(loStart, hiEnd)` verbatim except through\n * `renderNode` at each of `children`'s own spans — the gaps between/around\n * them (markdown or JSX syntax the children's own positions don't cover,\n * such as a parent JSX element's attributes) are copied through unchanged.\n */\nfunction renderChildrenSpan(\n children: Array<MdxOffsetNode>,\n loStart: number,\n hiEnd: number,\n body: string,\n renderNode: (node: MdxOffsetNode) => string,\n): string {\n let cursor = loStart\n let out = ''\n for (const child of children) {\n const start = child.position?.start.offset\n const end = child.position?.end.offset\n if (start === undefined || end === undefined) continue\n out += body.slice(cursor, start)\n out += renderNode(child)\n cursor = end\n }\n out += body.slice(cursor, hiEnd)\n return out\n}\n\n/**\n * Replaces a page-authored (or Docusaurus/Fern-only) `<Link href=\"...\">`\n * with a plain `<a href=\"...\">`, keeping every attribute and all children\n * exactly as authored — only the tag name changes, so nested content\n * (including any unknown component the fallback below also rewrites) is\n * preserved. A page that declares or imports its own `Link` keeps it\n * untouched; that binding, not this generic one, is what actually renders.\n */\nexport function replaceLinkWithAnchor(raw: string): string {\n return replaceUnknownComponents(raw, () => {}, { onlyRenameLinkTag: true })\n}\n\n/**\n * Fallback for any capitalized JSX tag Thally cannot render: not a builtin\n * (`isThallyBuiltinComponent`) and not declared or imported by the page\n * itself. Mintlify/Docusaurus content commonly references a project-local or\n * npm component that `components.ts`'s copy step already handles when it can\n * be resolved — this only ever fires for what's left: a name with nothing\n * backing it at all, which would otherwise throw \"Expected component X to be\n * defined\" at render. A paired tag becomes a plain `<div>`, keeping its\n * children (so nested prose/markup survives); a self-closing tag is removed\n * outright, since it has no content to keep. `warn` is called once per\n * distinct component name found. `<Link>` is renamed to `<a>` instead of\n * falling into that generic path, since it's common enough to warrant a\n * real mapping (Mintlify/Docusaurus content routinely writes `<Link\n * href=\"...\">`) rather than losing the link.\n *\n * Frontmatter is split off first (see `escapeFernLiteralBraces`) so a YAML\n * value can never be mistaken for JSX.\n */\nexport function replaceUnknownComponents(\n raw: string,\n warn: (name: string) => void,\n options: { onlyRenameLinkTag?: boolean } = {},\n): string {\n const { front, body } = splitFrontmatterBlock(raw)\n\n let root: MdxOffsetNode\n try {\n root = descriptionParser.parse(body) as MdxOffsetNode\n } catch {\n return raw\n }\n\n const declared = new Set<string>(['props'])\n const collectEsm = (node: MdxOffsetNode) => {\n if (node.type === 'mdxjsEsm') collectEsmBindings(node, declared)\n for (const child of node.children ?? []) collectEsm(child)\n }\n collectEsm(root)\n\n const warned = new Set<string>()\n const renderNode = (node: MdxOffsetNode): string => {\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n if (start === undefined || end === undefined) return ''\n const isJsx = node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement'\n const tagRoot = node.name ? node.name.split('.')[0] : undefined\n const text = body.slice(start, end)\n\n if (isJsx && tagRoot === 'Link' && !declared.has('Link')) {\n if (isSelfClosingJsx(text) || !node.children?.length) return renameTagOccurrences(text, node.name!, 'a')\n const openEnd = node.children[0].position?.start.offset ?? start\n const closeStart = node.children.at(-1)!.position?.end.offset ?? end\n return renameTagOccurrences(body.slice(start, openEnd), node.name!, 'a')\n + renderChildrenSpan(node.children, openEnd, closeStart, body, renderNode)\n + renameTagOccurrences(body.slice(closeStart, end), node.name!, 'a')\n }\n\n if (!options.onlyRenameLinkTag && isJsx && tagRoot && /^[A-Z]/.test(tagRoot)\n && !isThallyBuiltinComponent(node.name!) && !declared.has(tagRoot) && !MIGRATED_COMPONENT_TAG.test(tagRoot)) {\n if (!warned.has(node.name!)) {\n warned.add(node.name!)\n warn(node.name!)\n }\n if (isSelfClosingJsx(text)) return ''\n if (!node.children?.length) return '<div></div>'\n const openEnd = node.children[0].position?.start.offset ?? start\n const closeStart = node.children.at(-1)!.position?.end.offset ?? end\n const children = renderChildrenSpan(node.children, openEnd, closeStart, body, renderNode)\n // A flow (block-level) unknown component can wrap block content —\n // a fenced code block, a heading, another flow element — and MDX\n // only recognizes that as block content when it's set off from the\n // surrounding tag by a blank line; gluing it straight onto `<div>`\n // (the previous behavior) reads as inline text, which derails the\n // parser and can surface as an unrelated \"unclosed `<div>`\" error\n // once it hits the real closing tag. The source component's own\n // markup may have had no blank line there at all (a permissive\n // renderer doesn't require one), so always add it rather than\n // trying to detect when it's needed. An inline (text-level) unknown\n // component never contains block content, so it stays glued.\n return node.type === 'mdxJsxFlowElement' ? `<div>\\n\\n${children}\\n\\n</div>` : `<div>${children}</div>`\n }\n\n if (!node.children?.length) return text\n return renderChildrenSpan(node.children, start, end, body, renderNode)\n }\n\n return front + renderNode(root)\n}\n\n/**\n * Replace every fenced code block and inline `code span` in `body` with an\n * opaque single-line placeholder, so a textual rename can run as one pass\n * over the WHOLE body — including a tag or comment that spans multiple\n * lines — without ever matching inside code, then restore the original code\n * text afterward. A rename that only ever sees one line at a time (the old\n * approach) misses anything spanning lines: a `<!--\\n...\\n-->` comment, a\n * `<Warn\\n title=\"x\">` opening tag whose `</Warn>` gets renamed with no\n * matching open, a Docusaurus `<Link\\n to=\"/a\">` likewise. Every rename in\n * this module that isn't already AST-based goes through this one masker\n * instead of re-implementing fence tracking.\n */\nfunction maskCode(body: string): { masked: string; unmask: (text: string) => string } {\n // NUL is never valid in MDX; strip it so it can't collide with the \\u0000\n // placeholder markers stashed below.\n const source = body.replace(/\\u0000/g, '')\n\n const blocks: Array<string> = []\n const stash = (text: string): string => {\n blocks.push(text)\n return `\\u0000${blocks.length - 1}\\u0000`\n }\n\n const lines: Array<string> = []\n let codeFence: string | null = null\n let fenceBuffer: Array<string> = []\n // Note: MDX (mdx-js) disables CommonMark indented code blocks, so\n // 4-space-indented text is never code here and is intentionally left\n // unmasked, matching @mdx-js/mdx's own parsing.\n for (const line of source.split('\\n')) {\n const fenceMatch = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (codeFence) {\n fenceBuffer.push(line)\n // A closing fence has no info string. ` ```python` inside an open\n // Markdown fence is content, not a close; treating it as one can mask\n // every later HTML tag and leave React-invalid attributes untouched.\n if (fenceMatch && fenceMatch[1][0] === codeFence[0]\n && fenceMatch[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(fenceMatch[0].length))) {\n lines.push(stash(fenceBuffer.join('\\n')))\n codeFence = null\n fenceBuffer = []\n }\n continue\n }\n if (fenceMatch) {\n codeFence = fenceMatch[1]\n fenceBuffer = [line]\n continue\n }\n lines.push(line.split(/(`[^`]*`)/).map((segment, index) => (\n index % 2 === 1 ? stash(segment) : segment\n )).join(''))\n }\n // An unterminated fence (malformed source) still must not be rewritten.\n if (fenceBuffer.length) lines.push(stash(fenceBuffer.join('\\n')))\n\n return {\n masked: lines.join('\\n'),\n unmask: (text) => text.replace(/\\u0000(\\d+)\\u0000/g, (_match, index: string) => blocks[Number(index)]),\n }\n}\n\n/**\n * Apply a textual rename to the WHOLE body outside fenced/inline code (via\n * `maskCode`), so a match may span multiple lines.\n */\nexport function replaceOutsideCode(body: string, transform: (whole: string) => string): string {\n const { masked, unmask } = maskCode(body)\n return unmask(transform(masked))\n}\n\n/**\n * Fern authors often link sibling MDX files from Card props and Markdown.\n * Resolve only links to files that actually became pages; unknown paths,\n * external URLs, assets, and examples retain their authored destinations.\n */\nexport function rewriteFernRelativePageLinks(\n body: string,\n currentSourcePath: string,\n routesBySourcePath: ReadonlyMap<string, string>,\n): string {\n const rewrite = (target: string): string => {\n if (!target || target.startsWith('/') || target.startsWith('#') || target.startsWith('?')\n || target.includes('\\\\') || /[\\u0000-\\u001f\\u007f]/.test(target)\n || /^[A-Za-z][A-Za-z\\d+.-]*:/.test(target)) return target\n const suffixAt = target.search(/[?#]/)\n const pathname = suffixAt < 0 ? target : target.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : target.slice(suffixAt)\n if (!pathname || pathname.startsWith('//') || pathname.split('/').some((part) => /%2f|%5c/i.test(part))) return target\n const source = posix.normalize(posix.join(posix.dirname(currentSourcePath.replace(/\\\\/g, '/')), pathname))\n const candidates = /\\.mdx?$/i.test(source) ? [source] : [source, `${source}.mdx`, `${source}.md`, `${source}/index.mdx`, `${source}/index.md`]\n const route = candidates.map((candidate) => routesBySourcePath.get(candidate)).find(Boolean)\n return route ? `/${route.replace(/^\\/+/, '')}${suffix}` : target\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()(<[^>\\n]+>|[^\\s)]+)(?=\\s|\\))/g,\n (_match, opening: string, target: string) => `${opening}${target.startsWith('<') && target.endsWith('>') ? `<${rewrite(target.slice(1, -1))}>` : rewrite(target)}`)\n .replace(/(\\b(?:href|to)\\s*=\\s*)([\"'])([^\"'\\n]+)\\2/g,\n (_match, opening: string, quote: string, target: string) => `${opening}${quote}${rewrite(target)}${quote}`)\n .replace(/(\\b(?:href|to)\\s*=\\s*\\{\\s*)([\"'])([^\"'\\n]+)\\2(?=\\s*\\})/g,\n (_match, opening: string, quote: string, target: string) => `${opening}${quote}${rewrite(target)}${quote}`))\n}\n\n/** Convert Fern's indented file-list shorthand to Thally's nested Tree nodes. */\nfunction normalizeFernFileTrees(body: string): string {\n return replaceOutsideCode(body, (whole) => whole.replace(/<FileTree\\s*>\\s*\\n([\\s\\S]*?)\\n\\s*<\\/FileTree>/g,\n (original: string, contents: string) => {\n const lines = contents.split(/\\r?\\n/).filter((line) => line.trim())\n if (!lines.length) return original\n const nodes: Array<{ indent: number; name: string; isFolder: boolean }> = []\n for (const line of lines) {\n const match = /^( *)(?:-|\\*|\\+)\\s+(.+?)\\s*$/.exec(line)\n if (!match || match[1].length % 2 !== 0 || match[2].includes('\\u0000')) return original\n nodes.push({ indent: match[1].length / 2, name: match[2], isFolder: match[2].endsWith('/') })\n }\n const output = ['<Tree>']\n const folders: Array<number> = []\n for (const node of nodes) {\n while (folders.length > node.indent) {\n output.push('</Folder>')\n folders.pop()\n }\n // A child without a parent folder is not a reliable tree. Retain the\n // Fern source so migration validation can report it explicitly.\n if (node.indent > folders.length || (node.indent > 0 && folders.length === 0)) return original\n const name = `{${JSON.stringify(node.name)}}`\n if (node.isFolder) {\n output.push(`<Folder name=${name} defaultOpen>`)\n folders.push(node.indent)\n } else {\n output.push(`<File name=${name} />`)\n }\n }\n while (folders.length) {\n output.push('</Folder>')\n folders.pop()\n }\n output.push('</Tree>')\n return output.join('\\n')\n }))\n}\n\n/**\n * Converts an HTML comment (`<!-- text -->`) to MDX's own comment syntax\n * (`{/* text *\\/}`), skipping fenced/inline code. remark-mdx does not parse\n * `<!-- -->` at all — a real Markdown/Docusaurus source commonly has one\n * (`<!-- prettier-ignore -->` ahead of a snippet import is a common\n * Docusaurus pattern) and it otherwise throws \"Unexpected character `!`\"\n * wherever something needs a real MDX parse of the page — not just this\n * module's `normalizeMdx`, but `components.ts`'s independent component\n * analysis too, before that pass ever gets a chance to run.\n */\nexport function normalizeHtmlComments(body: string): string {\n return replaceOutsideCode(body, (whole) => whole.replace(/<!--([\\s\\S]*?)-->/g, (_match, comment: string) => `{/*${comment}*/}`))\n}\n\n/**\n * Rewrite Fern's callout intents to Thally's fixed callout tags without\n * touching fenced code. Delimiters are tracked with a stack so nested and\n * sibling callouts each close with the tag their own opening intent chose.\n * A single scan is required: collecting every opener before visiting any\n * closer incorrectly pairs sibling and nested callouts.\n */\nfunction normalizeFernCallouts(body: string): string {\n return replaceOutsideCode(body, (whole) => {\n const openTags: Array<string | null> = []\n const output: string[] = []\n let cursor = 0\n while (cursor < whole.length) {\n const opening = whole.indexOf('<Callout', cursor)\n const closing = whole.indexOf('</Callout>', cursor)\n const next = opening < 0 ? closing : closing < 0 ? opening : Math.min(opening, closing)\n if (next < 0) break\n output.push(whole.slice(cursor, next))\n if (next === closing) {\n const tag = openTags.pop()\n output.push(tag ? `</${tag}>` : '</Callout>')\n cursor = next + '</Callout>'.length\n continue\n }\n const attributeStart = next + '<Callout'.length\n if (!/[\\s/>]/.test(whole[attributeStart] ?? '')) {\n output.push('<Callout')\n cursor = attributeStart\n continue\n }\n // JSX attributes may contain quoted `>` or expression comparisons.\n // Locate the delimiter in one pass instead of using a backtracking\n // regex over arbitrary source content.\n let end = attributeStart\n let quote: string | null = null\n let expressionDepth = 0\n for (; end < whole.length; end++) {\n const character = whole[end]\n if (quote) {\n if (character === quote && whole[end - 1] !== '\\\\') quote = null\n } else if (character === '\"' || character === \"'\") {\n quote = character\n } else if (character === '{') {\n expressionDepth++\n } else if (character === '}' && expressionDepth > 0) {\n expressionDepth--\n } else if (character === '>' && expressionDepth === 0) {\n break\n }\n }\n if (end === whole.length) {\n output.push(whole.slice(next))\n cursor = whole.length\n break\n }\n const attributes = whole.slice(attributeStart, end)\n const intent = findStaticCalloutIntent(attributes)\n const isSelfClosing = attributes.trimEnd().endsWith('/')\n if (!intent) {\n output.push(whole.slice(next, end + 1))\n if (!isSelfClosing) openTags.push(null)\n } else {\n const value = intent.value.toLowerCase()\n const tag = value === 'warning' ? 'Warning'\n : value === 'success' || value === 'tip' ? 'Tip'\n : value === 'error' || value === 'danger' ? 'Error' : 'Note'\n output.push(`<${tag}${attributes.slice(0, intent.start)}${attributes.slice(intent.end)}>`)\n if (!isSelfClosing) openTags.push(tag)\n }\n cursor = end + 1\n }\n output.push(whole.slice(cursor))\n return output.join('')\n })\n}\n\n/** Find only a static, quoted intent attribute; preserve every other prop. */\nfunction findStaticCalloutIntent(attributes: string): { start: number; end: number; value: string } | null {\n let cursor = 0\n while (cursor < attributes.length) {\n const start = cursor\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n if (cursor === start) { cursor++; continue }\n const nameStart = cursor\n while (/[A-Za-z0-9_-]/.test(attributes[cursor] ?? '')) cursor++\n const name = attributes.slice(nameStart, cursor)\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n if (attributes[cursor] !== '=') continue\n cursor++\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n const quote = attributes[cursor]\n if (quote !== '\"' && quote !== \"'\") {\n // Other props may be JSX expressions. Skip balanced braces so a\n // string inside an expression cannot masquerade as an attribute.\n if (quote === '{') {\n let depth = 0\n do {\n if (attributes[cursor] === '{') depth++\n if (attributes[cursor] === '}') depth--\n cursor++\n } while (cursor < attributes.length && depth > 0)\n } else {\n while (cursor < attributes.length && !/\\s/.test(attributes[cursor])) cursor++\n }\n continue\n }\n const valueStart = ++cursor\n while (cursor < attributes.length && attributes[cursor] !== quote) cursor++\n const value = attributes.slice(valueStart, cursor)\n if (cursor < attributes.length) cursor++\n if (name === 'intent') return { start, end: cursor, value }\n }\n return null\n}\n\n/**\n * Unwrap Fern's per-tab `<CodeBlock>` only while inside a `<CodeGroup>`\n * (renamed from Fern's `<CodeBlocks>` earlier in the pipeline). Mintlify also\n * ships a genuine, globally available `<CodeBlock>` component for\n * programmatic rendering inside custom React components — that usage never\n * nests inside a `<CodeGroup>`, so it survives untouched.\n */\nfunction unwrapFernCodeBlockTabs(body: string): string {\n return replaceOutsideCode(body, (whole) => {\n let groupDepth = 0\n return whole.replace(/<CodeGroup\\b[^>]*>|<\\/CodeGroup>|<CodeBlock\\b[^>]*>|<\\/CodeBlock>/g, (match) => {\n if (match.startsWith('<CodeGroup')) {\n groupDepth++\n return match\n }\n if (match === '</CodeGroup>') {\n groupDepth = Math.max(0, groupDepth - 1)\n return match\n }\n return groupDepth > 0 ? '' : match\n })\n })\n}\n\n// TODO: a plain <pre>/<code> shim, not Thally's styled Pre/CodeGroup —\n// upgrade to a registered `CodeBlock` MDX built-in (mirroring Code/CodeGroup)\n// once the scaffold template ships one.\nconst STANDALONE_CODE_BLOCK_SHIM = [\n 'export const CodeBlock = ({ children, filename, ...rest }) => (',\n ' <pre {...rest}>',\n ' {filename ? <div>{filename}</div> : null}',\n ' <code>{children}</code>',\n ' </pre>',\n ');',\n].join('\\n')\n\n/** Extracts the source text of each top-level `export const X = (...) => (…|{…` body. */\nfunction exportDeclarationBodies(body: string): Array<string> {\n const bodies: Array<string> = []\n const opener = /export const \\w+ = [^\\n]*=> ([({])/g\n for (const match of body.matchAll(opener)) {\n const open = match[1]\n const close = open === '(' ? ')' : '}'\n let depth = 1\n let i = (match.index ?? 0) + match[0].length\n while (i < body.length && depth > 0) {\n if (body[i] === open) depth++\n else if (body[i] === close) depth--\n i++\n }\n bodies.push(body.slice((match.index ?? 0) + match[0].length, i))\n }\n return bodies\n}\n\n/**\n * True when `export const NAME = ` (ending right at `sourceIndex`) assigns a\n * real function expression — `function` or an arrow function — rather than a\n * plain value whose initializer merely contains `=>` further in, the way\n * `list.map((x) => x)` does. Only a genuine function reference crosses the\n * server/client boundary as a prop; a value like `items` above does not.\n */\nexport function isFunctionInitializer(source: string, sourceIndex: number): boolean {\n let index = sourceIndex\n const skipSpace = () => { while (/\\s/.test(source[index] ?? '')) index++ }\n // Keywords must end at a word boundary: `functionList`, `asyncMode`, and\n // `classNames` are ordinary identifiers, not function expressions.\n const keyword = (word: string) => new RegExp(`^${word}(?![\\\\w$])`).test(source.slice(index))\n skipSpace()\n if (keyword('async')) {\n index += 'async'.length\n skipSpace()\n // `async => x` is an arrow whose parameter is named `async`.\n if (source.startsWith('=>', index)) return true\n }\n if (keyword('function') || keyword('class')) return true\n if (source[index] === '(') {\n let depth = 0\n for (; index < source.length; index++) {\n if (source[index] === '(') depth++\n else if (source[index] === ')') {\n depth--\n if (depth === 0) {\n index++\n break\n }\n }\n }\n skipSpace()\n return source.startsWith('=>', index)\n }\n const identifier = /^[A-Za-z_$][\\w$]*/.exec(source.slice(index))\n if (!identifier) return false\n index += identifier[0].length\n skipSpace()\n return source.startsWith('=>', index)\n}\n\n/**\n * Detects a page-authored function (`export const Name = () => ...`) passed\n * as a bare JSX prop value (`someProp={Name}`) elsewhere on the same page.\n * Next renders an MDX page as a Server Component by default; an extracted\n * interactive snippet it imports is `'use client'` (see `components.ts`).\n * Passing a plain function across that boundary as a prop throws at render\n * (\"Functions cannot be passed directly to Client Components\") even though\n * the MDX itself compiles cleanly — Mintlify's own renderer has no such\n * server/client split, so this content is valid there. Thally has no import\n * mechanism that moves the declaration into the client module instead, so\n * the page is reported and excluded rather than shipped broken.\n *\n * Two things keep this from over-firing: fenced/inline code (a doc example\n * showing this exact shape) never counts, via `maskCode`; and only a real\n * function initializer counts as \"a function\" — `export const items =\n * list.map((x) => x)` is a plain value, not one, even though its own\n * initializer happens to contain `=>`.\n */\nexport function hasClientBoundaryFunctionProp(body: string): boolean {\n const { masked } = maskCode(body)\n const declared = [...functionDeclaredNames(body)]\n return declared.some((name) => new RegExp(`\\\\w+=\\\\{${name}\\\\}`).test(masked))\n}\n\n/**\n * A page's top-level `export` identifiers that are actually functions — a\n * `function`/`async function` declaration, or an `export const NAME = `\n * whose initializer is a real function expression (see\n * `isFunctionInitializer`). Excludes plain values (`export const diagram =\n * 'graph TD'`), even when their initializer text happens to contain `=>`\n * further in (`export const items = list.map((x) => x)`). Callers that need\n * to know whether a prop value crosses the server/client boundary as a\n * function must check against this set, not every `export const` name —\n * confusing the two would exclude pages that merely pass a string or object\n * to a client component.\n */\nexport function functionDeclaredNames(body: string): Set<string> {\n const { masked } = maskCode(body)\n const names = new Set<string>()\n for (const match of masked.matchAll(/export const (\\w+)\\s*=\\s*/g)) {\n if (isFunctionInitializer(masked, (match.index ?? 0) + match[0].length)) names.add(match[1])\n }\n // Function declarations (incl. `default`, `async`, generators) and classes:\n // a class is a constructor function and is just as unserializable.\n for (const match of masked.matchAll(/export\\s+(?:default\\s+)?(?:async\\s+)?(?:function\\s*\\*?\\s*|class\\s+)(\\w+)/g)) {\n names.add(match[1])\n }\n // One level of aliasing: `export const Alias = Demo` where `Demo` is one.\n for (const match of masked.matchAll(/^export const (\\w+)\\s*=\\s*(\\w+)\\s*;?\\s*$/gm)) {\n if (names.has(match[2])) names.add(match[1])\n }\n return names\n}\n\n/**\n * A page's own `export const` declarations sometimes reference a Mintlify\n * global built-in by bare JS identifier (e.g. `<CodeBlock>` or `<Icon>`\n * inside a custom render function) instead of through prose, where Thally's\n * MDX registry wires it in automatically via `_components`. A bare reference\n * with nothing importing or declaring it throws `ReferenceError` at render.\n * Provide it the same way the source page would have gotten it implicitly:\n * a real import where Thally ships an equivalent, otherwise a minimal\n * same-file shim (see `STANDALONE_CODE_BLOCK_SHIM`).\n */\nfunction provideScopedGlobalReferences(body: string): string {\n const alreadyBound = (name: string): boolean => new RegExp(`\\\\b${name}\\\\s*[=:]|\\\\bimport\\\\s+.*\\\\b${name}\\\\b`).test(body)\n const referencedIn = exportDeclarationBodies(body).join('\\n')\n\n let result = body\n if (/<Icon\\b/.test(referencedIn) && !alreadyBound('Icon')) {\n result = `import { Icon } from '@/components/mdx/content-icon';\\n\\n${result}`\n }\n if (/<CodeBlock\\b/.test(referencedIn) && !alreadyBound('CodeBlock')) {\n result = `${STANDALONE_CODE_BLOCK_SHIM}\\n\\n${result}`\n }\n return result\n}\n\n/**\n * Docusaurus authors a `<Tabs>` block's human labels once, in its own\n * `values={[{ label, value }, ...]}` prop, and each `<TabItem value=\"...\">`\n * repeats only the machine `value`. Thally's `<Tab title=\"...\">` has no\n * separate values table, so each tab's title must be resolved from the\n * parent's `values` entry (a `TabItem`'s own `label` still wins when given).\n * Docusaurus-only props that Thally's `<Tabs>` does not read are dropped so\n * they don't linger as dead JSX attributes on the migrated component.\n */\nfunction normalizeDocusaurusTabs(body: string): string {\n let result = body\n for (let depth = 0; depth < 20; depth += 1) {\n const updated = result.replace(/<Tabs\\b([^>]*)>((?:(?!<Tabs\\b)[\\s\\S])*?)<\\/Tabs>/g, (_match, attributes: string, inner: string) => {\n const labelByValue = new Map<string, string>()\n const valuesSource = attributes.match(/\\bvalues=\\{(\\[[\\s\\S]*?\\])\\s*\\}/)?.[1]\n if (valuesSource) {\n for (const entry of valuesSource.matchAll(/\\{([^{}]*)\\}/g)) {\n const label = entry[1].match(/\\blabel:\\s*(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const value = entry[1].match(/\\bvalue:\\s*(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n if (value) labelByValue.set(value, label ?? value)\n }\n }\n const cleanedAttributes = attributes\n .replace(/\\s*defaultValue=(?:\\{[^}]*\\}|\"[^\"]*\"|'[^']*')/g, '')\n .replace(/\\s*values=\\{[\\s\\S]*?\\]\\s*\\}/g, '')\n .replace(/\\s*values=\\{[^{}]*\\}/g, '')\n .replace(/\\s*groupId=(?:\"[^\"]*\"|'[^']*')/g, '')\n .replace(/\\s*queryString(?:=(?:\\{[^}]*\\}|\"[^\"]*\"|'[^']*'))?/g, '')\n const rewrittenInner = inner\n .replace(/<TabItem\\b([^>]*)>/g, (_itemMatch, itemAttributes: string) => {\n const label = itemAttributes.match(/\\blabel=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const value = itemAttributes.match(/\\bvalue=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const title = label ?? (value && labelByValue.get(value)) ?? value ?? 'Tab'\n return `<Tab title=\"${title.replace(/\"/g, '"')}\">`\n })\n .replace(/<\\/TabItem>/g, '</Tab>')\n return `<ThallyTabs${cleanedAttributes}>${rewrittenInner}</ThallyTabs>`\n })\n if (updated === result) break\n result = updated\n }\n return result.replace(/<ThallyTabs\\b/g, '<Tabs').replace(/<\\/ThallyTabs>/g, '</Tabs>')\n}\n\nconst TAB_FENCE_OPEN = /^(`{3,}|~{3,})(\\S*)\\s+tab\\b(.*)$/\n\n/**\n * `docusaurus-remark-plugin-tab-blocks` marks each fence in a tab group with\n * a `tab` meta keyword (```` ```js tab title=\"npm\" ````). Thally has no\n * matching remark plugin, but its `<CodeGroup>` already reads the same\n * `title=` fence attribute for tab labels, so consecutive tab-marked fences\n * are wrapped in one and the now-meaningless `tab` keyword is dropped. Only\n * fences that opt in via that keyword are touched — this never fires\n * speculatively on an ordinary fence.\n */\nfunction normalizeDocusaurusTabBlocks(body: string): string {\n const lines = body.split('\\n')\n const output: Array<string> = []\n let index = 0\n while (index < lines.length) {\n const open = lines[index].match(TAB_FENCE_OPEN)\n if (!open) {\n output.push(lines[index])\n index++\n continue\n }\n const blocks: Array<Array<string>> = []\n while (index < lines.length) {\n const start = lines[index].match(TAB_FENCE_OPEN)\n if (!start) break\n const marker = start[1]\n const block = [`${start[1]}${start[2]}${start[3]}`]\n index++\n while (index < lines.length && lines[index].trim() !== marker) {\n block.push(lines[index])\n index++\n }\n block.push(lines[index] ?? marker)\n index++\n blocks.push(block)\n let lookahead = index\n while (lookahead < lines.length && lines[lookahead].trim() === '') lookahead++\n if (!lines[lookahead] || !TAB_FENCE_OPEN.test(lines[lookahead])) break\n index = lookahead\n }\n if (blocks.length > 1) {\n output.push('<CodeGroup>', '')\n for (const block of blocks) output.push(...block, '')\n output.pop()\n output.push('</CodeGroup>')\n } else {\n output.push(...blocks[0])\n }\n }\n return output.join('\\n')\n}\n\n/**\n * Split a CSS declaration list on top-level `;` only — a `;` inside\n * `url(...)` (a data URI commonly contains one) must not end the\n * declaration early.\n */\nfunction splitCssDeclarations(value: string): Array<string> {\n const parts: Array<string> = []\n let depth = 0\n let current = ''\n for (const char of value) {\n if (char === '(') depth++\n else if (char === ')') depth = Math.max(0, depth - 1)\n if (char === ';' && depth === 0) {\n parts.push(current)\n current = ''\n } else {\n current += char\n }\n }\n if (current.trim()) parts.push(current)\n return parts\n}\n\n/**\n * Convert a CSS property name to the key a JSX style object expects:\n * camelCase, vendor prefixes capitalized (`-webkit-transform` ->\n * `WebkitTransform`) except React's own `-ms-` quirk (`msTransform`, not\n * `MsTransform`), and a custom property (`--x`) left as a literal string key.\n */\nfunction cssPropertyToJsKey(property: string): string {\n if (property.startsWith('--')) return JSON.stringify(property)\n const camel = property.replace(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase())\n return camel.startsWith('Ms') ? camel.slice(0, 1).toLowerCase() + camel.slice(1) : camel\n}\n\n/**\n * Convert an HTML `style=\"...\"` attribute's raw CSS text into the object\n * literal a JSX `style={{...}}` prop requires.\n *\n * TODO: `!important` cannot be expressed in a React style object at all\n * (there is no per-declaration escape hatch), so it is dropped rather than\n * left in a value string where it would do nothing; upgrade to a `!` layer\n * of inline `<style>` injection if a real page ever needs it.\n */\nfunction cssTextToStyleObjectLiteral(cssText: string): string {\n const entries = splitCssDeclarations(cssText).flatMap((declaration) => {\n const colon = declaration.indexOf(':')\n if (colon === -1) return []\n const property = declaration.slice(0, colon).trim()\n const value = declaration.slice(colon + 1).replace(/\\s*!\\s*important\\s*$/i, '').trim()\n if (!property || !value || !/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return []\n return [`${cssPropertyToJsKey(property)}: ${JSON.stringify(value)}`]\n })\n return `{${entries.join(', ')}}`\n}\n\n/**\n * Rewrite a string `style=\"...\"`/`style='...'` attribute on a lowercase\n * (intrinsic HTML) JSX element into `style={{...}}`. JSX (unlike HTML)\n * requires `style` to be a mapping from property to value; a raw string —\n * common in Markdown/MDX pasted from HTML, e.g. a copied DataFrame table —\n * throws at render instead of just being ignored, so this must run\n * unconditionally, not only for a known source platform. An already-correct\n * `style={...}` expression is untouched (the match requires a quote right\n * after `=`), as is any component tag (uppercase-first is never matched).\n */\nfunction convertHtmlStyleAttributes(body: string): string {\n return body.replace(\n // The separator before `style=` must be `\\s+`, not a single `\\s`: a\n // multi-line tag indents its attributes, so more than one whitespace\n // character (a newline plus spaces) commonly precedes it.\n /<([a-z][a-zA-Z0-9]*)((?:\\s+[^\\s\"'=<>/]+(?:=(?:\"[^\"]*\"|'[^']*'))?)*)\\s+style=([\"'])([\\s\\S]*?)\\3((?:\\s+[^\\s\"'=<>/]+(?:=(?:\"[^\"]*\"|'[^']*'))?)*)\\s*(\\/?)>/g,\n (_match, tag: string, before: string, _quote: string, styleText: string, after: string, selfClose: string) => (\n `<${tag}${before} style={${cssTextToStyleObjectLiteral(styleText)}}${after}${selfClose ? ' /' : ''}>`\n ),\n )\n}\n\n/** Mintlify allows presentational JSX in Update labels; Thally uses the label as an anchor id. */\nfunction normalizeMintlifyUpdateLabels(body: string): string {\n return body.replace(/(<Update\\b[^>]*\\blabel=)\\{(<\\>[\\s\\S]*?<\\/\\>)\\}/g, (match, prefix: string, fragment: string) => {\n let root: DescriptionNode\n try {\n root = descriptionParser.parse(fragment) as DescriptionNode\n } catch {\n return match\n }\n const plainText = (node: DescriptionNode): string | null => {\n // Preserve only parsed text nodes. Dropping markup with a regex can\n // leave a partial tag in the output when an attribute contains `>`.\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression' || node.type === 'mdxjsEsm') return null\n const parts = (node.children ?? []).map(plainText)\n return parts.some((part) => part === null) ? null : parts.join('')\n }\n const label = plainText(root)?.replace(/\\s+/g, ' ').trim()\n // Dynamic labels cannot be flattened safely; preserve their source form.\n return label && !/[{}]/.test(label) ? `${prefix}{${JSON.stringify(label)}}` : match\n })\n}\n\n/** Preserve Mintlify's generated `param-*` links on authored settings fields. */\nfunction normalizeMintlifyParameterAnchors(body: string): string {\n const seen = new Set<string>()\n const anchorFor = (name: string): string => {\n const id = `param-${name.toLowerCase().replace(/[._]/g, '-')}`\n if (seen.has(id)) return ''\n seen.add(id)\n return `<a id=\"${id}\"></a>\\n`\n }\n // `replaceOutsideCode` masks inline backticks as well as fenced code, so\n // scan heading lines separately to retain the authored setting name.\n let fence: string | undefined\n const withHeadings = body.split('\\n').map((line) => {\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = undefined\n return line\n }\n if (fence) return line\n const heading = line.match(/^ {0,3}#{1,6}\\s+`([A-Za-z][A-Za-z0-9._-]*)`(?:\\s|$)/)\n return heading ? `${anchorFor(heading[1])}${line}` : line\n }).join('\\n')\n return replaceOutsideCode(withHeadings, (segment) => segment\n .replace(/<(ResponseField|ParamField)\\b([^>]*?)\\bname=(?:\"([A-Za-z][A-Za-z0-9._-]*)\"|'([A-Za-z][A-Za-z0-9._-]*)')([^>]*)>/g,\n (match: string, _tag: string, _before: string, doubleQuoted: string, singleQuoted: string) =>\n `${anchorFor(doubleQuoted ?? singleQuoted)}${match}`))\n}\n\n/** Normalize only syntax Thally cannot render; supported source JSX stays intact. */\nexport function normalizeMdx(body: string, platform?: MigrationPlatform, unwrapMdxCodeBlocks = true): string {\n // A caller that doesn't know the source platform (the URL crawler, when it\n // can't identify one) must not guess — applying every platform's textual\n // renames to a page of unknown origin corrupts one that happens to use the\n // same component name for something else, e.g. a Mintlify page's own\n // `<Success>` becoming `<Tip>`, a Fern-only alias. An omitted platform\n // therefore runs no platform-specific renames; a caller exercising one\n // must pass it explicitly.\n const runFern = platform === 'fern'\n const runMintlify = platform === 'mintlify'\n const runDocusaurus = platform === 'docusaurus'\n\n // A heading's explicit `{#custom-id}` anchor (see `normalizeExplicitHeadingIds`)\n // means the same thing on every platform, so — unlike the platform-specific\n // renames below — this always runs, even when `platform` is omitted.\n // `normalizeExplicitHeadingIds` also covers Docusaurus' `{/* #id */}`\n // comment form.\n const sourceBody = runDocusaurus && unwrapMdxCodeBlocks ? unwrapDocusaurusMdxCodeBlocks(body) : body\n let rewritten = normalizeDocusaurusAdmonitions(normalizeExplicitHeadingIds(runFern ? normalizeFernFileTrees(normalizeFernCallouts(sourceBody)) : sourceBody))\n if (runDocusaurus) {\n // Docusaurus resolves GitHub emoji names in Markdown text. Leaving the\n // shortcodes literal makes comparison tables unreadable after import; the\n // code masker keeps examples and inline code byte-for-byte intact.\n rewritten = replaceOutsideCode(rewritten, (segment) => segment.replace(\n /:([+\\w-]+):/g,\n (shortcode: string, name: string) => nameToEmoji[name] ?? shortcode,\n ))\n // Docusaurus injects these theme components globally. Thally also\n // exposes its equivalents globally, so source-only imports must not survive.\n rewritten = normalizeDocusaurusTabBlocks(normalizeDocusaurusTabs(removeGlobalDocusaurusImports(rewritten)))\n // Data-only @site imports are often used solely by Docusaurus' tab\n // metadata. Once those props are projected to <Tab> labels, remove only\n // imports whose binding has no remaining use on the page.\n rewritten = replaceOutsideCode(rewritten, (segment) => segment.replace(\n /\\bimport\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])(@site\\/[^'\"]+)\\2\\s*;?/g,\n (statement: string, binding: string, _quote: string, _source: string, offset: number) => {\n const withoutStatement = segment.slice(0, offset) + segment.slice(offset + statement.length)\n return new RegExp(`\\\\b${binding}\\\\s*(?:\\\\.|\\\\[|\\\\})`).test(withoutStatement) ? statement : ''\n },\n ))\n rewritten = rewritten.replace(/^\\n{2,}/, '\\n')\n }\n if (runMintlify) rewritten = normalizeMintlifyParameterAnchors(rewritten)\n rewritten = replaceOutsideCode(rewritten, (segment) => {\n let result = convertHtmlStyleAttributes(segment)\n .replace(/<!--([\\s\\S]*?)-->/g, (_match, content: string) => `{/*${content}*/}`)\n .replace(/<Danger(\\s[^>]*)?>/g, '<Error$1>')\n .replace(/<\\/Danger>/g, '</Error>')\n .replace(/<Warn(\\s[^>]*)?>/g, '<Warning$1>')\n .replace(/<\\/Warn>/g, '</Warning>')\n .replace(/<Check(\\s[^>]*)?>/g, '<Note$1>')\n .replace(/<\\/Check>/g, '</Note>')\n .replace(/<Tree\\.Folder/g, '<Folder')\n .replace(/<\\/Tree\\.Folder>/g, '</Folder>')\n .replace(/<Tree\\.File/g, '<File')\n .replace(/<\\/Tree\\.File>/g, '</File>')\n if (runDocusaurus) {\n result = result\n // A TabItem outside any <Tabs>...</Tabs> pair (malformed source)\n // never reaches normalizeDocusaurusTabs' block match above; fall\n // back to its own label/value so it still renders as a Tab.\n .replace(/<TabItem\\b([^>]*)>/g, (_match, attributes: string) => {\n const title = attributes.match(/\\blabel=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n ?? attributes.match(/\\bvalue=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n ?? 'Tab'\n return `<Tab title=\"${title.replace(/\"/g, '"')}\">`\n })\n .replace(/<\\/TabItem>/g, '</Tab>')\n .replace(/<Link\\b([^>]*)\\bto=(?:\"([^\"]*)\"|'([^']*)')([^>]*)>/g, (_match, before: string, doubleQuoted: string, singleQuoted: string, after: string) => (\n `<a${before}href=\"${doubleQuoted ?? singleQuoted}\"${after}>`\n ))\n .replace(/<\\/Link>/g, '</a>')\n // The repository adapter expands DocCardList from the resolved\n // sidebar after page discovery. Its source tag has no runtime peer.\n .replace(/<(?:DocCardList|TOCInline)\\b[^>]*\\/>/g, '')\n }\n if (runMintlify) {\n result = normalizeMintlifyUpdateLabels(result)\n // Mintlify documents `<FileTree>` as a plain alias of `<Tree>`; Thally\n // only registers the latter.\n .replace(/<FileTree(\\s[^>]*)?>/g, '<Tree$1>')\n .replace(/<\\/FileTree>/g, '</Tree>')\n // Mintlify's `<GitHub.Repo repo=\"owner/name\" />` is the same repository\n // card Thally already registers as `<GitHub repo=\"owner/name\" />`.\n .replace(/<GitHub\\.Repo/g, '<GitHub')\n .replace(/<\\/GitHub\\.Repo>/g, '</GitHub>')\n // `<Column>` is an unstyled wrapper for arbitrary content inside\n // `<Columns>`; Thally's grid already treats any direct child as a\n // column, so a plain `<div>` (built into MDX, no registry entry\n // needed) matches.\n .replace(/<Column(\\s[^>]*)?>/g, '<div$1>')\n .replace(/<\\/Column>/g, '</div>')\n }\n if (runFern) {\n result = result\n // Fern-only wrappers with a direct Thally equivalent.\n .replace(/<CodeBlocks(\\s[^>]*)?>/g, '<CodeGroup$1>')\n .replace(/<\\/CodeBlocks>/g, '</CodeGroup>')\n .replace(/<ParameterField\\b/g, '<ParamField')\n .replace(/<\\/ParameterField>/g, '</ParamField>')\n .replace(/<Cards(\\s[^>]*)?>/g, '<CardGroup$1>')\n .replace(/<\\/Cards>/g, '</CardGroup>')\n .replace(/<Success(\\s[^>]*)?>/g, '<Tip$1>')\n .replace(/<\\/Success>/g, '</Tip>')\n .replace(/<Launch(\\s[^>]*)?>/g, '<Note$1>')\n .replace(/<\\/Launch>/g, '</Note>')\n // Fern's <Files> wraps <File>/<Folder> nodes Thally already renders\n // directly (also reached via the Docusaurus <Tree.Folder> rename above).\n .replace(/<Files(\\s[^>]*)?>\\n?/g, '')\n .replace(/<\\/Files>/g, '')\n }\n return result\n })\n if (runFern) rewritten = unwrapFernCodeBlockTabs(rewritten)\n const normalized = provideScopedGlobalReferences(rewritten)\n if (runDocusaurus && sourceBody !== body) {\n try {\n compileSync(normalized, { outputFormat: 'program' })\n } catch {\n // Some Docusaurus sites use this fence for imports or JSX fragments\n // whose surrounding source requires their private remark transforms.\n // Retain the original fenced page instead of dropping it entirely.\n return normalizeMdx(body, platform, false)\n }\n }\n return normalized\n}\n\n/** Parse source Markdown or MDX into the canonical page representation. */\nexport function parseMarkdownPage(input: {\n id: string\n navigationId?: string\n locale?: string\n raw: string\n source: string\n /** Gates platform-specific textual renames in `normalizeMdx`; omitted runs them all. */\n platform?: MigrationPlatform\n /** Resolve platform-specific routes from the already-parsed frontmatter. */\n resolveIdentity?: (\n frontmatter: Record<string, unknown>,\n fallback: MarkdownPageIdentity,\n ) => MarkdownPageIdentity\n}): MigrationPage | null {\n const parsed = parseFrontmatter(input.raw)\n const fallbackIdentity: MarkdownPageIdentity = {\n id: input.id,\n navigationId: input.navigationId ?? input.id,\n ...(input.locale ? { locale: input.locale } : {}),\n }\n const identity = input.resolveIdentity?.(parsed.data, fallbackIdentity) ?? fallbackIdentity\n let body = normalizeMdx(parsed.content, input.platform).trim()\n const keywords = Array.isArray(parsed.data.keywords)\n ? parsed.data.keywords.filter((value): value is string => typeof value === 'string')\n : []\n const heading = leadingPageHeading(body)\n const title = typeof parsed.data.title === 'string' && parsed.data.title.trim()\n ? parsed.data.title.trim()\n : heading?.title ?? titleFromId(identity.navigationId)\n if (heading && heading.title === title) {\n body = `${body.slice(0, heading.start)}${body.slice(heading.end)}`.trim()\n }\n const navTitle = typeof parsed.data.sidebarTitle === 'string' && parsed.data.sidebarTitle.trim()\n ? parsed.data.sidebarTitle.trim()\n : typeof parsed.data.navTitle === 'string' && parsed.data.navTitle.trim()\n ? parsed.data.navTitle.trim()\n : undefined\n const badge = typeof parsed.data.tag === 'string' && parsed.data.tag.trim()\n ? parsed.data.tag.trim()\n : typeof parsed.data.badge === 'string' && parsed.data.badge.trim()\n ? parsed.data.badge.trim()\n : undefined\n const sourceMode = typeof parsed.data.mode === 'string' ? parsed.data.mode : undefined\n // Mintlify's frame mode and Thally's wide mode both retain the sidebar while\n // removing the on-page table of contents. Other shared modes map directly.\n const mode = sourceMode === 'frame'\n ? 'wide'\n : ['default', 'wide', 'custom', 'center', 'home'].includes(sourceMode ?? '')\n ? sourceMode as MigrationPage['mode']\n : undefined\n const description = typeof parsed.data.description === 'string' && parsed.data.description.trim()\n ? parsed.data.description.trim()\n : firstParagraph(body)\n return {\n id: identity.id,\n navigationId: identity.navigationId,\n locale: identity.locale,\n title,\n navTitle,\n description,\n ...(input.platform === 'docusaurus' || input.platform === 'fern'\n ? { descriptionPlacement: 'body' as const }\n : {}),\n badge,\n keywords,\n mode,\n hidden: parsed.data.hidden === true ? true : undefined,\n noindex: parsed.data.noindex === true || parsed.data.noindex === 'true' ? true : undefined,\n openapi: typeof parsed.data.openapi === 'string' ? parsed.data.openapi.trim() : undefined,\n body,\n source: input.source,\n ...(parsed.error ? { frontmatterError: parsed.error } : {}),\n }\n}\n","/**\n * Thally's registered MDX built-in component tag names, kept in one place so\n * the unknown-component fallback (`mdx.ts`) knows what already renders\n * without guessing. Mirrors the registry in the Thally runtime's\n * `src/components/mdx/mdx-components.tsx` (read-only from this package,\n * which ships standalone and cannot import app source at runtime).\n *\n * A drift guard (`src/components/mdx/client-registry.test.ts`, in the app\n * package) recomputes this set straight from that registry's AST and fails\n * CI if the two disagree, so a renderer change that adds or removes a\n * built-in fails loudly here instead of silently going stale in the\n * migrator.\n */\nexport const THALLY_BUILTIN_COMPONENTS: ReadonlySet<string> = new Set([\n 'CodeGroup', 'Info', 'Warning', 'Check', 'Danger', 'Error', 'Note', 'Tip',\n 'Callout', 'AccordionGroup', 'Latex', 'Hero', 'Card', 'CardGroup',\n 'Columns', 'Frame', 'Accordion', 'Tooltip', 'Icon', 'Steps', 'Step',\n 'Tabs', 'Tab', 'Badge', 'Update', 'RequestExample', 'ResponseExample',\n 'Panel', 'ContentPanel', 'InlinePanel', 'InlineRequestExample',\n 'InlineResponseExample', 'Tile', 'TileGroup', 'Prompt', 'PromptUser',\n 'PromptAssistant', 'Terminal', 'TerminalInput', 'TerminalOutput',\n 'AgentPrompt', 'Color', 'Tree', 'Folder', 'File', 'ResponseField',\n 'ParamField', 'Expandable', 'Mermaid', 'View', 'Embed', 'LegacyView',\n 'GitHub', 'Github', 'Visibility', 'Human', 'Agent', 'BannerPreview',\n])\n\n/** True for a builtin tag, or a member-expression tag on one (`Color.Item` -> `Color`). */\nexport function isThallyBuiltinComponent(name: string): boolean {\n return THALLY_BUILTIN_COMPONENTS.has(name) || THALLY_BUILTIN_COMPONENTS.has(name.split('.')[0])\n}\n","/** Safe path normalization used before reading or writing migrated content. */\n\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\n\nconst SAFE_SEGMENT = /[^a-z0-9._-]+/gi\n\n/**\n * Remove trailing forward slashes in linear time. Keeping leading slashes is\n * important because callers may still need to reject absolute paths.\n */\nexport function trimTrailingSlashes(value: string): string {\n let end = value.length\n while (end > 0 && value.charCodeAt(end - 1) === 47) end--\n return value.slice(0, end)\n}\n\n/** Remove forward slashes from both ends without a backtracking expression. */\nexport function trimEdgeSlashes(value: string): string {\n let start = 0\n let end = value.length\n while (start < end && value.charCodeAt(start) === 47) start++\n while (end > start && value.charCodeAt(end - 1) === 47) end--\n return value.slice(start, end)\n}\n\n/** Turn a source path segment into a stable URL/file-system slug. */\nexport function slugifySegment(value: string, preserveCase = false): string {\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // Malformed percent escapes are legal in source filenames. Treat them as\n // literal slug input instead of letting one file abort the whole import.\n }\n const normalized = preserveCase ? decoded : decoded.toLowerCase()\n return normalized\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(SAFE_SEGMENT, '-')\n .replace(/(^-|-$)/g, '')\n}\n\n/**\n * Normalize a page reference to a Thally content id. Invalid or traversal\n * references return `null` instead of being allowed near the file system.\n */\nexport function pageIdFromReference(value: string, preserveCase = false): string | null {\n const withoutQuery = value.split(/[?#]/, 1)[0].replace(/\\\\/g, '/').replace(/^\\/+/, '')\n if (!withoutQuery || withoutQuery.includes('\\0')) return null\n const rawSegments = withoutQuery.split('/').filter(Boolean)\n if (rawSegments.some((segment) => segment === '..' || segment === '.')) return null\n const last = rawSegments.at(-1)?.replace(/\\.(?:mdx?|rst|txt)$/i, '') ?? ''\n // `index` collapses to its parent directory at any depth, matching how\n // Mintlify and Next.js both treat directory indexes. `readme` only does the\n // same at the content root (`readme.md` -> `/`); a nested `readme` is a\n // real, addressable page (`migration/readme.md` -> `/migration/readme`)\n // and must not collide with a sibling `migration/index.md`.\n const isRootLevelReadme = rawSegments.length === 1 && /^readme$/i.test(last)\n const collapsesToParent = /^index$/i.test(last) || isRootLevelReadme\n const baseSegments = collapsesToParent ? rawSegments.slice(0, -1) : rawSegments\n if (!collapsesToParent) {\n baseSegments[baseSegments.length - 1] = last\n }\n const segments = baseSegments.map((segment) => slugifySegment(segment, preserveCase)).filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\n/**\n * Resolve language directories and legacy language-prefixed sections to the\n * same content identity used by default-language navigation. A hyphenated\n * section is only an alias when its unprefixed counterpart actually exists.\n */\nexport function mintlifyLocalizedReference(\n value: string,\n locale: string,\n defaultPageIds: ReadonlySet<string> = new Set(),\n): string {\n const reference = value.replace(/^\\/+/, '')\n const localePrefix = `${locale.toLowerCase()}/`\n if (reference.toLowerCase().startsWith(localePrefix)) return reference.slice(localePrefix.length)\n const sectionPrefix = `${locale.toLowerCase()}-`\n if (reference.toLowerCase().startsWith(sectionPrefix)) {\n const candidate = reference.slice(sectionPrefix.length)\n const candidateId = pageIdFromReference(candidate, true)\n if (candidateId && defaultPageIds.has(candidateId)) return candidate\n }\n // A versioned site nests the locale one level in instead of leading\n // (\"edge/ar/introduction\", not \"ar/edge/introduction\") — every version's\n // page references repeat this shape for every language, so the locale\n // segment shows up mid-path rather than only as a directory prefix. Drop\n // the first segment that exactly matches the locale wherever it falls,\n // so the resulting identity is shared across languages instead of the\n // caller re-adding a locale prefix on top of one already embedded here.\n const segments = reference.split('/')\n const localeIndex = segments.findIndex((segment) => segment.toLowerCase() === locale.toLowerCase())\n if (localeIndex > 0) {\n return [...segments.slice(0, localeIndex), ...segments.slice(localeIndex + 1)].join('/')\n }\n return value\n}\n\n/** Resolve an untrusted relative path and prove it remains below `root`. */\nexport function resolveWithin(root: string, candidate: string): string {\n return resolveWithinRoot(root, candidate, root)\n}\n\n/**\n * Resolve an untrusted relative path against `baseDir`, but only require the\n * result to stay below `confineRoot` (which may be an ancestor of `baseDir`).\n * Used where a config file's relative paths are conventionally resolved\n * against the file's own directory, yet the security boundary is a wider\n * root (e.g. the whole repository checkout).\n */\nexport function resolveWithinRoot(baseDir: string, candidate: string, confineRoot: string): string {\n if (isAbsolute(candidate) || candidate.includes('\\0')) {\n throw new Error(`Unsafe migration path: ${candidate}`)\n }\n const target = resolve(baseDir, candidate)\n const fromRoot = relative(resolve(confineRoot), target)\n if (fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {\n throw new Error(`Migration path escapes its root: ${candidate}`)\n }\n return target\n}\n\n/** Return a slash-separated, traversal-free asset path. */\nexport function normalizeAssetPath(value: string): string | null {\n const normalized = value.replace(/\\\\/g, '/').replace(/^\\/+/, '')\n if (!normalized || normalized.includes('\\0')) return null\n const segments = normalized.split('/').filter(Boolean)\n if (segments.some((segment) => segment === '.' || segment === '..')) return null\n return segments.join('/')\n}\n","/**\n * Static Docusaurus repository projection. Sidebar modules are attacker-owned\n * source files, so this adapter reads only JSON5-compatible object literals and\n * never imports, evaluates, or executes JavaScript/TypeScript configuration.\n */\n\nimport { existsSync, lstatSync, readFileSync } from 'node:fs'\nimport { extname, posix } from 'node:path'\n\nimport JSON5 from 'json5'\nimport { parse as parseYaml } from 'yaml'\n\nimport type { MarkdownPageIdentity } from './mdx.js'\nimport { isRedirectPathSafe } from './navigation.js'\nimport { pageIdFromReference, resolveWithin, slugifySegment } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_CONFIG_BYTES = 20_000_000\nconst CATEGORY_FILENAMES = ['_category_.json', '_category_.yml', '_category_.yaml']\nconst SIDEBAR_FILENAMES = [\n 'sidebars.json',\n 'sidebars.js',\n 'sidebars.cjs',\n 'sidebars.mjs',\n 'sidebars.ts',\n]\n\nexport interface DocusaurusPageDescriptor {\n sourcePath: string\n docId: string\n navigationId: string\n sidebarPosition?: number\n title: string\n}\n\nexport interface DocusaurusSidebars {\n config: Record<string, unknown>\n sourcePath: string\n}\n\nexport interface DocusaurusNavigationResult {\n docsConfig: MigrationDocsConfig\n generatedPages: Array<MigrationPage>\n referencedNavigationIds: Set<string>\n warnings: Array<MigrationWarning>\n}\n\ninterface ProjectionContext {\n contentRoot: string\n descriptors: Array<DocusaurusPageDescriptor>\n descriptorByDocId: Map<string, DocusaurusPageDescriptor>\n generatedPages: Array<MigrationPage>\n generatedIds: Set<string>\n referencedNavigationIds: Set<string>\n sourceUrl: string\n routePrefix: string\n sidebarSource: string\n warnings: Array<MigrationWarning>\n}\n\ninterface CategoryMetadata {\n label?: string\n position?: number\n link?: unknown\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction stripNumberPrefix(value: string): string {\n return value.replace(/^\\d+[-_]+/, '')\n}\n\nfunction normalizeDocId(value: string): string {\n return value\n .split(/[?#]/, 1)[0]\n .replace(/\\\\/g, '/')\n .replace(/^\\/+/, '')\n .replace(/\\.(?:mdx?)$/i, '')\n .split('/')\n .filter(Boolean)\n .map(stripNumberPrefix)\n .join('/')\n}\n\nfunction docusaurusSlugifySegment(value: string): string {\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // Malformed escapes remain literal input and are normalized safely below.\n }\n return decoded\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/(^-|-$)/g, '')\n}\n\nfunction docusaurusRouteId(value: string): string | null {\n const segments = normalizeDocId(value)\n .split('/')\n .map(docusaurusSlugifySegment)\n .filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\nfunction defaultDocusaurusRouteId(value: string): string | null {\n const segments = normalizeDocId(value).split('/').filter(Boolean)\n if (/^(?:index|readme)$/i.test(segments.at(-1) ?? '')) segments.pop()\n const normalized = segments.map(docusaurusSlugifySegment).filter(Boolean)\n return normalized.join('/') || 'introduction'\n}\n\nfunction storageIdForRoute(routeId: string): string {\n return /(?:^|\\/)(?:index|readme)$/i.test(routeId) ? `${routeId}/index` : routeId\n}\n\nfunction titleCase(value: string): string {\n return stripNumberPrefix(value)\n .replace(/sidebar$/i, '')\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\nfunction routeFromSlug(slug: string, fallback: string, sourceDirectory?: string): string | null {\n if (slug === '/') return 'introduction'\n if (slug.startsWith('/')) return docusaurusRouteId(slug)\n const fallbackDirectory = sourceDirectory ?? (fallback === 'introduction' ? '' : posix.dirname(fallback))\n const resolved = posix.normalize(posix.join(fallbackDirectory, slug))\n if (resolved === '..' || resolved.startsWith('../')) return null\n return docusaurusRouteId(resolved)\n}\n\n/** Resolve Docusaurus `id`, `slug`, and numeric-prefix semantics once. */\nexport function resolveDocusaurusPageIdentity(\n sourcePath: string,\n frontmatter: Record<string, unknown>,\n fallback: MarkdownPageIdentity,\n): { identity: MarkdownPageIdentity; descriptor: Omit<DocusaurusPageDescriptor, 'title'> } {\n const sourceDocId = normalizeDocId(sourcePath)\n const sourceDirectory = posix.dirname(sourceDocId)\n const configuredId = typeof frontmatter.id === 'string' && frontmatter.id.trim()\n ? stripNumberPrefix(frontmatter.id.trim())\n : null\n const docId = configuredId\n ? normalizeDocId(sourceDirectory === '.' ? configuredId : posix.join(sourceDirectory, configuredId))\n : sourceDocId\n // Docusaurus collapses a source `index` document by default, but an explicit\n // `slug: index` remains a literal route. Keep those two cases distinct.\n const defaultNavigationId = defaultDocusaurusRouteId(docId) ?? fallback.navigationId\n const configuredSlug = typeof frontmatter.slug === 'string' ? frontmatter.slug.trim() : ''\n const navigationId = configuredSlug\n ? routeFromSlug(\n configuredSlug,\n defaultNavigationId,\n sourceDirectory === '.' ? '' : sourceDirectory,\n ) ?? defaultNavigationId\n : defaultNavigationId\n const position = typeof frontmatter.sidebar_position === 'number'\n && Number.isFinite(frontmatter.sidebar_position)\n ? frontmatter.sidebar_position\n : undefined\n return {\n identity: { id: storageIdForRoute(navigationId), navigationId },\n descriptor: {\n sourcePath: sourcePath.replace(/\\\\/g, '/'),\n docId,\n navigationId,\n ...(position === undefined ? {} : { sidebarPosition: position }),\n },\n }\n}\n\nfunction sourceReferenceKey(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/^\\/+/, '').replace(/\\.(?:mdx?)$/i, '').replace(/\\/$/, '')\n}\n\ninterface SourceHeading {\n index: number\n level: number\n id: string | null\n}\n\nfunction sourceHeadings(body: string): Array<SourceHeading> {\n const headings: Array<SourceHeading> = []\n const lines = body.split('\\n')\n let fence: string | null = null\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = null\n continue\n }\n if (fence) continue\n const heading = line.match(/^ {0,3}(#{2,6})\\s+(.+?)\\s*#*\\s*$/)\n if (!heading) continue\n const preceding = lines[index - 1]?.match(/^<a id=\"([\\p{L}\\p{N}_.:$-]{1,120})\"><\\/a>$/u)\n // The runtime extracts rendered heading text from MDX elements. Only\n // plain text can be mapped reliably without evaluating authored MDX.\n const plainText = !/[<>{}\\[\\]`*_]/.test(heading[2])\n const generatedId = plainText\n ? heading[2].normalize('NFC').toLowerCase()\n .replace(/[^\\p{L}\\p{M}\\p{N}]+/gu, '-').replace(/(^-|-$)/g, '')\n : null\n headings.push({ index, level: heading[1].length, id: preceding?.[1] ?? generatedId })\n }\n return headings\n}\n\n/**\n * Preserve original-language fragments in translated Docusaurus pages when\n * their heading outlines are identical. An inserted alias never replaces an\n * explicit translated ID, and ambiguous or edited outlines are left alone.\n */\nexport function addDocusaurusTranslatedHeadingAliases(pages: Array<MigrationPage>): void {\n const byRoute = new Map(pages.map((page) => [page.navigationId, page]))\n for (const page of pages) {\n const locale = page.source.match(/(?:^|[/#])i18n\\/([A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8})*)\\/docusaurus-plugin-content-docs\\//)?.[1]\n if (!locale) continue\n const originalRoute = page.navigationId === locale ? 'introduction'\n : page.navigationId.startsWith(`${locale}/`) ? page.navigationId.slice(locale.length + 1) : null\n if (!originalRoute) continue\n const original = byRoute.get(originalRoute)\n if (!original) continue\n const originalHeadings = sourceHeadings(original.body)\n const translatedHeadings = sourceHeadings(page.body)\n if (!originalHeadings.length || originalHeadings.length !== translatedHeadings.length\n || originalHeadings.some((heading, index) => heading.level !== translatedHeadings[index].level)) continue\n\n const occupied = new Set(translatedHeadings.map((heading) => heading.id).filter((id): id is string => !!id))\n for (const match of page.body.matchAll(/<a\\s+id=\"([^\"]+)\"/g)) occupied.add(match[1])\n const originalIdCounts = new Map<string, number>()\n for (const heading of originalHeadings) {\n if (heading.id) originalIdCounts.set(heading.id, (originalIdCounts.get(heading.id) ?? 0) + 1)\n }\n const aliases = new Map<number, string>()\n for (let index = 0; index < originalHeadings.length; index++) {\n const id = originalHeadings[index].id\n if (!id || occupied.has(id) || originalIdCounts.get(id) !== 1) continue\n aliases.set(translatedHeadings[index].index, id)\n occupied.add(id)\n }\n if (aliases.size) page.body = page.body.split('\\n').flatMap((line, index) => {\n const alias = aliases.get(index)\n return alias ? [`<a id=\"${alias}\"></a>`, line] : [line]\n }).join('\\n')\n }\n}\n\n/** Fill Docusaurus category card lists from the sidebar tree they summarize. */\nexport function expandDocusaurusDocCardLists(\n pages: Array<MigrationPage>,\n config: MigrationDocsConfig,\n sourceRoutes: ReadonlySet<string>,\n): void {\n const pageByRoute = new Map(pages.map((page) => [page.navigationId, page]))\n const containsRoute = (items: Array<string | MigrationNavigationGroup>, route: string): boolean =>\n items.some((item) => typeof item === 'string'\n ? item === route\n : containsRoute(item.pages, route))\n const findGroup = (items: Array<string | MigrationNavigationGroup>, route: string): MigrationNavigationGroup | undefined => {\n for (const item of items) {\n if (typeof item === 'string' || !containsRoute(item.pages, route)) continue\n return findGroup(item.pages, route) ?? item\n }\n return undefined\n }\n const firstRoute = (items: Array<string | MigrationNavigationGroup>): string | undefined => {\n for (const item of items) {\n if (typeof item === 'string') return item\n const candidate = firstRoute(item.pages)\n if (candidate) return candidate\n }\n return undefined\n }\n for (const page of pages) {\n if (!sourceRoutes.has(page.navigationId)) continue\n const group = config.tabs.map((tab) => findGroup([\n ...(tab.pages ?? []),\n ...(tab.groups ?? []),\n ], page.navigationId)).find(Boolean)\n if (!group) {\n page.body = page.body.replace(/<div data-thally-doc-card-list=\"\"\\s*\\/>/g, '')\n continue\n }\n const cards = group.pages.flatMap((item) => {\n if (typeof item === 'string') {\n if (item === page.navigationId) return []\n const target = pageByRoute.get(item)\n return [{ title: target?.title ?? item.split('/').at(-1) ?? item, route: item }]\n }\n const slug = slugifySegment(item.group)\n const routes = [...item.pages].flatMap((child) => typeof child === 'string' ? [child] : [])\n const route = routes.find((candidate) => candidate === slug || candidate.endsWith(`/${slug}`))\n ?? firstRoute(item.pages)\n return route ? [{ title: item.group, route }] : []\n })\n const markup = cards.length\n ? `<CardGroup>\\n${cards.map(({ title, route }) => ` <Card title={${JSON.stringify(title)}} href={${JSON.stringify(`/${route === 'introduction' ? '' : route}`)}} />`).join('\\n')}\\n</CardGroup>`\n : ''\n page.body = page.body.replace(/<div data-thally-doc-card-list=\"\"\\s*\\/>/g, markup)\n if (markup && !page.body.includes(markup)) page.body = [page.body.trim(), markup].filter(Boolean).join('\\n\\n')\n }\n}\n\n/**\n * Rewrite Docusaurus file/doc-id links after every final slug is known. This is\n * deliberately line based so examples inside fenced code remain byte-for-byte\n * source content. A link whose `#fragment` uses a case-preserved heading id\n * (live Docusaurus keeps case intact; Thally always lowercases its auto-slug)\n * is left as-is here — `preserveDocusaurusLinkedAnchors` (repository.ts)\n * repairs those afterward by adding an explicit anchor matching the literal\n * fragment, which also covers repeated table-field ids that this\n * path-only resolver has no visibility into.\n */\nexport function rewriteDocusaurusLinks(\n body: string,\n current: DocusaurusPageDescriptor,\n descriptors: Array<DocusaurusPageDescriptor>,\n options: {\n sourceOrigin?: string\n onExternalLink?: (target: string) => void\n /** Copy destinations, without a leading slash, after asset budgeting. */\n assetPaths?: ReadonlySet<string>\n } = {},\n): string {\n const routes = new Map<string, string>()\n for (const descriptor of descriptors) {\n const sourceKey = sourceReferenceKey(descriptor.sourcePath)\n routes.set(sourceKey, descriptor.navigationId)\n routes.set(sourceReferenceKey(descriptor.docId), descriptor.navigationId)\n routes.set(sourceReferenceKey(descriptor.navigationId), descriptor.navigationId)\n const sourceRoute = pageIdFromReference(sourceKey)\n if (sourceRoute) routes.set(sourceRoute, descriptor.navigationId)\n }\n const currentDirectory = posix.dirname(sourceReferenceKey(current.sourcePath))\n\n function copiedAssetTarget(target: string): string | null {\n if (!target.startsWith('/') || target.startsWith('//') || target.includes('\\\\')) return null\n const suffixIndex = target.search(/[?#]/)\n const path = suffixIndex >= 0 ? target.slice(0, suffixIndex) : target\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n if (path.startsWith('/docs/') && options.assetPaths?.has(path.slice('/docs/'.length))) {\n return `/${path.slice('/docs/'.length)}${suffix}`\n }\n return options.assetPaths?.has(path.slice(1)) ? target : null\n }\n\n function rewriteTarget(target: string): string {\n if (!target || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(target)) return target\n if (target.startsWith('#')) return target\n const suffixIndex = target.search(/[?#]/)\n const path = suffixIndex >= 0 ? target.slice(0, suffixIndex) : target\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n // Docusaurus sites often publish `static/img/foo` as `/img/foo` while\n // authors refer to it as `/docs/img/foo`. Strip the docs mount only after\n // the copy pass proves the resulting asset exists.\n const copiedAsset = copiedAssetTarget(target)\n if (copiedAsset) return copiedAsset\n const candidates = path.startsWith('/')\n ? [\n sourceReferenceKey(path),\n sourceReferenceKey(path).replace(/^docs\\//, ''),\n sourceReferenceKey(path).replace(/^docs\\/(?:next|current|latest)\\//, ''),\n ]\n : [\n sourceReferenceKey(posix.normalize(posix.join(currentDirectory, path))),\n sourceReferenceKey(path),\n ]\n const route = candidates.map((candidate) => routes.get(candidate)).find(Boolean)\n if (!route) {\n if (path.startsWith('/') && path !== '/' && options.sourceOrigin) {\n options.onExternalLink?.(target)\n return new URL(target, options.sourceOrigin).toString()\n }\n return target\n }\n return `${route === 'introduction' ? '/' : `/${route}`}${suffix}`\n }\n\n let codeFence: string | null = null\n return body.split('\\n').map((line) => {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (fence) {\n if (!codeFence) codeFence = fence[1]\n else if (fence[1][0] === codeFence[0] && fence[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(fence[0].length))) codeFence = null\n return line\n }\n if (codeFence) return line\n return line\n .replace(/(\\]\\()([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(target)}`)\n .replace(/(\\bhref=\")([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(target)}${suffix}`)\n .replace(/(\\bsrc=\")([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${copiedAssetTarget(target) ?? target}${suffix}`)\n // Markdown reference links carry their destination in a later\n // definition line. Docusaurus resolves `[label]` through that line, so\n // rewriting only inline links leaves an apparently working link in the\n // content whose click still goes to `/page.md` and 404s on Thally.\n .replace(/^(\\s{0,3}\\[[^\\]]+\\]:\\s*)(<[^>]+>|\\S+)/, (_match, prefix: string, destination: string) => {\n const bracketed = destination.startsWith('<') && destination.endsWith('>')\n const target = bracketed ? destination.slice(1, -1) : destination\n const rewritten = rewriteTarget(target)\n return `${prefix}${bracketed ? `<${rewritten}>` : rewritten}`\n })\n }).join('\\n')\n}\n\n/** Read a static Docusaurus site origin for links outside imported docs. */\nexport function readDocusaurusSiteOrigin(repositoryRoot: string): string | undefined {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return undefined\n const address = readBoundedText(configPath).match(/\\burl['\"]?\\s*:\\s*(['\"])(https?:\\/\\/[^'\"]+)\\1/)?.[2]\n if (!address) return undefined\n try {\n return new URL(address).origin\n } catch {\n return undefined\n }\n}\n\nfunction readBoundedText(path: string): string {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('The Docusaurus sidebar config is larger than 20 MB and could not be imported.')\n }\n return readFileSync(path, 'utf8')\n}\n\nfunction matchingObjectLiteral(source: string, start: number): string | null {\n let depth = 0\n let quote: string | null = null\n let isEscaped = false\n let lineComment = false\n let blockComment = false\n let objectStart = -1\n\n for (let index = start; index < source.length; index++) {\n const char = source[index]\n const next = source[index + 1]\n if (lineComment) {\n if (char === '\\n') lineComment = false\n continue\n }\n if (blockComment) {\n if (char === '*' && next === '/') {\n blockComment = false\n index++\n }\n continue\n }\n if (quote) {\n if (isEscaped) isEscaped = false\n else if (char === '\\\\') isEscaped = true\n else if (char === quote) quote = null\n continue\n }\n if (char === '/' && next === '/') {\n lineComment = true\n index++\n continue\n }\n if (char === '/' && next === '*') {\n blockComment = true\n index++\n continue\n }\n if (char === '\"' || char === \"'\" || char === '`') {\n quote = char\n continue\n }\n if (char === '{') {\n if (objectStart < 0) objectStart = index\n depth++\n } else if (char === '}' && objectStart >= 0) {\n depth--\n if (depth === 0) return source.slice(objectStart, index + 1)\n } else if (objectStart < 0 && !/\\s/.test(char)) {\n return null\n }\n }\n return null\n}\n\nfunction parseStaticSidebarModule(source: string): Record<string, unknown> {\n const bindings = new Map<string, Record<string, unknown>>()\n const normalizedSource = replaceExternalFbContent(source)\n const parseFailures: Array<string> = []\n const assignmentPatterns = [\n /\\bmodule\\.exports\\s*=\\s*/g,\n /\\bexport\\s+default\\s*/g,\n /\\b(?:const|let|var)\\s+[A-Za-z_$][\\w$]*(?:\\s*:\\s*[^=;]+)?\\s*=\\s*/g,\n ]\n const candidates = assignmentPatterns.flatMap((pattern) => [...normalizedSource.matchAll(pattern)])\n .sort((left, right) => (left.index ?? 0) - (right.index ?? 0))\n\n for (const candidate of candidates) {\n const literal = matchingObjectLiteral(normalizedSource, (candidate.index ?? 0) + candidate[0].length)\n if (!literal) continue\n try {\n const substituted = [...bindings].reduce(\n (value, [name, binding]) => value.replace(\n new RegExp(`(:\\\\s*)${name}\\\\b`, 'g'),\n (_match, prefix: string) => `${prefix}${JSON.stringify(binding)}`,\n ),\n literal,\n )\n const parsed = JSON5.parse(substituted) as unknown\n const object = objectValue(parsed)\n if (!object) continue\n const bindingName = candidate[0].match(/\\b(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)/)?.[1]\n if (bindingName) {\n bindings.set(bindingName, object)\n continue\n }\n return object\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n const line = Number(message.match(/at (\\d+):/)?.[1] ?? 0)\n const context = line > 0 ? literal.split('\\n').slice(Math.max(0, line - 2), line + 1).join(' ') : ''\n parseFailures.push(`${message}${context ? ` near ${context}` : ''}`)\n // Try the next assignment. Expressions and function calls are rejected.\n }\n }\n const exportedBinding = normalizedSource.match(/\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\b/)?.[1]\n ?? normalizedSource.match(/\\bmodule\\.exports\\s*=\\s*([A-Za-z_$][\\w$]*)\\b/)?.[1]\n if (exportedBinding && bindings.has(exportedBinding)) return bindings.get(exportedBinding)!\n throw new Error(`Sidebar config is executable or outside the supported data-only syntax.${parseFailures[0] ? ` ${parseFailures[0]}` : ''}`)\n}\n\nfunction replaceExternalFbContent(source: string): string {\n const marker = '...fbContent('\n let result = source\n let searchFrom = 0\n while (true) {\n const start = result.indexOf(marker, searchFrom)\n if (start < 0) return result.replace(/,\\s*,/g, ',')\n const objectStart = result.indexOf('{', start + marker.length)\n if (objectStart < 0) return result\n const objectLiteral = matchingObjectLiteral(result, objectStart)\n if (!objectLiteral) {\n searchFrom = start + marker.length\n continue\n }\n const objectEnd = objectStart + objectLiteral.length\n const close = result.indexOf(')', objectEnd)\n if (close < 0) return result\n const externalMatch = /\\bexternal\\s*:\\s*/g.exec(objectLiteral)\n let replacement = ''\n if (externalMatch) {\n const arrayStart = objectLiteral.indexOf('[', externalMatch.index + externalMatch[0].length)\n if (arrayStart >= 0) {\n const array = matchingArrayLiteral(objectLiteral, arrayStart)\n if (array) replacement = array.slice(1, -1)\n }\n }\n let replaceEnd = close + 1\n if (!replacement) {\n const trailingComma = result.slice(replaceEnd).match(/^\\s*,/)\n if (trailingComma) replaceEnd += trailingComma[0].length\n }\n result = `${result.slice(0, start)}${replacement}${result.slice(replaceEnd)}`\n searchFrom = start + replacement.length\n }\n}\n\nfunction matchingArrayLiteral(source: string, start: number): string | null {\n let depth = 0\n let quote = ''\n let isEscaped = false\n for (let index = start; index < source.length; index++) {\n const character = source[index]\n if (quote) {\n if (isEscaped) isEscaped = false\n else if (character === '\\\\') isEscaped = true\n else if (character === quote) quote = ''\n continue\n }\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character\n continue\n }\n if (character === '[') depth++\n if (character === ']' && --depth === 0) return source.slice(start, index + 1)\n }\n return null\n}\n\nfunction configuredSidebarPath(repositoryRoot: string): string | null {\n for (const filename of ['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']) {\n const path = resolveWithin(repositoryRoot, filename)\n if (!existsSync(path)) continue\n const source = readBoundedText(path)\n // A site can register other docs plugins before the classic preset. Their\n // sidebarPath belongs to a different content root (Docusaurus registers\n // its community plugin before the main docs preset, for example).\n for (const docs of source.matchAll(/\\bdocs\\s*:\\s*/g)) {\n const object = matchingObjectLiteral(source, (docs.index ?? 0) + docs[0].length)\n const candidate = object && staticStringField(object, 'sidebarPath')?.replace(/^\\.\\//, '')\n if (candidate) {\n const resolved = resolveWithin(repositoryRoot, candidate)\n if (existsSync(resolved) && lstatSync(resolved).isFile()) return candidate\n }\n }\n const match = source.match(/\\bsidebarPath\\s*:\\s*(?:require\\.resolve\\(\\s*)?(['\"])([^'\"]+)\\1/)\n if (!match) continue\n const candidate = match[2].replace(/^\\.\\//, '')\n const resolved = resolveWithin(repositoryRoot, candidate)\n if (existsSync(resolved) && lstatSync(resolved).isFile()) return candidate\n }\n return null\n}\n\n/** Read the configured/default sidebar without running the source module. */\nexport function readDocusaurusSidebars(repositoryRoot: string, versionedSidebarPath?: string): DocusaurusSidebars | null {\n // Archived versions carry their own sidebar file. Resolve it within the\n // project and parse it as data; never load source-controlled code.\n const configured = versionedSidebarPath ?? configuredSidebarPath(repositoryRoot)\n const sourcePath = [configured, ...(versionedSidebarPath ? [] : SIDEBAR_FILENAMES)]\n .filter((value): value is string => Boolean(value))\n .find((candidate) => {\n const path = resolveWithin(repositoryRoot, candidate)\n return existsSync(path) && lstatSync(path).isFile()\n })\n if (!sourcePath) return null\n const absolutePath = resolveWithin(repositoryRoot, sourcePath)\n const source = readBoundedText(absolutePath)\n const parsed = extname(sourcePath).toLowerCase() === '.json'\n ? objectValue(JSON5.parse(source))\n : parseStaticSidebarModule(source)\n if (!parsed) throw new Error('Docusaurus sidebar config must export an object.')\n return { config: parsed, sourcePath }\n}\n\nfunction namedExportObjectLiteralText(source: string, name: string): string | null {\n const normalizedSource = replaceExternalFbContent(source)\n const match = new RegExp(`\\\\bexport\\\\s+(?:const|let|var)\\\\s+${name}\\\\b(?:\\\\s*:\\\\s*[^=;]+)?\\\\s*=\\\\s*`).exec(normalizedSource)\n if (!match) return null\n return matchingObjectLiteral(normalizedSource, match.index + match[0].length)\n}\n\n/**\n * Pluck just the `redirects: [...]` array out of a plugin options object's\n * literal text, rather than `JSON5.parse`-ing the whole object — the Oasis\n * shape (a real, reproduced example) has a sibling `createRedirects(...) {\n * ... }` method in the same object literal, which is not valid JSON5 and\n * would otherwise fail the whole object and lose the `redirects` array too.\n */\nfunction redirectEntriesFromObjectLiteralText(objectLiteral: string): Array<{ source: string; destination: string }> {\n const match = /\\bredirects\\s*:\\s*/.exec(objectLiteral)\n if (!match) return []\n const arrayStart = objectLiteral.indexOf('[', match.index + match[0].length)\n if (arrayStart < 0) return []\n const arrayLiteral = matchingArrayLiteral(objectLiteral, arrayStart)\n if (!arrayLiteral) return []\n let parsed: unknown\n try {\n parsed = JSON5.parse(arrayLiteral)\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n const entries: Array<{ source: string; destination: string }> = []\n for (const raw of parsed) {\n const entry = objectValue(raw)\n if (!entry || typeof entry.to !== 'string') continue\n const froms = Array.isArray(entry.from) ? entry.from : [entry.from]\n for (const from of froms) {\n if (typeof from !== 'string') continue\n if (!isRedirectPathSafe(from, entry.to)) continue\n entries.push({ source: from, destination: entry.to })\n }\n }\n return entries\n}\n\n/**\n * Parse a `@docusaurus/plugin-client-redirects` `Options` object: either an\n * object literal written inline in the plugin's config entry, or (Oasis's\n * shape) a named export in a separate module the config imports, e.g.\n * `redirects.ts` exporting `redirectsOptions`. Only a literal `redirects:\n * [{ from, to }]` array is understood — `from` may be a single path or an\n * array of paths, both valid per the plugin's own docs. Its `createRedirects`\n * function computes redirects dynamically and can't be evaluated statically,\n * so its presence is warned about rather than silently ignored.\n */\nexport function readDocusaurusRedirects(\n repositoryRoot: string,\n warnings: Array<MigrationWarning>,\n): Array<{ source: string; destination: string }> {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return []\n const configSource = readBoundedText(configPath)\n const pluginMatch = /['\"]@docusaurus\\/plugin-client-redirects['\"]\\s*,\\s*/.exec(configSource)\n if (!pluginMatch) return []\n const afterPlugin = configSource.slice(pluginMatch.index + pluginMatch[0].length)\n const warnAboutCreateRedirects = (source: string): void => {\n if (!/\\bcreateRedirects\\s*[:(]/.test(source)) return\n warnings.push({\n code: 'unsupported-config',\n message: \"The redirects plugin's createRedirects function computes redirects dynamically and cannot be evaluated during migration; add its redirects manually.\",\n })\n }\n warnAboutCreateRedirects(configSource)\n // Case 1: the plugin's options object is written inline.\n const inlineLiteral = matchingObjectLiteral(configSource, pluginMatch.index + pluginMatch[0].length)\n if (inlineLiteral) return redirectEntriesFromObjectLiteralText(inlineLiteral)\n // Case 2: the options are an identifier imported from another module.\n const identifier = afterPlugin.match(/^([A-Za-z_$][\\w$]*)/)?.[1]\n if (!identifier) return []\n const importMatch = new RegExp(`import\\\\s*\\\\{[^}]*\\\\b${identifier}\\\\b[^}]*\\\\}\\\\s*from\\\\s*(['\"])([^'\"]+)\\\\1`).exec(configSource)\n ?? new RegExp(`import\\\\s+${identifier}\\\\s+from\\\\s*(['\"])([^'\"]+)\\\\1`).exec(configSource)\n const modulePath = importMatch?.[2]\n if (!modulePath || !modulePath.startsWith('.')) return []\n let resolvedPath: string | undefined\n try {\n resolvedPath = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs']\n .map((extension) => resolveWithin(repositoryRoot, `${modulePath.replace(/^\\.\\//, '')}${extension}`))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile())\n } catch {\n return []\n }\n if (!resolvedPath) return []\n const moduleSource = readBoundedText(resolvedPath)\n warnAboutCreateRedirects(moduleSource)\n const literal = namedExportObjectLiteralText(moduleSource, identifier)\n return literal ? redirectEntriesFromObjectLiteralText(literal) : []\n}\n\nfunction readCategoryMetadata(contentRoot: string, directory: string): CategoryMetadata {\n for (const filename of CATEGORY_FILENAMES) {\n const path = resolveWithin(contentRoot, posix.join(directory, filename))\n if (!existsSync(path) || !lstatSync(path).isFile()) continue\n try {\n const raw = readBoundedText(path)\n const parsed = filename.endsWith('.json') ? JSON5.parse(raw) : parseYaml(raw)\n const object = objectValue(parsed)\n if (!object) return {}\n return {\n ...(typeof object.label === 'string' ? { label: object.label } : {}),\n ...(typeof object.position === 'number' ? { position: object.position } : {}),\n ...('link' in object ? { link: object.link } : {}),\n }\n } catch {\n return {}\n }\n }\n return {}\n}\n\nfunction descriptorSort(left: DocusaurusPageDescriptor, right: DocusaurusPageDescriptor): number {\n const leftPosition = left.sidebarPosition ?? Number.MAX_SAFE_INTEGER\n const rightPosition = right.sidebarPosition ?? Number.MAX_SAFE_INTEGER\n if (leftPosition !== rightPosition) return leftPosition - rightPosition\n return left.sourcePath.localeCompare(right.sourcePath, undefined, { numeric: true })\n}\n\nfunction registerDoc(docId: string, context: ProjectionContext): string | null {\n const key = normalizeDocId(docId)\n const descriptor = context.descriptorByDocId.get(key)\n ?? context.descriptors.find((page) => page.navigationId === docusaurusRouteId(key))\n if (!descriptor) {\n context.warnings.push({\n code: 'missing-page',\n message: 'A Docusaurus sidebar document did not resolve to an imported page.',\n source: docId,\n })\n return null\n }\n context.referencedNavigationIds.add(descriptor.navigationId)\n return descriptor.navigationId\n}\n\nfunction generatedIndexPage(\n label: string,\n linkValue: unknown,\n context: ProjectionContext,\n): string | null {\n const link = objectValue(linkValue)\n if (!link) return null\n if (link.type === 'doc' && typeof link.id === 'string') return registerDoc(link.id, context)\n if (link.type !== 'generated-index') return null\n const fallback = `category/${slugifySegment(label)}`\n const unprefixedNavigationId = typeof link.slug === 'string'\n ? routeFromSlug(link.slug, fallback) ?? fallback\n : fallback\n const navigationId = context.routePrefix\n && unprefixedNavigationId !== context.routePrefix\n && !unprefixedNavigationId.startsWith(`${context.routePrefix}/`)\n ? posix.join(context.routePrefix, unprefixedNavigationId)\n : unprefixedNavigationId\n if (!context.generatedIds.has(navigationId)\n && !context.descriptors.some((page) => page.navigationId === navigationId)) {\n const description = typeof link.description === 'string'\n ? link.description\n : `Browse the ${label} documentation.`\n context.generatedPages.push({\n id: storageIdForRoute(navigationId),\n navigationId,\n title: typeof link.title === 'string' ? link.title : label,\n description,\n keywords: Array.isArray(link.keywords)\n ? link.keywords.filter((value): value is string => typeof value === 'string')\n : [],\n body: description,\n source: `${context.sourceUrl}#${context.sidebarSource}`,\n })\n context.generatedIds.add(navigationId)\n }\n context.referencedNavigationIds.add(navigationId)\n return navigationId\n}\n\nconst DOCUSAURUS_HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/\n\nfunction findDocusaurusConfigPath(repositoryRoot: string): string | null {\n return ['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']\n .map((filename) => resolveWithin(repositoryRoot, filename))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile()) ?? null\n}\n\n/**\n * Extract a static `--ifm-color-primary` accent from the classic theme's\n * `customCss` file (Infima's own theming convention: a `:root` block for\n * light mode, an `html[data-theme='dark']` block for dark mode). Its\n * `light`/`dark` blocks are normal, like Fern's (unlike Mintlify's inverted\n * schema `site.colors` otherwise follows), so they're swapped the same way\n * `fernThemeColors` does to give downstream consumers one consistent\n * contract.\n */\nexport function readDocusaurusThemeColor(repositoryRoot: string): { light?: string; dark?: string } | undefined {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return undefined\n const configSource = readBoundedText(configPath)\n const cssRelativePath = configSource.match(/\\bcustomCss\\s*:\\s*(?:\\[\\s*)?(?:require\\.resolve\\(\\s*)?(['\"])([^'\"]+)\\1/)?.[2]\n if (!cssRelativePath) return undefined\n let cssPath: string\n try {\n cssPath = resolveWithin(repositoryRoot, cssRelativePath.replace(/^\\.\\//, ''))\n } catch {\n return undefined\n }\n if (!existsSync(cssPath) || !lstatSync(cssPath).isFile()) return undefined\n const css = readBoundedText(cssPath)\n const pick = (block: string | undefined): string | undefined => {\n const value = block?.match(/--ifm-color-primary\\s*:\\s*([^;]+);/)?.[1]?.trim()\n return value && DOCUSAURUS_HEX_COLOR.test(value) ? value : undefined\n }\n const lightMode = pick(css.match(/:root\\s*\\{([^}]*)\\}/)?.[1])\n const darkMode = pick(css.match(/\\[data-theme=(['\"])dark\\1\\]\\s*\\{([^}]*)\\}/)?.[2])\n const colors: { light?: string; dark?: string } = {}\n if (darkMode) colors.light = darkMode\n if (lightMode) colors.dark = lightMode\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\nexport interface DocusaurusSiteSettings {\n name?: string\n description?: string\n navbarTitle?: string\n defaultColorMode?: 'light' | 'dark'\n logo?: { light: string; dark?: string; showTitle?: boolean }\n favicon?: string\n /** Docusaurus serves the classic docs plugin below /docs unless configured otherwise. */\n docsRouteBasePath: string\n navbarLinks: Array<{ label: string; href?: string; docId?: string; sidebarId?: string; docsPluginId?: string }>\n footerLinks: NonNullable<MigrationDocsConfig['footer']>['links']\n copyright?: string\n}\n\nfunction propertyStart(source: string, name: string): number {\n // Only property positions count. A bare word in a comment or a value must\n // never become executable configuration during repository migration.\n const pattern = new RegExp(`(?:^|[,{\\\\n])\\\\s*[\"']?${name}[\"']?\\\\s*:\\\\s*`, 'm')\n const match = pattern.exec(source)\n return match ? match.index + match[0].length : -1\n}\n\nfunction staticStringBindings(source: string): Map<string, string> {\n const bindings = new Map<string, string>()\n for (const match of source.matchAll(/\\bconst\\s+([A-Z][A-Z0-9_]*)\\s*=\\s*((?:\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'))/g)) {\n try {\n const value = JSON5.parse(match[2]) as unknown\n if (typeof value === 'string') bindings.set(match[1], value)\n } catch {\n // Executable or malformed declarations cannot become imported links.\n }\n }\n return bindings\n}\n\nfunction staticArrayField(source: string, name: string): string | null {\n const start = propertyStart(source, name)\n return start < 0 ? null : matchingArrayLiteral(source, start)\n}\n\nfunction staticObjectEntries(array: string | null): Array<string> {\n if (!array) return []\n const entries: Array<string> = []\n let afterDelimiter = 1\n let quote = ''\n let lineComment = false\n let blockComment = false\n for (let index = 1; index < array.length - 1; index++) {\n const char = array[index]\n const next = array[index + 1]\n if (lineComment) {\n if (char === '\\n') lineComment = false\n continue\n }\n if (blockComment) {\n if (char === '*' && next === '/') { blockComment = false; index++ }\n continue\n }\n if (quote) {\n if (char === '\\\\') { index++; continue }\n if (char === quote) quote = ''\n continue\n }\n if (char === '/' && next === '/') { lineComment = true; index++; continue }\n if (char === '/' && next === '*') { blockComment = true; index++; continue }\n if (char === '\"' || char === \"'\" || char === '`') { quote = char; continue }\n if (char === ',') { afterDelimiter = index + 1; continue }\n if (char !== '{') continue\n const literal = matchingObjectLiteral(array, index)\n if (!literal) continue\n const lead = array.slice(afterDelimiter, index)\n .replace(/\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*/g, '').trim()\n // `isDev && { ... }` is a conditional entry; never assume it appears in\n // production just because its object literal can be read statically.\n if (!lead) entries.push(literal)\n index += literal.length - 1\n }\n return entries\n}\n\nfunction staticStringField(source: string, name: string, bindings?: Map<string, string>): string | undefined {\n const start = propertyStart(source, name)\n if (start < 0) return undefined\n const quoted = source.slice(start).match(/^(\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*')/)\n if (!quoted) {\n const binding = source.slice(start).match(/^([A-Z][A-Z0-9_]*)\\b/)?.[1]\n return binding ? bindings?.get(binding) : undefined\n }\n try {\n const parsed = JSON5.parse(quoted[1]) as unknown\n return typeof parsed === 'string' ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\n/** Project Docusaurus' static site identity and footer without loading config code. */\nexport function readDocusaurusSiteSettings(repositoryRoot: string): DocusaurusSiteSettings {\n const empty: DocusaurusSiteSettings = { docsRouteBasePath: 'docs', defaultColorMode: 'light', navbarLinks: [], footerLinks: [] }\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return empty\n const source = readBoundedText(configPath)\n const bindings = staticStringBindings(source)\n const presets = staticArrayField(source, 'presets')\n const classicDocs = presets && [...presets.matchAll(/[\"']?docs[\"']?\\s*:\\s*/g)]\n .map((match) => matchingObjectLiteral(presets, (match.index ?? 0) + match[0].length))\n .find((object): object is string => Boolean(object))\n const docsRouteBasePath = classicDocs && staticStringField(classicDocs, 'routeBasePath') || 'docs'\n const themeStart = propertyStart(source, 'themeConfig')\n const theme = themeStart < 0 ? null : matchingObjectLiteral(source, themeStart)\n const colorModeStart = theme ? propertyStart(theme, 'colorMode') : -1\n const colorMode = colorModeStart < 0 ? null : matchingObjectLiteral(theme!, colorModeStart)\n const configuredColorMode = colorMode ? staticStringField(colorMode, 'defaultMode') : undefined\n const defaultColorMode = configuredColorMode === 'dark' ? 'dark' : 'light'\n const navbarStart = theme ? propertyStart(theme, 'navbar') : -1\n const navbar = navbarStart < 0 ? null : matchingObjectLiteral(theme!, navbarStart)\n const logoStart = navbar ? propertyStart(navbar, 'logo') : -1\n const logo = logoStart < 0 ? null : matchingObjectLiteral(navbar!, logoStart)\n const footerStart = theme ? propertyStart(theme, 'footer') : -1\n const footer = footerStart < 0 ? null : matchingObjectLiteral(theme!, footerStart)\n const navbarLinks = navbar ? staticObjectEntries(staticArrayField(navbar, 'items')).flatMap((item) => {\n // A dropdown owns nested links but no single destination. Taking its\n // first child as the parent's href creates duplicate, misleading links.\n if (propertyStart(item, 'items') >= 0 || propertyStart(item, 'dropdownItemsAfter') >= 0) return []\n const docsPluginId = staticStringField(item, 'docsPluginId', bindings)\n const href = staticStringField(item, 'to', bindings)\n ?? staticStringField(item, 'href', bindings)\n const docId = staticStringField(item, 'docId', bindings)\n const sidebarId = staticStringField(item, 'sidebarId', bindings)\n const label = staticStringField(item, 'label', bindings) ?? staticStringField(item, 'aria-label', bindings)\n return label && (href || docId || sidebarId || docsPluginId)\n ? [{ label, ...(href ? { href } : {}), ...(docId ? { docId } : {}),\n ...(sidebarId ? { sidebarId } : {}), ...(docsPluginId ? { docsPluginId } : {}) }]\n : []\n }) : []\n const footerLinks = footer ? staticObjectEntries(staticArrayField(footer, 'links')).flatMap((column) => {\n const heading = staticStringField(column, 'title', bindings)\n if (!heading) return []\n const items = staticObjectEntries(staticArrayField(column, 'items')).flatMap((item) => {\n const href = staticStringField(item, 'to', bindings) ?? staticStringField(item, 'href', bindings)\n const label = staticStringField(item, 'label', bindings)\n return label && href\n ? [{ label, href }]\n : []\n })\n return items.length > 0 ? [{ heading, items }] : []\n }) : []\n // A build-time year expression is the one dynamic Docusaurus copyright\n // pattern that can be represented without evaluating source JavaScript.\n const copyright = footer && propertyStart(footer, 'copyright') >= 0\n ? staticStringField(footer, 'copyright')\n ?? footer.slice(propertyStart(footer, 'copyright')).match(/^`([^`]+)`/)?.[1]\n ?.replace(/\\$\\{new Date\\(\\)\\.getFullYear\\(\\)\\}/g, '{year}')\n : undefined\n return {\n name: staticStringField(source, 'title'),\n description: staticStringField(source, 'tagline'),\n ...(navbar && staticStringField(navbar, 'title') ? { navbarTitle: staticStringField(navbar, 'title') } : {}),\n defaultColorMode,\n docsRouteBasePath,\n ...(logo && staticStringField(logo, 'src') ? {\n logo: {\n light: staticStringField(logo, 'src')!,\n ...(staticStringField(logo, 'srcDark') ? { dark: staticStringField(logo, 'srcDark') } : {}),\n showTitle: Boolean(navbar && staticStringField(navbar, 'title')),\n },\n } : {}),\n ...(staticStringField(source, 'favicon') ? { favicon: staticStringField(source, 'favicon') } : {}),\n navbarLinks,\n footerLinks,\n ...(copyright ? { copyright } : {}),\n }\n}\n\nfunction autogeneratedItems(dirName: string, context: ProjectionContext): Array<string | MigrationNavigationGroup> {\n const normalizedDir = dirName === '.' ? '' : normalizeDocId(dirName)\n const inDirectory = context.descriptors.filter((descriptor) => {\n const source = descriptor.sourcePath.replace(/\\.(?:mdx?)$/i, '')\n return !normalizedDir || source === normalizedDir || source.startsWith(`${normalizedDir}/`)\n })\n const directPages: Array<DocusaurusPageDescriptor> = []\n const childDirectories = new Set<string>()\n for (const descriptor of inDirectory) {\n const source = descriptor.sourcePath.replace(/\\.(?:mdx?)$/i, '')\n const relativePath = normalizedDir ? posix.relative(normalizedDir, source) : source\n const segments = relativePath.split('/').filter(Boolean)\n if (segments.length <= 1) directPages.push(descriptor)\n else childDirectories.add(segments[0])\n }\n\n const pages = directPages.map((descriptor) => ({\n // An index document is the category landing page in Docusaurus. Thally\n // renders it as a child link, so put it before the category's other docs.\n position: descriptor.sidebarPosition ?? (/(?:^|\\/)(?:index|readme)\\.mdx?$/i.test(descriptor.sourcePath)\n ? -1 : Number.MAX_SAFE_INTEGER),\n sortKey: descriptor.sourcePath,\n item: descriptor.navigationId as string | MigrationNavigationGroup,\n }))\n const groups = [...childDirectories].map((segment) => {\n const directory = normalizedDir ? posix.join(normalizedDir, segment) : segment\n const metadata = readCategoryMetadata(context.contentRoot, directory)\n const pages = autogeneratedItems(directory, context)\n // A folder containing only its index document is a direct sidebar doc in\n // Docusaurus. Inventing a category here duplicates the link and moves it\n // after ordered siblings when the folder has no `_category_` metadata.\n if (pages.length === 1 && typeof pages[0] === 'string'\n && !metadata.label && metadata.position === undefined && !metadata.link) {\n const onlyPage = context.descriptors.find((descriptor) => descriptor.navigationId === pages[0])\n if (onlyPage && /(?:^|\\/)(?:index|readme)\\.mdx?$/i.test(onlyPage.sourcePath)) {\n return {\n position: onlyPage.sidebarPosition ?? Number.MAX_SAFE_INTEGER,\n sortKey: segment,\n item: pages[0],\n }\n }\n }\n const landing = generatedIndexPage(metadata.label ?? titleCase(segment), metadata.link, context)\n if (landing && !pages.includes(landing)) pages.unshift(landing)\n return {\n position: metadata.position ?? Number.MAX_SAFE_INTEGER,\n sortKey: segment,\n item: {\n group: metadata.label ?? titleCase(segment),\n pages,\n } satisfies MigrationNavigationGroup,\n }\n })\n // Docusaurus sorts direct docs and child categories in one list. Sorting\n // them separately moves every category below every doc regardless of the\n // authored sidebar_position / _category_.json position.\n return [...pages, ...groups]\n .sort((left, right) => left.position - right.position\n || left.sortKey.localeCompare(right.sortKey, undefined, { numeric: true }))\n .map(({ item }) => {\n if (typeof item === 'string') context.referencedNavigationIds.add(item)\n return item\n })\n}\n\nfunction convertItems(value: unknown, context: ProjectionContext): Array<string | MigrationNavigationGroup> {\n if (typeof value === 'string') {\n const page = registerDoc(value, context)\n return page ? [page] : []\n }\n if (Array.isArray(value)) return value.flatMap((entry) => convertItems(entry, context))\n const object = objectValue(value)\n if (!object) return []\n\n if (object.type === 'doc' || object.type === 'ref') {\n const page = typeof object.id === 'string' ? registerDoc(object.id, context) : null\n return page ? [page] : []\n }\n if (object.type === 'autogenerated') {\n return autogeneratedItems(typeof object.dirName === 'string' ? object.dirName : '.', context)\n }\n if (object.type === 'category') {\n const label = typeof object.label === 'string' ? object.label : 'Documentation'\n const pages = convertItems(object.items, context)\n const landing = generatedIndexPage(label, object.link, context)\n if (landing && !pages.includes(landing)) pages.unshift(landing)\n return pages.length > 0 ? [{ group: label, pages }] : []\n }\n if (object.type === 'link' || object.type === 'html') return []\n\n // Docusaurus category shorthand and sidebar slices are ordinary objects.\n return Object.entries(object).flatMap(([label, items]) => {\n const pages = convertItems(items, context)\n return pages.length > 0 ? [{ group: label, pages }] : []\n })\n}\n\n/** Project explicit and autogenerated Docusaurus sidebars into Thally tabs. */\nexport function projectDocusaurusNavigation(input: {\n sidebars: DocusaurusSidebars | null\n descriptors: Array<DocusaurusPageDescriptor>\n contentRoot: string\n sourceUrl: string\n routePrefix?: string\n}): DocusaurusNavigationResult {\n const warnings: Array<MigrationWarning> = []\n const descriptorByDocId = new Map(input.descriptors.map((page) => [page.docId, page]))\n const context: ProjectionContext = {\n contentRoot: input.contentRoot,\n descriptors: input.descriptors,\n descriptorByDocId,\n generatedPages: [],\n generatedIds: new Set(),\n referencedNavigationIds: new Set(),\n sourceUrl: input.sourceUrl,\n routePrefix: input.routePrefix ?? '',\n sidebarSource: input.sidebars?.sourcePath ?? 'autogenerated sidebar',\n warnings,\n }\n const sidebarEntries: Array<[string, unknown]> = input.sidebars ? Object.entries(input.sidebars.config) : [['docs', [\n { type: 'autogenerated', dirName: '.' },\n ]]]\n const tabs = sidebarEntries.flatMap(([sidebarId, value]) => {\n const converted = convertItems(value, context)\n if (converted.length === 0) return []\n return [{\n tab: sidebarEntries.length === 1 ? 'Documentation' : titleCase(sidebarId),\n // Docusaurus categories are disclosures, including at the sidebar\n // root. Keeping them as Thally root nodes preserves their collapsed\n // state and the authored interleaving of documents and categories.\n pages: converted,\n }]\n })\n\n const unreferenced = input.descriptors\n .filter((page) => !context.referencedNavigationIds.has(page.navigationId))\n .sort(descriptorSort)\n .map((page) => page.navigationId)\n if (unreferenced.length > 0) {\n if (tabs.length === 0) tabs.push({ tab: 'Documentation', pages: [] })\n tabs[0].pages?.push({ group: 'Additional', pages: unreferenced })\n }\n return {\n docsConfig: { tabs },\n generatedPages: context.generatedPages,\n referencedNavigationIds: context.referencedNavigationIds,\n warnings,\n }\n}\n","/**\n * Navigation projection for imported sites. Mintlify's schema is intentionally\n * more expressive than Thally's tab/group model, so complex containers are\n * flattened predictably while preserving page order and nested groups.\n */\n\nimport { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, extname, relative } from 'node:path'\n\nimport { mintlifyLocalizedReference, pageIdFromReference, resolveWithin, trimEdgeSlashes } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationNavigationTab,\n MigrationPage,\n MigrationWarning,\n} from './types.js'\n\ninterface MintlifyPageReference {\n ref: string\n navigationId: string\n locale?: string\n}\n\nconst MAX_MINTLIFY_CONFIG_BYTES = 20_000_000\n\nexport interface MintlifyNavigationResult {\n docsConfig: MigrationDocsConfig\n pageReferences: Array<MintlifyPageReference>\n warnings: Array<MigrationWarning>\n}\n\nexport interface MintlifyProjectionOptions {\n /** Public URL migrations may expose page hrefs including the docs mount path. */\n pathPrefix?: string\n}\n\n/** Preserve Mintlify's implicit `/section` route for section landing pages. */\nexport function addMintlifyDirectoryRedirects(\n config: MigrationDocsConfig,\n pages: Array<MigrationPage>,\n): MigrationDocsConfig {\n const pageIds = new Set(pages.map((page) => page.id))\n const redirects = [...(config.redirects ?? [])]\n const redirectSources = new Set(redirects.map((redirect) => redirect.source.replace(/\\/$/, '') || '/'))\n function hasAuthoredRedirect(source: string): boolean {\n if (redirectSources.has(source)) return true\n return (config.redirects ?? []).some((redirect) => {\n // A trailing catch-all also owns its empty suffix. Do not insert an\n // exact alias that competes with that authored directory behavior.\n const match = redirect.source.match(/^(.*)\\/:[A-Za-z_][A-Za-z0-9_]*\\*\\/?$/)\n return match ? source === match[1] || source.startsWith(`${match[1]}/`) : false\n })\n }\n for (const page of pages) {\n if (!/\\/(?:overview|introduction)$/.test(page.navigationId)) continue\n const parent = page.id.replace(/\\/(?:overview|introduction)$/, '')\n if (!parent || pageIds.has(parent)) continue\n const source = `/${parent}`\n if (hasAuthoredRedirect(source)) continue\n redirects.push({ source, destination: `/${page.id}`, permanent: false })\n redirectSources.add(source)\n }\n\n const navigationOrder: Array<string> = []\n function collectPages(nodes: Array<string | MigrationNavigationGroup>): void {\n for (const node of nodes) {\n if (typeof node === 'string') navigationOrder.push(node)\n else if (!node.hidden) collectPages(node.pages)\n }\n }\n for (const tab of config.tabs) {\n if (!tab.hidden) collectPages([...(tab.pages ?? []), ...(tab.groups ?? [])])\n }\n const pagesByNavigationId = new Map<string, Array<MigrationPage>>()\n for (const page of pages) {\n if (page.hidden) continue\n const variants = pagesByNavigationId.get(page.navigationId) ?? []\n variants.push(page)\n pagesByNavigationId.set(page.navigationId, variants)\n }\n const firstDescendantByDirectory = new Map<string, MigrationPage>()\n for (const navigationId of navigationOrder) {\n for (const page of pagesByNavigationId.get(navigationId) ?? []) {\n const segments = page.id.split('/')\n for (let length = 1; length < segments.length; length++) {\n const directory = segments.slice(0, length).join('/')\n if (!firstDescendantByDirectory.has(directory)) firstDescendantByDirectory.set(directory, page)\n }\n }\n }\n // Mintlify 307s *any* nav-shaped directory path with no page of its own to\n // its first descendant page in navigation order — not only ones an\n // overview/introduction page or an authored redirect already pointed at\n // (e.g. a `product`/`tab`/`group` container path like Upstash's `/redis`,\n // or a plain mid-tree directory like `/vector/sdks/py/example_calls`).\n // `firstDescendantByDirectory` already holds every such directory (built\n // from real page ids in navigation order above), so redirect all of them\n // in one pass; `hasAuthoredRedirect` skips any directory the overview/\n // introduction pass above, or the project's own `redirects:`, already\n // covers, and `pageIds.has(directory)` never overrides a real page.\n for (const [directory, landing] of firstDescendantByDirectory) {\n if (pageIds.has(directory)) continue\n const source = `/${directory}`\n if (hasAuthoredRedirect(source)) continue\n // Match full stored ids, not locale-independent navigation ids: a French\n // directory must never be redirected to an English descendant.\n redirects.push({ source, destination: `/${landing.id}`, permanent: false })\n redirectSources.add(source)\n }\n return redirects.length > 0 ? { ...config, redirects } : config\n}\n\n/**\n * Keep authored page URLs while resolving bare documentation roots to the\n * first visible navigation page. An unrelated `home.mdx` is not evidence that\n * Mintlify served it at `/`; explicit source redirects always take priority.\n */\nexport function addMintlifyHomepageRedirects(\n config: MigrationDocsConfig,\n pages: Array<MigrationPage>,\n): MigrationDocsConfig {\n const defaultPages = new Set(pages\n .filter((page) => !page.locale || page.locale === config.i18n?.defaultLocale)\n .map((page) => page.navigationId))\n function firstPage(nodes: Array<string | MigrationNavigationGroup>): string | undefined {\n for (const node of nodes) {\n if (typeof node === 'string') {\n if (defaultPages.has(node)) return node\n } else if (!node.hidden) {\n const page = firstPage(node.pages)\n if (page) return page\n }\n }\n }\n const homepage = config.tabs.filter((tab) => !tab.hidden)\n .map((tab) => firstPage([...(tab.pages ?? []), ...(tab.groups ?? [])]))\n .find(Boolean)\n if (!homepage || homepage === 'introduction') return config\n const redirects = [...(config.redirects ?? [])]\n const sources = new Set(redirects.map((redirect) => redirect.source.replace(/\\/$/, '') || '/'))\n const roots = ['', ...(config.i18n?.locales ?? [])\n .filter((locale) => locale.code !== config.i18n?.defaultLocale)\n .map((locale) => locale.code)]\n for (const locale of roots) {\n const source = locale ? `/${locale}` : '/'\n if (sources.has(source)) continue\n redirects.push({ source, destination: `${locale ? `/${locale}` : ''}/${homepage}`, permanent: false })\n }\n return { ...config, redirects }\n}\n\nconst LANGUAGE_LABELS: Record<string, string> = {\n ar: 'Arabic',\n de: 'German',\n en: 'English',\n es: 'Spanish',\n fr: 'French',\n hi: 'Hindi',\n it: 'Italian',\n ja: 'Japanese',\n ko: 'Korean',\n nl: 'Dutch',\n pl: 'Polish',\n pt: 'Portuguese',\n ru: 'Russian',\n tr: 'Turkish',\n uk: 'Ukrainian',\n zh: 'Chinese',\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\n/**\n * Some Mintlify sites (e.g. Upstash's docs.json) group `products` under an\n * extra `productGroups: [{ group, products }]` wrapper instead of a bare\n * `products` array directly on the tab. Flatten it into `products` so the\n * existing container handling picks the products up unchanged — otherwise\n * every page and `openapi`/`asyncapi` reference under it is silently\n * invisible to navigation projection and API-spec resolution alike.\n */\nfunction withFlattenedProductGroups(container: Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(container.productGroups)) return container\n const flattened = (container.productGroups as Array<unknown>).flatMap((entry) => {\n const group = objectValue(entry)\n return group && Array.isArray(group.products) ? group.products : []\n })\n if (flattened.length === 0) return container\n return {\n ...container,\n products: [...(Array.isArray(container.products) ? container.products : []), ...flattened],\n }\n}\n\nfunction projectedHref(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const href = value.trim()\n if (!href || /[\\u0000-\\u001f\\u007f]/.test(href)) return undefined\n if (/^(?:javascript|data|vbscript|file):/i.test(href)) return undefined\n const scheme = href.match(/^([a-z][a-z0-9+.-]*):/i)?.[1].toLowerCase()\n if (scheme && !['http', 'https', 'mailto', 'tel'].includes(scheme)) return undefined\n return href\n}\n\nfunction labelFor(value: Record<string, unknown>, fallback: string): string {\n for (const key of ['tab', 'group', 'anchor', 'product', 'dropdown', 'version', 'menu', 'label', 'name', 'title']) {\n if (typeof value[key] === 'string' && value[key]) return String(value[key])\n }\n return fallback\n}\n\nfunction localReference(value: string): string {\n return value.split('#', 1)[0]\n}\n\nfunction jsonPointer(root: unknown, pointer: string): unknown {\n if (!pointer || pointer === '#') return root\n const tokens = pointer.replace(/^#\\/?/, '').split('/').filter(Boolean)\n return tokens.reduce<unknown>((current, token) => {\n if (Array.isArray(current)) {\n const index = Number(token)\n return Number.isSafeInteger(index) && index >= 0 ? current[index] : undefined\n }\n const object = objectValue(current)\n if (!object) return undefined\n return object[token.replace(/~1/g, '/').replace(/~0/g, '~')]\n }, root)\n}\n\nfunction readMintlifyJson(path: string, repositoryRoot: string): unknown {\n if (!existsSync(path) || !lstatSync(path).isFile()) {\n throw new Error(`Mintlify config reference is not a regular file: ${relative(repositoryRoot, path)}`)\n }\n const realPath = realpathSync(path)\n const realRoot = realpathSync(repositoryRoot)\n resolveWithin(realRoot, relative(realRoot, realPath))\n if (lstatSync(realPath).size > MAX_MINTLIFY_CONFIG_BYTES) {\n throw new Error(`Mintlify config reference exceeded ${MAX_MINTLIFY_CONFIG_BYTES / 1_000_000} MB: ${relative(repositoryRoot, path)}`)\n }\n return JSON.parse(readFileSync(realPath, 'utf8')) as unknown\n}\n\nfunction resolveJsonReferences(\n value: unknown,\n currentFile: string,\n repositoryRoot: string,\n stack: Set<string>,\n): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => resolveJsonReferences(entry, currentFile, repositoryRoot, stack))\n }\n const object = objectValue(value)\n if (!object) return value\n if (typeof object.$ref === 'string') {\n const [filePart, pointer = ''] = object.$ref.split('#', 2)\n const referencedFile = filePart\n ? resolveWithin(dirname(currentFile), filePart)\n : currentFile\n const relativePath = relative(repositoryRoot, referencedFile)\n resolveWithin(repositoryRoot, relativePath)\n const stackKey = `${referencedFile}#${pointer}`\n if (stack.has(stackKey)) throw new Error(`Circular Mintlify $ref: ${object.$ref}`)\n stack.add(stackKey)\n const referencedRoot = readMintlifyJson(referencedFile, repositoryRoot)\n const referenced = jsonPointer(referencedRoot, pointer ? `#${pointer}` : '')\n const resolved = resolveJsonReferences(referenced, referencedFile, repositoryRoot, stack)\n stack.delete(stackKey)\n const siblings = Object.fromEntries(\n Object.entries(object)\n .filter(([key]) => key !== '$ref')\n .map(([key, entry]) => [\n key,\n resolveJsonReferences(entry, currentFile, repositoryRoot, stack),\n ]),\n )\n // Mintlify merges sibling keys over object-valued references. Retaining\n // this behavior matters for split navigation files that override one\n // label, link, or visibility flag at the reference site.\n return objectValue(resolved) ? { ...resolved as Record<string, unknown>, ...siblings } : resolved\n }\n return Object.fromEntries(\n Object.entries(object).map(([key, entry]) => [\n key,\n resolveJsonReferences(entry, currentFile, repositoryRoot, stack),\n ]),\n )\n}\n\n/** Read `docs.json`/`mint.json`, including bounded local JSON references. */\nexport function readMintlifyConfig(repositoryRoot: string): Record<string, unknown> | null {\n const configPath = ['docs.json', 'mint.json']\n .map((filename) => resolveWithin(repositoryRoot, filename))\n .find(existsSync)\n if (!configPath) return null\n const raw = readMintlifyJson(configPath, repositoryRoot)\n return resolveJsonReferences(raw, configPath, repositoryRoot, new Set()) as Record<string, unknown>\n}\n\n/** One `openapi`/`asyncapi` value found anywhere in Mintlify's navigation tree. */\nexport interface MintlifyApiSpecReference {\n /** The field's raw value: a repository-relative path, or an `http(s)://` URL. */\n value: string\n kind: 'openapi' | 'asyncapi'\n /** Label of the nearest enclosing tab/anchor/dropdown/product/version/menu, so the resolved spec binds to that tab specifically. Undefined at the navigation root. */\n tabLabel?: string\n /** Set when the source used Mintlify's object form to scope generated pages under a nested directory; Thally can only bind the whole tab, so this is lost and must be warned about. */\n directory?: string\n}\n\n/**\n * Mintlify lets `openapi`/`asyncapi` appear not just at the top-level `api`\n * key but on any navigation container (most commonly a tab:\n * `navigation.tabs[].openapi`, but the same field is honored on an anchor,\n * dropdown, product, version or group too) — Mintlify binds the resulting\n * API reference to whichever tab that container renders under. This walks\n * the whole raw navigation tree (the same shape `convertContainerToTabs`\n * projects) collecting every occurrence, so the caller can resolve and bind\n * each one instead of only ever seeing the single top-level `api` field.\n */\nexport function mintlifyNavigationApiReferences(config: Record<string, unknown>): Array<MintlifyApiSpecReference> {\n const navigation = objectValue(config.navigation) ?? config\n const references: Array<MintlifyApiSpecReference> = []\n const containerKeys = ['tabs', 'anchors', 'products', 'dropdowns', 'versions', 'menus', 'languages'] as const\n const nestedKeys = ['groups', 'pages'] as const\n\n function visit(rawNode: Record<string, unknown>, tabLabel: string | undefined): void {\n const node = withFlattenedProductGroups(rawNode)\n for (const kind of ['openapi', 'asyncapi'] as const) {\n const value = node[kind]\n if (typeof value === 'string' && value.trim()) {\n references.push({ value: value.trim(), kind, tabLabel })\n continue\n }\n // Mintlify also accepts an object form (`{ source, directory }`) to\n // scope a spec's auto-generated operation pages under a nested\n // directory instead of the whole tab. Thally's API reference can't\n // be scoped to a nested path (it always renders under the tab it's\n // bound to), so the spec is still resolved and bound at the tab\n // level — better than vanishing outright — but the caller is told\n // via `directory` so it can warn that the manual scoping was lost.\n const object = objectValue(value)\n if (object && typeof object.source === 'string' && object.source.trim()) {\n references.push({\n value: object.source.trim(),\n kind,\n tabLabel,\n ...(typeof object.directory === 'string' && object.directory.trim()\n ? { directory: object.directory.trim() }\n : {}),\n })\n }\n }\n for (const key of containerKeys) {\n const entries = node[key]\n if (!Array.isArray(entries)) continue\n for (const entry of entries) {\n const object = objectValue(entry)\n if (!object) continue\n // A nested container becomes the new binding tab only at the outer\n // level (Mintlify tabs aren't themselves nested inside other tabs in\n // practice, but anchors/dropdowns can sit inside a tab) — reuse the\n // enclosing tab's label unless this container names its own.\n visit(object, labelFor(object, tabLabel ?? 'Documentation'))\n }\n }\n for (const key of nestedKeys) {\n const entries = node[key]\n if (!Array.isArray(entries)) continue\n for (const entry of entries) {\n if (typeof entry === 'string') continue\n const object = objectValue(entry)\n if (object) visit(object, tabLabel)\n }\n }\n }\n visit(navigation, undefined)\n return references\n}\n\nfunction normalizePageRef(value: string, pathPrefix = ''): string | null {\n if (/^(?:https?:)?\\/\\//i.test(value) || value.startsWith('#')) return null\n let ref = localReference(value).split('?', 1)[0].replace(/^\\/+/, '')\n const prefix = trimEdgeSlashes(pathPrefix)\n if (prefix && (ref === prefix || ref.startsWith(`${prefix}/`))) {\n ref = ref === prefix ? 'introduction' : ref.slice(prefix.length + 1)\n }\n ref = ref.replace(/\\.(?:mdx?|rst|txt)$/i, '')\n // Mintlify routes are case-sensitive and commonly use camelCase filenames\n // (for example `additionalFiles`). Lowercasing here breaks both authored\n // navigation and links even though the source site resolves them correctly.\n return pageIdFromReference(ref, true)\n}\n\ninterface ProjectionContext {\n locale?: string\n defaultPageIds?: ReadonlySet<string>\n pathPrefix?: string\n references: Array<MintlifyPageReference>\n seenReferences: Set<string>\n warnings: Array<MigrationWarning>\n warningKeys: Set<string>\n}\n\nfunction warnOnce(context: ProjectionContext, key: string, message: string): void {\n if (context.warningKeys.has(key)) return\n context.warningKeys.add(key)\n context.warnings.push({ code: 'unsupported-config', message })\n}\n\nfunction iconName(value: unknown): string | undefined {\n if (typeof value === 'string' && value) return value\n const icon = objectValue(value)\n return typeof icon?.name === 'string' && icon.name ? icon.name : undefined\n}\n\nfunction containerPresentation(value: Record<string, unknown>): {\n description?: string\n icon?: string\n} {\n return {\n ...(typeof value.description === 'string' && value.description.trim()\n ? { description: value.description.trim() }\n : {}),\n ...(iconName(value.icon) ? { icon: iconName(value.icon) } : {}),\n }\n}\n\nfunction registerReference(value: string, context: ProjectionContext): string | null {\n const localizedValue = context.locale\n ? mintlifyLocalizedReference(value, context.locale, context.defaultPageIds)\n : value\n const navigationId = normalizePageRef(localizedValue, context.pathPrefix)\n if (!navigationId) return null\n const key = `${context.locale ?? ''}:${value}`\n if (!context.seenReferences.has(key)) {\n context.seenReferences.add(key)\n context.references.push({ ref: value, navigationId, locale: context.locale })\n }\n return navigationId\n}\n\n/**\n * Mintlify lets a `pages` entry name a single OpenAPI operation directly\n * (`\"GET /users\"`) to hand-pick or reorder which operations of an\n * already-`openapi`-scoped ancestor appear, instead of a page file\n * reference. Thally always renders every operation of a bound spec and\n * has no manual-selection equivalent, so these are not migratable pages —\n * treating them as one is what produced a \"did not resolve to a source\n * page\" warning per operation instead of one explanation for the group.\n */\nconst OPENAPI_OPERATION_REF = /^(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\s+\\S/\n\nfunction convertPage(\n value: unknown,\n context: ProjectionContext,\n): string | MigrationNavigationGroup | null {\n if (typeof value === 'string') {\n if (OPENAPI_OPERATION_REF.test(value)) {\n warnOnce(\n context,\n 'openapi-operation-list',\n 'One or more navigation groups hand-pick or reorder individual OpenAPI operations (e.g. \"GET /users\"); '\n + \"Thally always renders every operation of a bound spec and has no manual-selection equivalent, so that \"\n + 'list was dropped. The operations themselves are still available through the bound API reference.',\n )\n return null\n }\n return registerReference(value, context)\n }\n const object = objectValue(value)\n if (!object) return null\n if (typeof object.page === 'string') return registerReference(object.page, context)\n const href = projectedHref(object.href)\n if (href && !object.pages && !object.groups) {\n const page = registerReference(href, context)\n if (page) return page\n warnOnce(\n context,\n 'external-page-link',\n 'External links nested inside a Mintlify sidebar cannot be represented as Thally pages and were omitted.',\n )\n return null\n }\n const pages = Array.isArray(object.pages) ? object.pages : []\n if ('group' in object || pages.length > 0) {\n const children: Array<string | MigrationNavigationGroup> = []\n if (typeof object.root === 'string') {\n const root = registerReference(object.root, context)\n if (root) children.push(root)\n }\n for (const page of pages) {\n const converted = convertPage(page, context)\n if (converted) children.push(converted)\n }\n if (children.length === 0) return null\n return {\n group: labelFor(object, 'Documentation'),\n ...(iconName(object.icon) ? { icon: iconName(object.icon) } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n pages: children,\n }\n }\n return null\n}\n\nfunction convertNavigationValues(\n values: Array<unknown>,\n context: ProjectionContext,\n): Array<string | MigrationNavigationGroup> {\n return values.flatMap<string | MigrationNavigationGroup>((value) => {\n const page = convertPage(value, context)\n return page ? [page] : []\n })\n}\n\ninterface NavigationProjectionTrace {\n rootContainerKind?: 'tabs' | 'anchors' | 'products' | 'dropdowns' | 'versions' | 'menus'\n}\n\nfunction convertContainerToTabs(\n containerValue: unknown,\n context: ProjectionContext,\n fallbackTab: string,\n trace?: NavigationProjectionTrace,\n depth = 0,\n): Array<MigrationNavigationTab> {\n const rawContainer = objectValue(containerValue)\n if (!rawContainer) return []\n const container = withFlattenedProductGroups(rawContainer)\n const containerKeys = ['tabs', 'anchors', 'products', 'dropdowns', 'versions', 'menus'] as const\n for (const key of containerKeys) {\n if (!Array.isArray(container[key])) continue\n const entries = [...container[key] as Array<unknown>]\n if (key === 'versions') {\n entries.sort((left, right) => Number(objectValue(right)?.default === true) - Number(objectValue(left)?.default === true))\n }\n const tabs = entries.flatMap((value, index) => {\n const object = objectValue(value)\n if (!object) return []\n const tab = labelFor(object, `${fallbackTab} ${index + 1}`)\n const href = projectedHref(object.href)\n const hasNestedContainers = containerKeys.some((containerKey) => Array.isArray(object[containerKey]))\n if (href && !object.pages && !object.groups && !hasNestedContainers) {\n return [{\n tab,\n href,\n ...containerPresentation(object),\n ...(object.hidden === true ? { hidden: true } : {}),\n }]\n }\n const nested = convertContainerToTabs(object, context, tab, trace, depth + 1)\n if (nested.length > 0) {\n if (nested.length === 1) {\n return [{\n ...nested[0],\n tab,\n ...containerPresentation(object),\n ...(href ? { href } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n }]\n }\n const presentation = containerPresentation(object)\n return nested.map((item, childIndex) => ({\n ...presentation,\n ...item,\n tab: `${tab}: ${item.tab}`,\n ...(childIndex === 0 && href && !item.href ? { href } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n }))\n }\n return []\n })\n if (tabs.length > 0) {\n if (depth === 0 && trace) trace.rootContainerKind = key\n return tabs\n }\n }\n const rawGroups = Array.isArray(container.groups) ? container.groups : []\n const rawPages = Array.isArray(container.pages) ? container.pages : []\n const hasRootNodes = typeof container.root === 'string' || rawPages.length > 0\n const values = [\n ...(typeof container.root === 'string' ? [container.root] : []),\n ...rawGroups,\n ...rawPages,\n ]\n const children = convertNavigationValues(values, context)\n return children.length > 0\n ? [{\n tab: fallbackTab,\n ...(hasRootNodes\n ? { pages: children }\n : { groups: children as Array<MigrationNavigationGroup> }),\n ...containerPresentation(container),\n ...(projectedHref(container.href) ? { href: projectedHref(container.href) } : {}),\n ...(container.hidden === true ? { hidden: true } : {}),\n }]\n : []\n}\n\nfunction projectedTheme(value: unknown): MigrationDocsConfig['theme'] {\n if (value === 'maple') return 'maple'\n if (['aspen', 'luma', 'sequoia'].includes(String(value))) return 'sharp'\n if (['almond', 'palm'].includes(String(value))) return 'minimal'\n return typeof value === 'string' ? 'default' : undefined\n}\n\nfunction projectedNavbar(value: unknown): MigrationDocsConfig['navbar'] {\n const navbar = objectValue(value)\n if (!navbar) return undefined\n const links = Array.isArray(navbar.links)\n ? navbar.links.flatMap((entry) => {\n const link = objectValue(entry)\n const href = projectedHref(link?.href)\n if (!link || !href) return []\n const label = typeof link.label === 'string' ? link.label : typeof link.name === 'string' ? link.name : ''\n if (!label) return []\n return [{ label, href, ...(link.type === 'github' ? { type: 'github' as const } : {}) }]\n })\n : []\n const primaryValue = objectValue(navbar.primary)\n const primaryHref = projectedHref(primaryValue?.href)\n const primary = primaryValue && primaryHref\n ? {\n label: typeof primaryValue.label === 'string'\n ? primaryValue.label\n : primaryValue.type === 'github' ? 'GitHub' : 'Get started',\n href: primaryHref,\n }\n : undefined\n return links.length > 0 || primary ? { ...(links.length > 0 ? { links } : {}), ...(primary ? { primary } : {}) } : undefined\n}\n\nfunction projectedGlobalNavigationLinks(\n value: unknown,\n): NonNullable<NonNullable<MigrationDocsConfig['navbar']>['links']> {\n const global = objectValue(value)\n if (!global) return []\n const links: Array<{ label: string; href: string }> = []\n const visit = (entry: unknown): void => {\n if (Array.isArray(entry)) {\n entry.forEach(visit)\n return\n }\n const item = objectValue(entry)\n if (!item) return\n const href = projectedHref(item.href)\n if (href) {\n const label = labelFor(item, '')\n if (label) links.push({ label, href })\n }\n for (const key of ['tabs', 'anchors', 'dropdowns', 'products', 'versions', 'languages', 'menus']) {\n if (Array.isArray(item[key])) visit(item[key])\n }\n }\n visit(global)\n return links\n}\n\nfunction projectedFooter(value: unknown): MigrationDocsConfig['footer'] {\n const footer = objectValue(value)\n if (!footer) return undefined\n const socials = objectValue(footer.socials)\n const socialLinks = socials\n ? Object.fromEntries(Object.entries(socials).flatMap(([key, value]) => {\n const href = projectedHref(value)\n return href ? [[key, href]] : []\n }))\n : undefined\n const links = Array.isArray(footer.links)\n ? footer.links.flatMap((entry) => {\n const column = objectValue(entry)\n if (!column || !Array.isArray(column.items)) return []\n const heading = typeof column.heading === 'string'\n ? column.heading\n : typeof column.header === 'string' ? column.header : ''\n const items = column.items.flatMap((item) => {\n const link = objectValue(item)\n const href = projectedHref(link?.href)\n return link && typeof link.label === 'string' && href\n ? [{ label: link.label, href }]\n : []\n })\n return heading && items.length > 0 ? [{ heading, items }] : []\n })\n : []\n return (socialLinks && Object.keys(socialLinks).length > 0) || links.length > 0\n ? { ...(socialLinks && Object.keys(socialLinks).length > 0 ? { socials: socialLinks } : {}), ...(links.length > 0 ? { links } : {}) }\n : undefined\n}\n\nfunction projectedFont(value: unknown): { family: string; weight?: Array<string> } | undefined {\n if (typeof value === 'string' && value) return { family: value }\n const font = objectValue(value)\n if (!font) return undefined\n const family = typeof font.family === 'string'\n ? font.family\n : typeof font.name === 'string' ? font.name : undefined\n if (!family) return undefined\n const weight = Array.isArray(font.weight)\n ? font.weight.map(String)\n : Array.isArray(font.weights) ? font.weights.map(String) : undefined\n return { family, ...(weight && weight.length > 0 ? { weight } : {}) }\n}\n\nfunction projectedCompatibleConfig(config: Record<string, unknown>): Omit<MigrationDocsConfig, 'tabs' | 'i18n' | 'redirects'> {\n const banner = objectValue(config.banner)\n const bannerContent = banner && (typeof banner.content === 'string' || objectValue(banner.content))\n ? banner.content as string | Record<string, string>\n : undefined\n const bannerType = banner && ['info', 'warning', 'critical'].includes(String(banner.type ?? banner.variant))\n ? String(banner.type ?? banner.variant) as 'info' | 'warning' | 'critical'\n : undefined\n const bannerColor = objectValue(banner?.color)\n const bodyFont = projectedFont(objectValue(config.fonts)?.body ?? config.fonts)\n const headingFont = projectedFont(objectValue(config.fonts)?.heading)\n const feedback = objectValue(config.feedback)\n const seo = objectValue(config.seo)\n const iconLibrary = objectValue(config.icons)?.library\n const projectedIconLibrary = ['lucide', 'fontawesome', 'tabler'].includes(String(iconLibrary))\n ? String(iconLibrary) as 'lucide' | 'fontawesome' | 'tabler'\n : undefined\n const navbar = projectedNavbar(config.navbar)\n const globalLinks = projectedGlobalNavigationLinks(objectValue(config.navigation)?.global)\n const navbarLinks = [...new Map(\n [...(navbar?.links ?? []), ...globalLinks].map((link) => [`${link.label}:${link.href}`, link]),\n ).values()]\n const projectedNavigation = navbarLinks.length > 0 || navbar?.primary\n ? { ...(navbarLinks.length > 0 ? { links: navbarLinks } : {}), ...(navbar?.primary ? { primary: navbar.primary } : {}) }\n : undefined\n return {\n ...(projectedTheme(config.theme) ? { theme: projectedTheme(config.theme) } : {}),\n ...(projectedIconLibrary ? { icons: { library: projectedIconLibrary } } : {}),\n ...(bannerContent ? {\n banner: {\n content: bannerContent,\n ...(banner?.dismissible === false ? { dismissible: false } : {}),\n ...(typeof banner?.id === 'string' ? { id: banner.id } : {}),\n ...(typeof banner?.revision === 'string' ? { revision: banner.revision } : {}),\n ...(bannerType ? { type: bannerType } : {}),\n ...(bannerColor ? { color: {\n ...(typeof bannerColor.light === 'string' ? { light: bannerColor.light } : {}),\n ...(typeof bannerColor.dark === 'string' ? { dark: bannerColor.dark } : {}),\n } } : {}),\n },\n } : {}),\n ...(projectedNavigation ? { navbar: projectedNavigation } : {}),\n ...(projectedFooter(config.footer) ? { footer: projectedFooter(config.footer) } : {}),\n ...(bodyFont || headingFont ? { fonts: { ...(bodyFont ? { body: bodyFont } : {}), ...(headingFont ? { heading: headingFont } : {}) } } : {}),\n ...(seo?.indexing === 'all' ? { seo: { indexing: 'all' } } : {}),\n ...(typeof feedback?.thumbsRating === 'boolean' ? { feedback: { thumbsRating: feedback.thumbsRating } } : {}),\n }\n}\n\nconst NEXT_REDIRECT_PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Next.js redirects compile through path-to-regexp and reject a bare `*`\n * segment (Mintlify and Fern's trailing wildcard syntax) with \"Invalid\n * redirects found\", crashing the whole build. Both platforms only document\n * `*` as a trailing catch-all segment, so it is translated to Next's named\n * catch-all (`/:path*`) here; a `*` anywhere else, or a syntax Next can't\n * express, is dropped rather than guessed at. Source text already written as\n * path-to-regexp (e.g. `:path*`) passes through unchanged: only a literal\n * `*` segment is rewritten, and the final `isValidNextRedirectPath` check\n * still accepts it.\n */\nfunction translateRedirectWildcards(\n source: string,\n destination: string,\n): { source: string; destination: string } | null {\n const sourceSegments = source.split('/')\n const destinationSegments = destination.split('/')\n const sourceWildcardIndex = sourceSegments.indexOf('*')\n if (sourceWildcardIndex !== -1 && sourceWildcardIndex !== sourceSegments.length - 1) return null\n if (sourceSegments.slice(0, -1).includes('*') || destinationSegments.slice(0, -1).includes('*')) return null\n\n const translatedSource = [...sourceSegments]\n if (sourceWildcardIndex !== -1) translatedSource[sourceWildcardIndex] = ':path*'\n\n const destinationHasWildcard = destinationSegments.at(-1) === '*'\n if (destinationHasWildcard && sourceWildcardIndex === -1) return null\n const translatedDestination = [...destinationSegments]\n if (destinationHasWildcard) translatedDestination[translatedDestination.length - 1] = ':path*'\n\n const finalSource = translatedSource.join('/')\n const finalDestination = translatedDestination.join('/')\n if (!isValidNextRedirectPath(finalSource) || !isValidNextRedirectPath(finalDestination)) return null\n return { source: finalSource, destination: finalDestination }\n}\n\n/** Conservative structural check for the path-to-regexp syntax Next.js redirects accept. */\nfunction isValidNextRedirectPath(path: string): boolean {\n return path.split('/').every((segment) => {\n if (segment === '' || segment === '*') return segment === ''\n if (!segment.startsWith(':')) return !segment.includes('*') && !segment.includes(':')\n const name = segment.endsWith('*') ? segment.slice(1, -1) : segment.slice(1)\n return NEXT_REDIRECT_PARAM_NAME.test(name)\n })\n}\n\n/**\n * Shared redirect-safety check for Mintlify and Fern: both require a\n * site-relative, `/`-rooted source and destination (Mintlify's own redirect\n * docs give only rooted examples; neither documents an absolute-URL\n * destination), so a protocol-relative or absolute value (`//evil.example`\n * reads as same-scheme cross-origin to a browser and to Next.js) is rejected.\n */\n// Matches every ASCII control character (incl. DEL, \\x7f) and every Unicode\n// whitespace character (`\\s` already covers the line/paragraph separators\n// U+2028/U+2029, along with tab, CR, LF, NBSP, etc).\nconst UNSAFE_REDIRECT_CHARS = /[\\s\\x00-\\x1f\\x7f]/\n\nexport function isRedirectPathSafe(rawSource: string, rawDestination: string): boolean {\n for (const value of [rawSource, rawDestination]) {\n if (!value.startsWith('/')) return false\n if (value.startsWith('//') || value.startsWith('/\\\\')) return false\n if (value.includes('\\\\')) return false\n // A browser strips whitespace/control characters (tab, CR, LF, ...) from\n // a URL before navigating, so a literal tab in `/\\t/evil.example` passes\n // every check above yet reaches the browser as `//evil.example`. Reject\n // any such character anywhere in the raw value.\n if (UNSAFE_REDIRECT_CHARS.test(value)) return false\n // Browsers unescape a leading `%2f%2f`/`%5c` before treating it as `//`/`\\`.\n const lower = value.toLowerCase()\n if (lower.startsWith('/%2f%2f') || lower.startsWith('/%5c')) return false\n }\n return true\n}\n\n/**\n * Translate a redirect's trailing wildcard for Next.js, once its source and\n * destination have already passed {@link isRedirectPathSafe}.\n */\nexport { translateRedirectWildcards }\n\n/**\n * Mintlify's `versions` container authors every version's own page paths\n * with the version identifier as a literal leading segment (`v1.15.22/en/\n * introduction`), including the default version's — the live site still\n * serves that path, but also serves the same page with the segment\n * dropped (`/en/introduction` 307s to the versioned URL). Thally has no\n * multi-version content model of its own (each version becomes its own\n * tab, per existing behavior), so an in-repo link authored the second way\n * has nothing to resolve to. Collecting each `versions` container's\n * default identifier lets the repository scanner add a matching redirect\n * alongside the one it already adds for a page's literal source path.\n */\nexport function mintlifyDefaultVersionPrefixes(config: Record<string, unknown>): Set<string> {\n const navigation = objectValue(config.navigation) ?? config\n const prefixes = new Set<string>()\n function collect(container: Record<string, unknown>): void {\n if (Array.isArray(container.versions)) {\n const entries = container.versions\n .map((value) => objectValue(value))\n .filter((value): value is Record<string, unknown> => value !== null)\n const defaultEntry = entries.find((entry) => entry.default === true) ?? entries[0]\n if (defaultEntry && typeof defaultEntry.version === 'string' && defaultEntry.version.trim()) {\n prefixes.add(defaultEntry.version.trim())\n }\n }\n if (Array.isArray(container.languages)) {\n for (const value of container.languages) {\n const language = objectValue(value)\n if (language) collect(language)\n }\n }\n }\n collect(navigation)\n return prefixes\n}\n\n/**\n * Every version identifier declared across all `versions` containers (not\n * just the default one) — used to label which versions' pages were dropped\n * when a repository exceeds the source-file discovery budget.\n */\nexport function mintlifyAllVersionPrefixes(config: Record<string, unknown>): Set<string> {\n const navigation = objectValue(config.navigation) ?? config\n const prefixes = new Set<string>()\n function collect(container: Record<string, unknown>): void {\n if (Array.isArray(container.versions)) {\n for (const value of container.versions) {\n const entry = objectValue(value)\n if (entry && typeof entry.version === 'string' && entry.version.trim()) prefixes.add(entry.version.trim())\n }\n }\n if (Array.isArray(container.languages)) {\n for (const value of container.languages) {\n const language = objectValue(value)\n if (language) collect(language)\n }\n }\n }\n collect(navigation)\n return prefixes\n}\n\n/** Convert current and legacy Mintlify navigation into Thally's schema. */\nexport function projectMintlifyNavigation(\n config: Record<string, unknown>,\n options: MintlifyProjectionOptions = {},\n): MintlifyNavigationResult {\n const warnings: Array<MigrationWarning> = []\n const references: Array<MintlifyPageReference> = []\n const seenReferences = new Set<string>()\n const warningKeys = new Set<string>()\n const navigation = objectValue(config.navigation) ?? config\n const languages = Array.isArray(navigation.languages)\n ? navigation.languages.flatMap((value): Array<Record<string, unknown>> => {\n const language = objectValue(value)\n if (!language) return []\n try {\n const code = Intl.getCanonicalLocales(String(language.language ?? language.locale ?? 'en'))[0]\n return [{ ...language, language: code }]\n } catch {\n warnings.push({ code: 'unsupported-config', message: 'A navigation language with an invalid locale code was skipped.' })\n return []\n }\n })\n : []\n let tabs: Array<MigrationNavigationTab> = []\n let i18n: MigrationDocsConfig['i18n']\n const localizedNavigation: Record<string, Array<MigrationNavigationTab>> = {}\n const projectionTrace: NavigationProjectionTrace = {}\n\n if (languages.length > 0) {\n const defaultLanguage = languages.find((entry) => entry.default === true) ?? languages[0]\n const defaultLocale = String(defaultLanguage.language)\n const locales = languages.map((entry) => {\n const code = String(entry.language)\n let label: string | undefined = LANGUAGE_LABELS[code]\n try {\n label ??= new Intl.DisplayNames(['en'], { type: 'language' }).of(code) ?? undefined\n } catch {\n // Unknown extension tags remain readable as their normalized code.\n }\n return { code, label: label ?? code.toUpperCase() }\n })\n i18n = { defaultLocale, locales }\n const defaultPageIds = new Set<string>()\n // The default language supplies canonical page identities even when it\n // appears after translations in the authored language picker.\n for (const language of [defaultLanguage, ...languages.filter((entry) => entry !== defaultLanguage)]) {\n const locale = String(language.language)\n const context: ProjectionContext = {\n locale,\n defaultPageIds,\n pathPrefix: options.pathPrefix,\n references,\n seenReferences,\n warnings,\n warningKeys,\n }\n const languageTabs = convertContainerToTabs(\n language,\n context,\n 'Documentation',\n language === defaultLanguage ? projectionTrace : undefined,\n )\n if (language === defaultLanguage) {\n tabs = languageTabs\n for (const reference of references) defaultPageIds.add(reference.navigationId)\n } else if (languageTabs.length > 0) {\n localizedNavigation[locale] = languageTabs\n }\n }\n if (Object.keys(localizedNavigation).length > 0) i18n.navigation = localizedNavigation\n } else {\n const context = { references, seenReferences, warnings, warningKeys, pathPrefix: options.pathPrefix }\n tabs = convertContainerToTabs(navigation, context, 'Documentation', projectionTrace)\n if (tabs.length === 0 && Array.isArray(config.navigation)) {\n const children = convertNavigationValues(config.navigation, context)\n if (children.length > 0) {\n const hasRootPages = children.some((page) => typeof page === 'string')\n tabs = [{\n tab: 'Documentation',\n ...(hasRootPages\n ? { pages: children }\n : { groups: children as Array<MigrationNavigationGroup> }),\n }]\n }\n }\n }\n\n if (tabs.length === 0) {\n warnings.push({\n code: 'unsupported-config',\n message: 'Mintlify navigation could not be projected; generated navigation will be used.',\n })\n }\n const redirects = Array.isArray(config.redirects)\n ? config.redirects.flatMap((value) => {\n const redirect = objectValue(value)\n if (!redirect || typeof redirect.source !== 'string' || typeof redirect.destination !== 'string') return []\n const rawSource = redirect.source.trim()\n const rawDestination = redirect.destination.trim()\n if (!isRedirectPathSafe(rawSource, rawDestination)) return []\n const translated = translateRedirectWildcards(rawSource, rawDestination)\n if (!translated) {\n warnings.push({\n code: 'unsupported-config',\n message: `Redirect from ${rawSource} uses a wildcard Next.js cannot express and was dropped.`,\n })\n return []\n }\n return [{\n source: translated.source,\n destination: translated.destination,\n ...(typeof redirect.permanent === 'boolean' ? { permanent: redirect.permanent } : {}),\n }]\n })\n : []\n return {\n docsConfig: {\n tabs,\n ...(projectionTrace.rootContainerKind === 'dropdowns'\n ? { navigation: { display: 'dropdown' as const } }\n : {}),\n ...projectedCompatibleConfig(config),\n ...(i18n ? { i18n } : {}),\n ...(redirects.length > 0 ? { redirects } : {}),\n },\n pageReferences: references,\n warnings,\n }\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_]/)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\ninterface GeneratedNavigationOptions {\n /** Dedicated docs platforms expose their primary sections as top-level tabs. */\n topLevelTabs?: boolean\n /** Ordered tabs recovered from the source site's rendered navigation. */\n topLevelNavigation?: ReadonlyArray<{\n section: string\n label: string\n pageId: string\n }>\n}\n\nconst TOP_LEVEL_LABELS: Record<string, string> = {\n 'api-reference': 'API Reference',\n cli: 'CLI',\n faqs: 'FAQs',\n introduction: 'Overview',\n 'mcp-server': 'MCP Server',\n sdk: 'SDK',\n}\n\nfunction topLevelLabel(segment: string): string {\n return TOP_LEVEL_LABELS[segment] ?? titleCase(segment)\n}\n\nfunction groupsWithinSection(\n section: string,\n pageIds: Array<string>,\n sectionLabel = topLevelLabel(section),\n): Array<MigrationNavigationGroup> {\n const groups = new Map<string, Array<string>>()\n for (const id of pageIds) {\n const relative = id === 'introduction'\n ? ''\n : id.startsWith(`${section}/`)\n ? id.slice(section.length + 1)\n : id\n const nestedSegment = relative.includes('/') ? relative.split('/', 1)[0] : 'overview'\n const group = groups.get(nestedSegment) ?? []\n group.push(id)\n groups.set(nestedSegment, group)\n }\n return [...groups].map(([segment, pages]) => ({\n group: segment === 'overview' ? sectionLabel : titleCase(segment),\n pages,\n }))\n}\n\nfunction preferredLandingPage(\n section: string,\n pageIds: Array<string>,\n): string | undefined {\n const candidates = [\n section === 'introduction' ? 'introduction' : undefined,\n `${section}/overview`,\n `${section}/introduction`,\n section,\n ]\n return candidates.find((candidate): candidate is string => Boolean(candidate && pageIds.includes(candidate)))\n}\n\n/** Build deterministic fallback navigation from imported default-locale pages. */\nexport function buildNavigationFromPages(\n pages: Array<MigrationPage>,\n options: GeneratedNavigationOptions = {},\n): MigrationDocsConfig {\n const ids = pages.filter((page) => !page.locale || page.locale === 'en').map((page) => page.navigationId)\n const ordered = [...new Set(ids)]\n if (options.topLevelTabs) {\n const sourceNavigation = (options.topLevelNavigation ?? []).flatMap((entry) => {\n const sectionPages = ordered.filter((id) => id === entry.section || id.startsWith(`${entry.section}/`))\n const pageId = ordered.includes(entry.pageId)\n ? entry.pageId\n : preferredLandingPage(entry.section, sectionPages) ?? sectionPages[0]\n return pageId ? [{ ...entry, pageId }] : []\n })\n if (sourceNavigation.length > 1) {\n const claimedIds = new Set<string>()\n const tabs = sourceNavigation.map((entry) => {\n const pageIds = ordered.filter((id) => {\n const matches = id === entry.pageId\n || id === entry.section\n || id.startsWith(`${entry.section}/`)\n if (matches) claimedIds.add(id)\n return matches\n })\n return { entry, pageIds }\n })\n // Mintlify's first tab is the documentation home and owns pages that do\n // not belong to another product tab (for example /create and /deploy).\n tabs[0].pageIds.push(...ordered.filter((id) => !claimedIds.has(id)))\n return {\n tabs: tabs.map(({ entry, pageIds }) => ({\n tab: entry.label,\n href: entry.pageId === 'introduction' ? '/' : `/${entry.pageId}`,\n groups: groupsWithinSection(entry.section, [...new Set(pageIds)], entry.label),\n })),\n }\n }\n const sectionNames = [...new Set(ordered\n .filter((id) => id.includes('/'))\n .map((id) => id.split('/', 1)[0]))]\n if (sectionNames.length > 1) {\n const defaultSection = sectionNames.includes('introduction')\n ? 'introduction'\n : sectionNames[0]\n const sections = new Map<string, Array<string>>()\n for (const id of ordered) {\n const section = id.includes('/') ? id.split('/', 1)[0] : defaultSection\n const bucket = sections.get(section) ?? []\n bucket.push(id)\n sections.set(section, bucket)\n }\n return {\n tabs: [...sections].map(([section, pageIds]) => {\n const label = topLevelLabel(section)\n const landingPage = preferredLandingPage(section, pageIds)\n return {\n tab: label,\n ...(landingPage\n ? { href: landingPage === 'introduction' ? '/' : `/${landingPage}` }\n : {}),\n groups: groupsWithinSection(section, pageIds),\n }\n }),\n }\n }\n }\n const buckets = new Map<string, Array<string>>()\n for (const id of ordered) {\n const segment = id.includes('/') ? id.split('/', 1)[0] : 'overview'\n const bucket = buckets.get(segment) ?? []\n bucket.push(id)\n buckets.set(segment, bucket)\n }\n const groups = [...buckets].map(([segment, pageIds]) => ({\n group: segment === 'overview' ? 'Overview' : titleCase(segment),\n pages: pageIds,\n }))\n return { tabs: [{ tab: 'Documentation', groups }] }\n}\n\n/** Exposed for repository discovery and focused unit tests. */\nexport function isDocumentationExtension(filename: string): boolean {\n return ['.md', '.mdx', '.rst', '.txt'].includes(extname(filename).toLowerCase())\n}\n\n/**\n * A source page can be excluded after navigation is projected (invalid MDX,\n * a client-boundary function prop, a duplicate id). Its reference still sits\n * in the projected tabs/groups at that point, across every tab, group, and\n * locale, since the nav tree and the page list are built from the same\n * source config independently. Drop those dangling references here so\n * `thally check` never reports a nav entry with no backing MDX file, and\n * drop any group left with no pages as a result. Shared by every platform's\n * navigation projection (Mintlify, Fern, Docusaurus).\n */\nexport function pruneMissingNavigationPages(\n config: MigrationDocsConfig,\n availableIds: ReadonlySet<string>,\n): MigrationDocsConfig {\n const pruneNodes = (nodes: Array<string | MigrationNavigationGroup>): Array<string | MigrationNavigationGroup> => {\n const seenSiblings = new Set<string>()\n return nodes.flatMap((node): Array<string | MigrationNavigationGroup> => {\n if (typeof node === 'string') {\n // Distinct source files can resolve to one final frontmatter slug.\n // Showing that route twice in one sidebar group is misleading even\n // though both references passed the existence check.\n if (!availableIds.has(node) || seenSiblings.has(node)) return []\n seenSiblings.add(node)\n return [node]\n }\n const pages = pruneNodes(node.pages)\n return pages.length > 0 ? [{ ...node, pages }] : []\n })\n }\n const tabs = config.tabs.flatMap((tab) => {\n const hadPages = (tab.pages?.length ?? 0) > 0 || (tab.groups?.length ?? 0) > 0\n const pages = tab.pages ? pruneNodes(tab.pages) : undefined\n const groups = tab.groups ? (pruneNodes(tab.groups) as Array<MigrationNavigationGroup>) : undefined\n const hasPages = (pages?.length ?? 0) > 0 || (groups?.length ?? 0) > 0\n // A tab that never referenced pages/groups (href-only, api-only) is untouched.\n if (hadPages && !hasPages) return []\n return [{\n ...tab,\n ...(tab.pages ? { pages } : {}),\n ...(tab.groups ? { groups } : {}),\n }]\n })\n return { ...config, tabs }\n}\n","/**\n * Static Fern (`fern/docs.yml`) repository projection. Fern navigation and\n * generator config are plain YAML data files, so this adapter only ever\n * parses them with `yaml` and never imports or executes JavaScript.\n */\n\nimport { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'\nimport { basename, dirname, extname, relative } from 'node:path'\n\nimport { load } from 'cheerio'\nimport { parse as parseYaml } from 'yaml'\n\nimport { isRedirectPathSafe, translateRedirectWildcards } from './navigation.js'\nimport { resolveWithin, resolveWithinRoot } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationNavigationTab,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_CONFIG_BYTES = 20_000_000\n\n/** Retain safe Fern announcement links without emitting source-controlled HTML. */\nfunction announcementMarkdown(message: string): string {\n const document = load(message)\n document('script, style, iframe, object, embed, svg, math').remove()\n const escapeText = (value: string): string => value\n .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n .replace(/([\\\\`*_\\[\\]{}()!])/g, '\\\\$1')\n const links = new Map<string, string>()\n document('a').each((index, element) => {\n const marker = `THALLYANNOUNCEMENTLINK${index}TOKEN`\n const label = document(element).text().trim()\n const rawHref = document(element).attr('href')?.trim() ?? ''\n let href: string | undefined\n if (/^https?:\\/\\//i.test(rawHref)) {\n try { href = new URL(rawHref).toString() } catch { /* invalid source link becomes text */ }\n } else if (rawHref.startsWith('/') && !rawHref.startsWith('//') && !/[\\\\<>\\s]/.test(rawHref)) {\n href = rawHref\n }\n const destination = href?.replace(/\\(/g, '%28').replace(/\\)/g, '%29')\n links.set(marker, destination && label ? `[${escapeText(label)}](${destination})` : escapeText(label))\n document(element).replaceWith(marker)\n })\n let text = escapeText(document('body').text())\n for (const [marker, link] of links) text = text.replaceAll(marker, link)\n return text.trim()\n}\n\nexport interface FernPageDescriptor {\n /** Path to the referenced page file, relative to the Fern root. */\n sourcePath: string\n navigationId: string\n /** Fern's sidebar label can intentionally differ from the page title. */\n navTitle?: string\n /** Keep routable pages excluded by Fern's `hidden` navigation flag. */\n hidden?: boolean\n}\n\n/** One `api:` navigation node, resolved to the name/tab Thally needs to bind its spec. */\nexport interface FernApiSection {\n /** The node's own value (a display name or, in multi-API repos, a `fern/apis/<name>` identifier). */\n name: string\n /** True when `name` came from an explicit `api-name` field rather than falling back to the `api:` display title. */\n nameExplicit: boolean\n /** Label of the tab that owns this node, if that tab also has other content and survived projection. */\n tabLabel?: string\n /**\n * Route segments (section slugs) leading to this node, used only to\n * disambiguate two `api:` nodes that land on the same `tabLabel` — a\n * \"Production API Reference\" and \"Testnet API Reference\" section both\n * nested under one tab both want that tab's label; without this, the\n * second one silently overwrites the first tab's binding instead of\n * getting its own tab.\n */\n routeSegments: Array<string>\n}\n\nexport interface FernNavigationResult {\n docsConfig: MigrationDocsConfig\n descriptors: Array<FernPageDescriptor>\n warnings: Array<MigrationWarning>\n /** Every `api:` node found in navigation, in document order. A repo can declare several (e.g. a REST and a WebSocket API in separate tabs). */\n apiSections: Array<FernApiSection>\n /** Fern changelog tabs render their entries as a feed at the bare route. */\n changelogIndexes: Array<{ route: string; entries: Array<string> }>\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\nfunction readBoundedYaml(path: string): unknown {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('The Fern config is larger than 20 MB and could not be imported.')\n }\n return parseYaml(readFileSync(path, 'utf8'))\n}\n\n/** Read `fern/docs.yml` without executing anything. */\nexport function readFernConfig(fernRoot: string): { config: Record<string, unknown>; sourcePath: string } | null {\n const sourcePath = 'docs.yml'\n const path = resolveWithin(fernRoot, sourcePath)\n if (!existsSync(path) || !lstatSync(path).isFile()) return null\n const config = objectValue(readBoundedYaml(path))\n if (!config) throw new Error('fern/docs.yml must contain an object.')\n return { config, sourcePath }\n}\n\ninterface WalkContext {\n fernRoot: string\n repositoryRoot: string\n descriptors: Array<FernPageDescriptor>\n seenNavigationIds: Set<string>\n /** Every `api:` node seen so far, in document order; `tabLabel` is filled in once its owning tab finishes walking. */\n apiSections: Array<FernApiSection>\n changelogIndexes: Array<{ route: string; entries: Array<string> }>\n warnings: Array<MigrationWarning>\n warningKeys: Set<string>\n /** External navigation leaves cannot live inside Thally groups; keep them as navbar links. */\n externalLinks: Array<{ label: string; href: string }>\n /** Bare tab/section routes with no page of their own, soft-redirected to their first descendant. */\n bareRouteRedirects: Array<{ source: string; destination: string }>\n /** Slugified segment -> the literal explicit `slug` it was derived from, when the two differ (e.g. `baml-client` -> `baml_client`). */\n segmentAliases: Map<string, string>\n /**\n * Directory, relative to `fernRoot` (posix, no trailing slash, '' at the\n * root), that a page's `path` is actually relative to. A product's own\n * config lives under `fern/products/<name>/`, so its pages resolve there\n * rather than at the Fern root, even though the product's *route* segment\n * is unrelated and handled separately via `parentSegments`.\n */\n pathPrefix: string\n hiddenInherited?: boolean\n /**\n * The navigation id that actually owns a page's content, keyed by\n * `sourcePath` — the first nav location a file is registered at. A file\n * registered again at a second nav location (e.g. a Fern page listed\n * under both a guide section and a `slug: baml_client` reference section)\n * gets its own position-derived id recorded in `descriptors` (so a\n * redirect from it can still be built), but the navigation tree itself\n * points that second location at this id, since `repository.ts` creates\n * exactly one page per physical file and the second id never becomes one.\n */\n sourcePathToNavigationId: Map<string, string>\n}\n\nfunction warnOnce(context: WalkContext, key: string, message: string): void {\n if (context.warningKeys.has(key)) return\n context.warningKeys.add(key)\n context.warnings.push({ code: 'unsupported-config', message })\n}\n\nfunction firstLeafId(nodes: Array<string | MigrationNavigationGroup>): string | undefined {\n for (const node of nodes) {\n if (typeof node === 'string') return node\n const nested = firstLeafId(node.pages)\n if (nested) return nested\n }\n return undefined\n}\n\n/** A tab or section with no page of its own still has a public URL that Fern resolves to its first descendant. */\nfunction addBareRouteRedirect(\n segments: Array<string>,\n pages: Array<string | MigrationNavigationGroup>,\n context: WalkContext,\n): void {\n if (segments.length === 0) return\n const destination = firstLeafId(pages)\n const source = segments.join('/')\n if (destination && destination !== source) {\n context.bareRouteRedirects.push({ source: `/${source}`, destination: `/${destination}` })\n }\n}\n\n/** A literal explicit `slug` value is only trusted as a redirect segment when it's already plain URL-safe text. */\nconst FERN_SEGMENT_ALIAS = /^[\\w.-]+$/\n\n/**\n * Fern's own slugifier treats any non-alphanumeric run (including `.`, which\n * Thally's shared `slugifySegment` deliberately preserves for other\n * platforms) as a separator, so Fern gets its own minimal one here.\n */\nfunction fernBasicSlug(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')\n}\n\n/**\n * Fern derives a default slug from a display name by lowercasing, replacing\n * non-alphanumeric runs with hyphens, dropping parentheses, and splitting\n * camelCase/acronym boundaries (`OpenAI` -> `open-ai`, `SDKs` -> `sd-ks`) —\n * confirmed against buildwithfern.com's own \"Configuring slugs\" doc and a\n * live site's sitemap. Only the label fallback needs this; an authored\n * `slug` is used as literal, already-intended path text.\n */\nfunction fernLabelSlug(label: string): string {\n const decamelized = label\n .replace(/[()]/g, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n return fernBasicSlug(decamelized)\n}\n\n/**\n * A Fern tab, section, or page contributes its slugified label as a URL\n * segment by default (confirmed against a live Fern site's sitemap: nested\n * sections with no `slug` field still nest their descendants by title).\n * `slug` overrides the label; `skip-slug: true` omits the segment entirely.\n *\n * An author-written `slug` is intentional URL text (e.g. BAML's `slug:\n * baml_client`, matching its own `baml_client/` folder name) — Fern serves\n * it literally, underscore and all. `fernBasicSlug` still squashes it into\n * Thally's usual hyphenated route (kept as the canonical route: changing it\n * would be a wider behavior change than this warrants), but when the two\n * differ, the literal form is recorded as a segment alias so\n * `fernUnderscoreAliasRedirects` can add a redirect from the original\n * folder-name-shaped link to the route Thally actually uses.\n */\nfunction segmentFor(value: Record<string, unknown>, label: string, context?: WalkContext): string | null {\n if (value['skip-slug'] === true) return null\n // Fern uses an authored empty slug to put a tab at the site root.\n if (typeof value.slug !== 'string') return fernLabelSlug(label) || null\n const explicit = value.slug.trim()\n if (!explicit) return null\n const slugified = fernBasicSlug(explicit)\n if (context && explicit !== slugified && FERN_SEGMENT_ALIAS.test(explicit)) {\n context.segmentAliases.set(slugified, explicit)\n }\n return slugified || null\n}\n\nfunction uniqueNavigationId(base: string, context: WalkContext): string {\n if (!context.seenNavigationIds.has(base)) return base\n let index = 2\n while (context.seenNavigationIds.has(`${base}-${index}`)) index++\n return `${base}-${index}`\n}\n\nfunction registerPageAt(rawPath: string, base: string, context: WalkContext, navTitle?: string, hidden = false): string {\n let sourcePath: string\n try {\n const absolute = resolveWithinRoot(\n context.pathPrefix ? resolveWithinRoot(context.fernRoot, context.pathPrefix, context.repositoryRoot) : context.fernRoot,\n rawPath.trim(),\n context.repositoryRoot,\n )\n sourcePath = relative(context.fernRoot, absolute).replace(/\\\\/g, '/')\n } catch {\n warnOnce(context, `fern-unsafe-page-${rawPath}`, `Fern page path \"${rawPath}\" escapes the repository and was skipped.`)\n return ''\n }\n const navigationId = uniqueNavigationId(base || 'introduction', context)\n context.seenNavigationIds.add(navigationId)\n const isHidden = hidden || context.hiddenInherited === true\n context.descriptors.push({ sourcePath, navigationId, ...(navTitle ? { navTitle } : {}), ...(isHidden ? { hidden: true } : {}) })\n // `repository.ts` creates exactly one page per physical file, keyed off\n // the first nav location that registers it — a file listed at a second\n // nav location (Fern allows the same page under several sections) must\n // not point the tree at this position's own id, which will never become\n // a page. Point it at the id that actually owns the content instead;\n // `fernUnderscoreAliasRedirects` still adds a redirect from this\n // position's own derived route to that kept id, for any old/external\n // link built from it.\n const kept = context.sourcePathToNavigationId.get(sourcePath)\n if (kept) {\n if (!isHidden) {\n const owner = context.descriptors.find((descriptor) => descriptor.navigationId === kept)\n if (owner) owner.hidden = false\n }\n return kept\n }\n context.sourcePathToNavigationId.set(sourcePath, navigationId)\n return navigationId\n}\n\n/** Expand Fern's folder shorthand from actual Markdown files in document order. */\nfunction registerFolder(\n object: Record<string, unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): MigrationNavigationGroup | null {\n const rawPath = String(object.folder).trim()\n let folder: string\n try {\n folder = resolveWithinRoot(\n context.pathPrefix ? resolveWithinRoot(context.fernRoot, context.pathPrefix, context.repositoryRoot) : context.fernRoot,\n rawPath,\n context.repositoryRoot,\n )\n } catch {\n warnOnce(context, `fern-unsafe-folder-${rawPath}`, `Fern folder \"${rawPath}\" escapes the repository and was skipped.`)\n return null\n }\n if (!existsSync(folder) || !lstatSync(folder).isDirectory()) {\n warnOnce(context, `fern-missing-folder-${rawPath}`, `Fern folder \"${rawPath}\" does not exist and was skipped.`)\n return null\n }\n const label = typeof object.title === 'string' && object.title.trim() ? object.title.trim() : titleCase(basename(folder))\n // Folder titles are navigation labels. Fern keeps the directory name in\n // the route unless a slug override is authored.\n const segment = typeof object.slug === 'string' || object['skip-slug'] === true\n ? segmentFor(object, label, context)\n : fernBasicSlug(basename(folder))\n const segments = segment ? [...parentSegments, segment] : parentSegments\n const visit = (directory: string, routeSegments: Array<string>, depth: number): Array<string | MigrationNavigationGroup> => {\n if (depth > 12 || context.descriptors.length >= 5_000) return []\n const pages: Array<string | MigrationNavigationGroup> = []\n const entries = readdirSync(directory, { withFileTypes: true })\n .filter((entry) => !entry.name.startsWith('.') && !entry.isSymbolicLink())\n .sort((left, right) => Number(left.name !== 'index.mdx' && left.name !== 'index.md')\n - Number(right.name !== 'index.mdx' && right.name !== 'index.md') || left.name.localeCompare(right.name))\n for (const entry of entries) {\n const path = resolveWithin(directory, entry.name)\n if (entry.isDirectory()) {\n const nested = visit(path, [...routeSegments, fernBasicSlug(entry.name)], depth + 1)\n if (nested.length) pages.push({ group: titleCase(entry.name), pages: nested })\n } else if (entry.isFile() && ['.md', '.mdx'].includes(extname(entry.name).toLowerCase())) {\n const stem = basename(entry.name, extname(entry.name))\n const pageSegment = stem.toLowerCase() === 'index' ? null : fernBasicSlug(stem)\n const route = [...routeSegments, ...(pageSegment ? [pageSegment] : [])].join('/')\n const source = lstatSync(path).size <= MAX_CONFIG_BYTES ? readFileSync(path, 'utf8') : ''\n const frontmatter = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/)?.[1] ?? ''\n const hidden = /^hidden:\\s*true\\s*$/m.test(frontmatter)\n const registered = registerPageAt(relative(context.fernRoot, path), route, { ...context, pathPrefix: '' }, undefined, hidden)\n if (registered && !hidden && !context.hiddenInherited) pages.push(registered)\n }\n }\n return pages\n }\n const pages = visit(folder, segments, 0)\n if (!pages.length) return null\n addBareRouteRedirect(segments, pages, context)\n return { group: label, pages }\n}\n\nfunction registerPage(\n object: Record<string, unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): string | null {\n if (typeof object.path !== 'string' || !object.path.trim()) return null\n const label = typeof object.page === 'string' && object.page.trim() ? object.page.trim() : 'Untitled'\n const segment = segmentFor(object, label, context)\n const base = [...parentSegments, segment].filter(Boolean).join('/')\n return registerPageAt(object.path, base, context, label, object.hidden === true) || null\n}\n\n/** A `section`/`page`/`link`/`api`/`changelog` node from `layout` or `contents`. */\nfunction convertNode(\n node: unknown,\n parentSegments: Array<string>,\n context: WalkContext,\n): string | MigrationNavigationGroup | null {\n const object = objectValue(node)\n if (!object) return null\n\n if (typeof object.page === 'string') {\n const page = registerPage(object, parentSegments, context)\n return object.hidden === true || context.hiddenInherited ? null : page\n }\n\n if (typeof object.folder === 'string') {\n const folder = registerFolder(object, parentSegments, object.hidden === true ? { ...context, hiddenInherited: true } : context)\n return object.hidden === true || context.hiddenInherited ? null : folder\n }\n\n if (typeof object.section === 'string') {\n const label = object.section\n const segment = segmentFor(object, label, context)\n const segments = segment ? [...parentSegments, segment] : parentSegments\n const contents = Array.isArray(object.contents) ? object.contents : []\n const pages: Array<string | MigrationNavigationGroup> = []\n // A section can also carry its own `path`, making the section itself a\n // clickable landing page hosted at the section's own segment (not a\n // further-nested page segment).\n const hasOwnPath = typeof object.path === 'string' && object.path.trim().length > 0\n if (hasOwnPath) {\n const registered = registerPageAt(object.path as string, segments.join('/'), context, label, object.hidden === true)\n if (registered) pages.push(registered)\n }\n for (const child of contents) {\n const converted = convertNode(child, segments, object.hidden === true ? { ...context, hiddenInherited: true } : context)\n if (converted) pages.push(converted)\n }\n if (pages.length === 0) return null\n // A section without its own `path` still has a public URL at its segment;\n // Fern resolves that bare route to the section's first descendant page.\n if (!hasOwnPath && segment) addBareRouteRedirect(segments, pages, context)\n if (object.hidden === true || context.hiddenInherited) return null\n return {\n group: label,\n ...(typeof object.icon === 'string' ? { icon: object.icon } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n pages,\n }\n }\n\n if (typeof object.link === 'string') {\n const label = object.link.trim()\n const rawHref = typeof object.href === 'string' ? object.href.trim() : ''\n // Fern links may appear within a section, while Thally's group schema\n // accepts page ids only. Only absolute web URLs belong in the navbar;\n // canonicalizing through URL also rejects malformed or deceptive hosts.\n let href: string | undefined\n if (/^https?:\\/\\//i.test(rawHref) && !/[\\\\\\u0000-\\u0020\\u007f]/.test(rawHref)) {\n try {\n const url = new URL(rawHref)\n if (['http:', 'https:'].includes(url.protocol) && !url.username && !url.password) href = url.toString()\n } catch { /* An invalid authored link is reported below. */ }\n }\n if (label && href && object.hidden !== true && !context.hiddenInherited) {\n if (!context.externalLinks.some((link) => link.label === label && link.href === href)) {\n context.externalLinks.push({ label, href })\n }\n } else if (!href && object.hidden !== true && !context.hiddenInherited) {\n warnOnce(context, `fern-link-${rawHref}`, `Fern navigation link \"${label}\" has an unsafe or invalid external URL and was skipped.`)\n }\n return null\n }\n\n if (typeof object.api === 'string') {\n // `api` is the display title shown in the nav; `api-name` (when\n // present) is the actual `fern/apis/<name>/` folder name. A repo with\n // `api: Plant API` / `api-name: plants` has no `apis/Plant API`\n // folder, so preferring `api-name` is required to find the spec. A repo\n // can declare several `api:` nodes (e.g. a REST API and a WebSocket API\n // in separate tabs) — each is tracked and resolved independently rather\n // than only ever importing the first one found.\n // Like a section or page, an `api:` node contributes its own slug to the\n // route unless `skip-slug: true` (confirmed against a live Fern site:\n // VapiAI's `api-reference` tab has one `api:` node with `skip-slug:\n // true` served directly at the tab's own route, and a second `Webhooks`\n // node — no skip-slug — served one level deeper, at\n // \".../api-reference/webhooks\"). This is also this node's own auto-\n // generated operation page prefix, used to rewrite in-content links to\n // those pages onto Thally's route.\n const ownSegment = segmentFor(object, object.api, context)\n context.apiSections.push({\n name: typeof object['api-name'] === 'string' ? object['api-name'] : object.api,\n nameExplicit: typeof object['api-name'] === 'string',\n routeSegments: ownSegment ? [...parentSegments, ownSegment] : parentSegments,\n })\n return null\n }\n\n if (typeof object.changelog === 'string') {\n return registerFolder({ folder: object.changelog, title: 'Changelog', 'skip-slug': true }, parentSegments, context)\n }\n\n return null\n}\n\nfunction convertNodes(\n nodes: Array<unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): Array<string | MigrationNavigationGroup> {\n return nodes.flatMap((node) => {\n const converted = convertNode(node, parentSegments, context)\n return converted ? [converted] : []\n })\n}\n\nfunction groupsFromConverted(\n converted: Array<string | MigrationNavigationGroup>,\n): Array<MigrationNavigationGroup> {\n const loosePages = converted.filter((entry): entry is string => typeof entry === 'string')\n const groups = converted.filter((entry): entry is MigrationNavigationGroup => typeof entry !== 'string')\n return loosePages.length > 0 ? [{ group: 'Overview', pages: loosePages }, ...groups] : groups\n}\n\n/**\n * Resolve the default Fern version's navigation when no top-level nav\n * exists. `configDir` is the directory `chosen.path` is conventionally\n * relative to (the Fern root for a top-level docs.yml, or a product's own\n * directory for a product config); `context.repositoryRoot` (the whole\n * repository checkout) is the security boundary. A version file is a\n * legitimate Fern layout even when it lives outside `fern/` (e.g. a sibling\n * `docs/` directory referenced as `../docs/index.yml`), so it may resolve\n * anywhere inside the repository, not just under the Fern root — escapes\n * from the repository itself are still rejected. Once a version file loads,\n * its own `path:` entries are relative to *its* directory, not the Fern\n * root, so `pathPrefix` is shifted there for the rest of this config's walk.\n */\nfunction resolveVersionedNavigation(\n config: Record<string, unknown>,\n configDir: string,\n fernRoot: string,\n context: WalkContext,\n): Record<string, unknown> {\n if (Array.isArray(config.navigation)) return config\n if (Array.isArray(config.products)) {\n warnOnce(context, 'fern-products', 'Nested Fern multi-product docs are not supported; only this docs.yml was imported.')\n return config\n }\n if (!Array.isArray(config.versions)) return config\n const versions = config.versions.flatMap((entry) => {\n const version = objectValue(entry)\n return version ? [version] : []\n })\n const chosen = versions.find((version) => version.default === true) ?? versions[0]\n const skipped = versions.filter((version) => version !== chosen)\n .map((version) => (typeof version.version === 'string' ? version.version : undefined))\n .filter((name): name is string => Boolean(name))\n if (skipped.length > 0) {\n warnOnce(\n context,\n 'fern-versions',\n `Only the default Fern version was imported; other versions were skipped: ${skipped.join(', ')}.`,\n )\n }\n if (!chosen || typeof chosen.path !== 'string') return config\n try {\n const versionPath = resolveWithinRoot(configDir, chosen.path, context.repositoryRoot)\n if (!existsSync(versionPath) || !lstatSync(versionPath).isFile()) {\n warnOnce(context, 'fern-version-not-file', `Fern version file \"${chosen.path}\" is not a regular file and was skipped.`)\n return config\n }\n const versionConfig = objectValue(readBoundedYaml(versionPath))\n if (!versionConfig) return config\n context.pathPrefix = relative(fernRoot, dirname(versionPath)).replace(/\\\\/g, '/')\n return { ...config, navigation: versionConfig.navigation, tabs: versionConfig.tabs ?? config.tabs }\n } catch (error) {\n warnOnce(\n context,\n 'fern-version-read-failed',\n `Fern version file \"${chosen.path}\" could not be read (${error instanceof Error ? error.message : String(error)}) and was skipped.`,\n )\n return config\n }\n}\n\n/**\n * Build tabs for one docs config (the top-level docs.yml, or one product's\n * own config), rooted at `routePrefix`. Shared by the plain top-level path\n * and by `projectFernProducts` so both get identical tabbed/flat-navigation\n * and version-resolution handling.\n */\nfunction buildTabsFromConfig(\n rawConfig: Record<string, unknown>,\n configDir: string,\n fernRoot: string,\n routePrefix: Array<string>,\n fallbackTabLabel: string,\n context: WalkContext,\n): Array<MigrationNavigationTab> {\n const config = resolveVersionedNavigation(rawConfig, configDir, fernRoot, context)\n const tabsMeta = objectValue(config.tabs) ?? {}\n const navigation = config.navigation\n\n const isTabbedNavigation = Array.isArray(navigation)\n && navigation.length > 0\n && navigation.every((entry) => typeof objectValue(entry)?.tab === 'string')\n\n if (isTabbedNavigation) {\n return (navigation as Array<Record<string, unknown>>).flatMap((entry): Array<MigrationNavigationTab> => {\n const id = String(entry.tab)\n const meta = objectValue(tabsMeta[id]) ?? {}\n const label = typeof meta['display-name'] === 'string' ? meta['display-name'] : titleCase(id)\n const tabSegment = segmentFor(meta, label, context)\n const segments = [...routePrefix, ...(tabSegment ? [tabSegment] : [])]\n const layout = Array.isArray(entry.layout) ? entry.layout : []\n const sectionsBefore = context.apiSections.length\n const groups = groupsFromConverted(convertNodes(layout, segments, context))\n for (let index = sectionsBefore; index < context.apiSections.length; index += 1) {\n context.apiSections[index].tabLabel ??= label\n }\n if (groups.length === 0 && typeof meta.href === 'string' && /^https?:\\/\\//i.test(meta.href)) {\n return [{ tab: label, href: meta.href }]\n }\n if (groups.length === 0 && typeof meta.changelog === 'string') {\n // A Fern changelog tab names a directory rather than explicit page\n // nodes. Keep every MDX entry, newest dated filename first.\n const changelog = registerFolder({ folder: meta.changelog, title: label, 'skip-slug': true }, segments, context)\n if (changelog) {\n const indexRoute = segments.join('/')\n const descriptors = new Map(context.descriptors.map((descriptor) => [descriptor.navigationId, descriptor]))\n const visiblePages = changelog.pages.filter((page): page is string => typeof page === 'string')\n .filter((page) => !descriptors.get(page)?.hidden)\n // Fern's feed is ordered by publication date, while a directory\n // listing is alphabetical. An overview file may publish at the tab\n // root via frontmatter `slug`, so recognize it before slug remapping.\n const index = visiblePages.find((page) => {\n const descriptor = descriptors.get(page)\n if (!descriptor) return false\n const stem = basename(descriptor.sourcePath, extname(descriptor.sourcePath))\n return page === indexRoute || stem === 'overview' || stem === 'index'\n })\n const entries = visiblePages.filter((page) => page !== index).sort((left, right) => {\n const date = (page: string): string => descriptors.get(page)?.sourcePath.match(/\\d{4}-\\d{2}-\\d{2}/)?.[0] ?? ''\n return date(right).localeCompare(date(left)) || left.localeCompare(right)\n })\n // Fern renders the entries in the feed, not in its sidebar. Keep\n // each article routable for its permalink while showing only the\n // feed itself in the navigation tree.\n for (const entryId of entries) {\n const descriptor = descriptors.get(entryId)\n if (descriptor) descriptor.hidden = true\n }\n changelog.pages = [index ?? indexRoute]\n context.changelogIndexes.push({ route: indexRoute, entries })\n const latest = index ?? firstLeafId(changelog.pages)\n const bareRouteIndex = context.bareRouteRedirects.findIndex((redirect) => redirect.source === `/${indexRoute}`)\n const indexDescriptor = index ? descriptors.get(index) : undefined\n const indexSource = indexDescriptor && lstatSync(resolveWithinRoot(context.fernRoot, indexDescriptor.sourcePath, context.repositoryRoot)).size <= MAX_CONFIG_BYTES\n ? readFileSync(resolveWithinRoot(context.fernRoot, indexDescriptor.sourcePath, context.repositoryRoot), 'utf8') : ''\n const indexFrontmatter = indexSource.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/)?.[1] ?? ''\n const indexSlug = indexFrontmatter.match(/^slug:\\s*[\"']?([^\\s\"']+)[\"']?\\s*$/m)?.[1]?.replace(/^\\/+|\\/+$/g, '')\n const hasBarePage = index === indexRoute || indexSlug === indexRoute\n if (bareRouteIndex >= 0 && hasBarePage) context.bareRouteRedirects.splice(bareRouteIndex, 1)\n else if (latest && bareRouteIndex >= 0) context.bareRouteRedirects[bareRouteIndex].destination = `/${latest}`\n return [{ tab: label, groups: [changelog] }]\n }\n }\n if (groups.length === 0) return []\n if (segments.length > 0) addBareRouteRedirect(segments, groups, context)\n return [{\n tab: label,\n ...(typeof meta.icon === 'string' ? { icon: meta.icon } : {}),\n groups,\n }]\n })\n }\n if (Array.isArray(navigation)) {\n const sectionsBefore = context.apiSections.length\n const groups = groupsFromConverted(convertNodes(navigation, routePrefix, context))\n for (let index = sectionsBefore; index < context.apiSections.length; index += 1) {\n context.apiSections[index].tabLabel ??= fallbackTabLabel\n }\n if (groups.length > 0) {\n if (routePrefix.length > 0) addBareRouteRedirect(routePrefix, groups, context)\n return [{ tab: fallbackTabLabel, groups }]\n }\n }\n return []\n}\n\n/**\n * Project Fern's `products:` (a docs.yml that fans out into several\n * independently-navigable products, e.g. buildwithfern.com/learn) into one\n * top-level tab per product, each routed under its own `slug`/display-name\n * segment and reading its pages from its own `fern/products/<name>/`\n * directory.\n */\nfunction projectFernProducts(\n rawProducts: Array<unknown>,\n fernRoot: string,\n context: WalkContext,\n): Array<MigrationNavigationTab> {\n return rawProducts.flatMap((entry) => {\n const product = objectValue(entry)\n const rawPath = typeof product?.path === 'string' ? product.path.trim() : ''\n if (!product || !rawPath) return []\n const label = typeof product['display-name'] === 'string' && product['display-name'].trim()\n ? product['display-name'].trim()\n : 'Product'\n let productPath: string\n try {\n productPath = resolveWithin(fernRoot, rawPath)\n } catch {\n warnOnce(context, `fern-product-unsafe-${rawPath}`, `Fern product \"${label}\" path \"${rawPath}\" is unsafe and was skipped.`)\n return []\n }\n if (!existsSync(productPath) || !lstatSync(productPath).isFile()) {\n warnOnce(context, `fern-product-missing-${rawPath}`, `Fern product \"${label}\" path \"${rawPath}\" does not exist and was skipped.`)\n return []\n }\n let productConfig: Record<string, unknown> | null\n try {\n productConfig = objectValue(readBoundedYaml(productPath))\n } catch (error) {\n warnOnce(\n context,\n `fern-product-read-failed-${rawPath}`,\n `Fern product \"${label}\" could not be read (${error instanceof Error ? error.message : String(error)}) and was skipped.`,\n )\n return []\n }\n if (!productConfig) return []\n const productDir = dirname(productPath)\n const routeSegment = segmentFor(product, label, context)\n const priorPrefix = context.pathPrefix\n context.pathPrefix = relative(fernRoot, productDir).replace(/\\\\/g, '/')\n try {\n return buildTabsFromConfig(\n productConfig,\n productDir,\n fernRoot,\n routeSegment ? [routeSegment] : [],\n label,\n context,\n )\n } finally {\n context.pathPrefix = priorPrefix\n }\n })\n}\n\n/** Project a Fern `docs.yml` navigation tree into Thally tabs/groups. */\nexport function projectFernNavigation(input: {\n config: Record<string, unknown>\n fernRoot: string\n /**\n * The whole repository checkout — the security boundary for anything a\n * config file references (e.g. a `versions:` file living outside\n * `fern/`). Defaults to `fernRoot` for callers with no wider repository\n * context (e.g. unit tests), which reproduces the previous fernRoot-only\n * confinement.\n */\n repositoryRoot?: string\n}): FernNavigationResult {\n const context: WalkContext = {\n fernRoot: input.fernRoot,\n repositoryRoot: input.repositoryRoot ?? input.fernRoot,\n descriptors: [],\n seenNavigationIds: new Set(),\n apiSections: [],\n changelogIndexes: [],\n warnings: [],\n warningKeys: new Set(),\n externalLinks: [],\n bareRouteRedirects: [],\n segmentAliases: new Map(),\n pathPrefix: '',\n sourcePathToNavigationId: new Map(),\n }\n const config = input.config\n const hasProducts = Array.isArray(config.products) && config.products.length > 0 && !Array.isArray(config.navigation)\n const tabs = hasProducts\n ? projectFernProducts(config.products as Array<unknown>, input.fernRoot, context)\n : buildTabsFromConfig(config, input.fernRoot, input.fernRoot, [], 'Documentation', context)\n\n if (tabs.length === 0) {\n context.warnings.push({\n code: 'unsupported-config',\n message: 'Fern navigation could not be projected; generated navigation will be used.',\n })\n }\n\n const navbarLinks = Array.isArray(config['navbar-links'])\n ? (config['navbar-links'] as Array<unknown>).flatMap((entry) => {\n const link = objectValue(entry)\n const href = typeof link?.url === 'string'\n ? link.url\n : typeof link?.href === 'string' ? link.href : typeof link?.value === 'string' ? link.value : undefined\n const label = typeof link?.text === 'string'\n ? link.text\n : typeof link?.label === 'string' ? link.label : link?.type === 'github' ? 'GitHub' : undefined\n return href && label ? [{ label, href, ...(link?.type === 'github' ? { type: 'github' as const } : {}) }] : []\n })\n : []\n for (const link of context.externalLinks) {\n if (!navbarLinks.some((existing) => existing.label === link.label && existing.href === link.href)) {\n navbarLinks.push(link)\n }\n }\n const announcement = objectValue(config.announcement)\n const announcementMessage = typeof announcement?.message === 'string'\n ? announcement.message.trim()\n : ''\n // Fern permits HTML announcements; reduce them to escaped text and vetted\n // links before the Markdown-capable Thally banner renders the result.\n const bannerContent = announcementMarkdown(announcementMessage)\n\n const redirects = Array.isArray(config.redirects)\n ? (config.redirects as Array<unknown>).flatMap((value) => {\n const redirect = objectValue(value)\n if (!redirect || typeof redirect.source !== 'string' || typeof redirect.destination !== 'string') return []\n const rawSource = redirect.source.trim()\n const rawDestination = redirect.destination.trim()\n if (!isRedirectPathSafe(rawSource, rawDestination)) return []\n const translated = translateRedirectWildcards(rawSource, rawDestination)\n if (!translated) {\n warnOnce(\n context,\n `fern-redirect-wildcard-${rawSource}`,\n `Redirect from ${rawSource} uses a wildcard Next.js cannot express and was dropped.`,\n )\n return []\n }\n return [{\n source: translated.source,\n destination: translated.destination,\n ...(typeof redirect.permanent === 'boolean' ? { permanent: redirect.permanent } : {}),\n }]\n })\n : []\n\n const authoredSources = new Set(redirects.map((redirect) => redirect.source))\n const knownIds = new Set(context.descriptors.map((descriptor) => descriptor.navigationId))\n // The id that actually owns a descriptor's page content — itself, unless\n // the same source file was registered at an earlier nav location too, in\n // which case `registerPageAt` already pointed the tree at that earlier\n // id and this descriptor's own id never becomes a real page. Every\n // redirect destination must resolve through this, never a descriptor's\n // raw `navigationId`, or it targets a route that doesn't exist.\n const keptNavigationId = (descriptor: FernPageDescriptor): string => (\n context.sourcePathToNavigationId.get(descriptor.sourcePath) ?? descriptor.navigationId\n )\n // A page whose route includes a segment Fern derived from an explicit\n // `slug` that got hyphenated (see `segmentFor`) is also reachable on the\n // live Fern site at its literal, unslugified form (Fern's own routing is\n // file/slug-based and tolerates it) — e.g. BAML's `slug: baml_client`\n // means both `/ref/baml-client/...` (Thally's route) and\n // `/ref/baml_client/...` (in-body links, matching the folder name) are\n // live. Add one redirect per affected page so those in-body links keep\n // resolving instead of 404ing after migration.\n const segmentAliasRedirects = context.segmentAliases.size > 0\n ? context.descriptors.flatMap((descriptor) => {\n const segments = descriptor.navigationId.split('/')\n let changed = false\n const aliased = segments.map((segment) => {\n const literal = context.segmentAliases.get(segment)\n if (!literal) return segment\n changed = true\n return literal\n })\n if (!changed) return []\n const source = `/${aliased.join('/')}`\n const destination = `/${keptNavigationId(descriptor)}`\n if (source === destination || knownIds.has(aliased.join('/'))) return []\n return [{ source, destination }]\n })\n : []\n // A source file registered at more than one nav location (a Fern page\n // listed under both a guide section and a `slug: baml_client` reference\n // section, say) keeps exactly one page, at the first location's route —\n // Fern itself serves the content at every route it's registered under, so\n // every other location's own derived route redirects to the kept one\n // instead of 404ing.\n const duplicateNavRedirects = context.descriptors.flatMap((descriptor) => {\n const kept = keptNavigationId(descriptor)\n if (kept === descriptor.navigationId) return []\n return [{ source: `/${descriptor.navigationId}`, destination: `/${kept}` }]\n })\n const allRedirects = [\n ...redirects,\n ...context.bareRouteRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ...segmentAliasRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ...duplicateNavRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ]\n\n // Two `api:` nodes both nested under the same top-level tab (e.g.\n // Paradex's \"Production API Reference\" and \"Testnet API Reference\"\n // sections, both inside a `portal` tab) get the same `tabLabel` from the\n // loop above — Thally's schema allows only one `.api` per tab, so the\n // second would otherwise silently overwrite the first tab's binding.\n // Disambiguate every collision after the fact (the first claimant keeps\n // the plain tab label) using the node's own section route, which is\n // exactly what differs between them.\n const claimedTabLabels = new Set<string>()\n const disambiguatedApiSections = context.apiSections.map((section) => {\n if (!section.tabLabel || !claimedTabLabels.has(section.tabLabel)) {\n if (section.tabLabel) claimedTabLabels.add(section.tabLabel)\n return section\n }\n const distinguishingSegment = section.routeSegments.at(-1)\n let tabLabel = distinguishingSegment ? `${section.tabLabel}: ${titleCase(distinguishingSegment)}` : section.tabLabel\n // The route segment can itself title-case back to the tab's own label\n // (e.g. a section nested under a route segment also called\n // \"api-reference\"), producing a redundant \"API Reference: API\n // Reference\" name, or the segment-based label can still collide with\n // another section's. Either way, fall back to a plain ordinal suffix\n // instead of shipping a confusing or still-colliding tab name.\n if (!tabLabel || tabLabel === `${section.tabLabel}: ${section.tabLabel}` || claimedTabLabels.has(tabLabel)) {\n let ordinal = 2\n let candidate = `${section.tabLabel} (${ordinal})`\n while (claimedTabLabels.has(candidate)) {\n ordinal += 1\n candidate = `${section.tabLabel} (${ordinal})`\n }\n tabLabel = candidate\n }\n claimedTabLabels.add(tabLabel)\n return { ...section, tabLabel }\n })\n\n return {\n docsConfig: {\n tabs,\n ...(bannerContent ? { banner: { content: bannerContent, dismissible: true } } : {}),\n ...(navbarLinks.length > 0 ? { navbar: { links: navbarLinks } } : {}),\n ...(allRedirects.length > 0 ? { redirects: allRedirects } : {}),\n },\n descriptors: context.descriptors,\n warnings: context.warnings,\n apiSections: disambiguatedApiSections,\n changelogIndexes: context.changelogIndexes,\n }\n}\n","/** Render canonical migration bundles into a portable Thally repository tree. */\n\nimport { mergeComponentRegistry } from './components.js'\n\nimport type {\n MigrationBundle,\n MigrationDocsConfig,\n MigrationNavigationGroup,\n RenderedMigrationFile,\n} from './types.js'\n\nfunction yamlString(value: string): string {\n return JSON.stringify(value.replace(/\\s+/g, ' ').trim())\n}\n\nfunction renderPage(bundle: MigrationBundle, page: MigrationBundle['pages'][number]): string {\n return [\n '---',\n `title: ${yamlString(page.title)}`,\n page.navTitle ? `navTitle: ${yamlString(page.navTitle)}` : null,\n `description: ${yamlString(page.description)}`,\n page.descriptionPlacement === 'body' ? 'descriptionPlacement: body' : null,\n page.badge ? `badge: ${yamlString(page.badge)}` : null,\n page.keywords.length > 0 ? `keywords: [${page.keywords.map(yamlString).join(', ')}]` : null,\n page.mode ? `mode: ${yamlString(page.mode)}` : null,\n page.hidden ? 'hidden: true' : null,\n page.noindex ? 'noindex: true' : null,\n page.openapi ? `openapi: ${yamlString(page.openapi)}` : null,\n bundle.sourceKind === 'url' ? `source: ${yamlString(page.source)}` : null,\n '---',\n '',\n page.body,\n '',\n ].filter((line) => line !== null).join('\\n')\n}\n\n/** Merge imported tabs into an existing site without duplicating changelog tabs. */\nexport function mergeMigrationConfig(\n existing: MigrationDocsConfig,\n incoming: MigrationDocsConfig,\n): MigrationDocsConfig {\n const tabs = existing.tabs.filter((tab) => tab.tab.toLowerCase() !== 'changelog')\n const names = new Set(tabs.map((tab) => tab.tab.toLowerCase()))\n const seenPages = new Set<string>()\n function recordPages(pages: Array<string | MigrationNavigationGroup> = []): void {\n for (const page of pages) {\n if (typeof page === 'string') seenPages.add(page)\n else recordPages(page.pages)\n }\n }\n for (const tab of tabs) {\n recordPages(tab.pages)\n recordPages(tab.groups)\n }\n function uniquePages(\n pages: Array<string | MigrationNavigationGroup> = [],\n ): Array<string | MigrationNavigationGroup> {\n return pages.flatMap<string | MigrationNavigationGroup>((page) => {\n if (typeof page === 'string') {\n if (seenPages.has(page)) return []\n seenPages.add(page)\n return [page]\n }\n const children = uniquePages(page.pages)\n return children.length > 0 ? [{ ...page, pages: children }] : []\n })\n }\n function uniqueGroups(\n groups: Array<MigrationNavigationGroup> | undefined,\n ): Array<MigrationNavigationGroup> {\n return uniquePages(groups ?? []) as Array<MigrationNavigationGroup>\n }\n for (const tab of incoming.tabs) {\n if (tab.tab.toLowerCase() === 'changelog') continue\n const uniqueTab = {\n ...tab,\n ...(tab.pages ? { pages: uniquePages(tab.pages) } : {}),\n ...(tab.groups ? { groups: uniqueGroups(tab.groups) } : {}),\n }\n if ((tab.pages || tab.groups)\n && !uniqueTab.pages?.length\n && !uniqueTab.groups?.length\n && !tab.href\n && !tab.api) continue\n if (!names.has(tab.tab.toLowerCase())) {\n tabs.push(uniqueTab)\n names.add(tab.tab.toLowerCase())\n continue\n }\n const target = tabs.find((item) => item.tab.toLowerCase() === tab.tab.toLowerCase())\n if (!target) continue\n const incomingRootNodes = [\n ...(uniqueTab.pages ?? []),\n ...(uniqueTab.groups ?? []),\n ]\n if (uniqueTab.pages?.length) {\n target.pages = [...(target.pages ?? target.groups ?? []), ...incomingRootNodes]\n delete target.groups\n } else if (uniqueTab.groups?.length) {\n if (target.pages) target.pages = [...target.pages, ...uniqueTab.groups]\n else target.groups = [...(target.groups ?? []), ...uniqueTab.groups]\n }\n }\n const changelog = existing.tabs.find((tab) => tab.tab.toLowerCase() === 'changelog')\n ?? incoming.tabs.find((tab) => tab.tab.toLowerCase() === 'changelog')\n if (changelog) tabs.push(changelog)\n const i18n = existing.i18n || incoming.i18n\n ? {\n defaultLocale: existing.i18n?.defaultLocale ?? incoming.i18n?.defaultLocale ?? 'en',\n locales: [...new Map(\n [...(existing.i18n?.locales ?? []), ...(incoming.i18n?.locales ?? [])]\n .map((locale) => [locale.code, locale]),\n ).values()],\n }\n : undefined\n return {\n ...incoming,\n ...existing,\n tabs,\n // Collection presentation belongs to the imported information\n // architecture; starter defaults must not coerce source dropdowns to tabs.\n navigation: incoming.navigation ?? existing.navigation,\n ...(i18n ? { i18n } : {}),\n }\n}\n\n/** Materialize every canonical page, asset, and config as repository file changes. */\nexport function renderMigrationFiles(\n bundle: MigrationBundle,\n options: { existingConfig?: MigrationDocsConfig; existingComponentRegistry?: string } = {},\n): Array<RenderedMigrationFile> {\n const config = options.existingConfig\n ? mergeMigrationConfig(options.existingConfig, bundle.docsConfig)\n : bundle.docsConfig\n return [\n ...bundle.pages.map((page) => ({\n path: `src/content/${page.id}.mdx`,\n content: renderPage(bundle, page),\n })),\n ...bundle.assets.map((asset) => ({ path: `public/${asset.path}`, content: asset.content })),\n ...(bundle.componentFiles ?? []).flatMap((file) => file.path === 'src/mdx/custom-components.tsx'\n && options.existingComponentRegistry !== undefined && typeof file.content === 'string'\n ? mergeComponentRegistry(options.existingComponentRegistry, file.content)\n : [file]),\n { path: 'docs.json', content: `${JSON.stringify(config, null, 2)}\\n` },\n ]\n}\n","/**\n * Public URL adapter for the shared migration engine. Discovery prefers\n * machine-readable Markdown and sitemaps, remains scoped to the submitted docs\n * path, then falls back to bounded navigation crawling and HTML extraction.\n */\n\nimport { load } from 'cheerio'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport TurndownService from 'turndown'\nimport { unified } from 'unified'\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml'\n\nimport { parseMarkdownPage } from './mdx.js'\nimport { addMintlifyDirectoryRedirects, buildNavigationFromPages, projectMintlifyNavigation } from './navigation.js'\nimport { pageIdFromReference } from './path.js'\nimport type {\n MigrationBundle,\n MigrationFetcher,\n MigrationFetchResponse,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationPlatform,\n MigrationWarning,\n} from './types.js'\n\nconst DEFAULT_MAX_PAGES = 1_000\nconst DEFAULT_MAX_TOTAL_BYTES = 100_000_000\nconst MAX_DISCOVERED_URLS = 5_000\nconst MAX_LOCAL_RESPONSE_BYTES = 2_000_000\nconst MAX_SITEMAP_DOCUMENTS = 25\nconst PORTABLE_MDX_COMPONENTS = new Set([\n 'Accordion', 'AccordionGroup', 'Badge', 'Callout', 'Card', 'CardGroup',\n 'Check', 'CodeGroup', 'Color', 'Column', 'Columns', 'ContentPanel', 'Danger', 'Error', 'Expandable',\n 'Agent', 'AgentPrompt', 'BannerPreview', 'Embed', 'File', 'Folder', 'Frame', 'GitHub', 'Github', 'Hero', 'Human',\n 'Icon', 'Info', 'InlinePanel', 'InlineRequestExample', 'InlineResponseExample',\n 'Latex', 'LegacyView', 'Mermaid', 'Note', 'Panel', 'ParamField', 'Prompt',\n 'PromptAssistant', 'PromptUser',\n 'RequestExample', 'ResponseExample', 'ResponseField', 'Step', 'Steps',\n 'Tab', 'Tabs', 'Terminal', 'TerminalInput', 'TerminalOutput', 'Tile', 'TileGroup',\n 'Tip', 'Tooltip', 'Tree', 'Update', 'View', 'Visibility', 'Warning',\n])\nconst LOCALE_CODES = new Set([\n 'ar', 'cs', 'da', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hi', 'hu', 'id',\n 'it', 'ja', 'ko', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv',\n 'th', 'tr', 'uk', 'vi', 'zh', 'pt-br', 'zh-hans', 'zh-hant',\n])\nconst PORTABLE_URL_PROPS = 'href|src|img|primaryHref|secondaryHref'\nconst PORTABLE_URL_PROP_NAMES = new Set(PORTABLE_URL_PROPS.split('|'))\nconst remoteMarkdownParser = unified().use(remarkParse).use(remarkMdx)\n\ninterface RemoteMarkdownAttributeValue {\n type: string\n value: string\n}\n\ninterface RemoteMarkdownAttribute {\n type: string\n name?: string\n value?: string | null | RemoteMarkdownAttributeValue\n}\n\ninterface RemoteMarkdownNode {\n type: string\n alt?: string | null\n attributes?: Array<RemoteMarkdownAttribute>\n identifier?: string\n url?: string\n value?: string\n children?: Array<RemoteMarkdownNode>\n position?: {\n start: { offset?: number }\n end: { offset?: number }\n }\n}\n\ninterface EmbeddedOpenApiFragment {\n method: string\n path: string\n document: Record<string, unknown>\n}\n\nexport interface UrlMigrationOptions {\n sourceUrl: string\n /** Explicit caller selection; omitted callers retain source auto-detection. */\n platform?: MigrationPlatform\n fetcher?: MigrationFetcher\n maxPages?: number\n concurrency?: number\n maxTotalBytes?: number\n}\n\n/** Validate the transport-level shape of a docs URL; hosted callers add SSRF checks. */\nexport function validateMigrationUrl(value: string): URL {\n let url: URL\n try {\n url = new URL(value)\n } catch {\n throw new Error('Enter a complete documentation URL, including https://.')\n }\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new Error('Documentation imports support only HTTP and HTTPS URLs.')\n }\n if (url.username || url.password) throw new Error('Documentation URLs cannot contain credentials.')\n url.hash = ''\n return url\n}\n\nasync function readResponseBody(response: Response): Promise<string> {\n const contentLength = Number(response.headers.get('content-length') ?? 0)\n if (contentLength > MAX_LOCAL_RESPONSE_BYTES) throw new Error('A documentation response exceeded the 2 MB import limit.')\n if (!response.body) return ''\n const reader = response.body.getReader()\n const chunks: Array<Uint8Array> = []\n let size = 0\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > MAX_LOCAL_RESPONSE_BYTES) {\n await reader.cancel()\n throw new Error('A documentation response exceeded the 2 MB import limit.')\n }\n chunks.push(value)\n }\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(body)\n}\n\n/** Fetch implementation for local CLI usage. Cloud injects its pinned network boundary. */\nexport const defaultMigrationFetcher: MigrationFetcher = async (url, request) => {\n const response = await fetch(url, {\n headers: {\n Accept: request.accept,\n 'User-Agent': 'Thally-Migrate/1.0 (+https://thally.io)',\n },\n redirect: 'follow',\n signal: AbortSignal.timeout(15_000),\n })\n if (!response.ok) throw new Error(`Documentation server returned ${response.status}.`)\n return {\n finalUrl: new URL(response.url),\n body: await readResponseBody(response),\n contentType: response.headers.get('content-type') ?? '',\n headers: Object.fromEntries(response.headers.entries()),\n }\n}\n\nfunction docsScopePath(source: URL): string {\n const path = source.pathname.replace(/\\/+$/, '') || '/'\n if (path === '/') return '/'\n const segments = path.split('/').filter(Boolean)\n return `/${segments.length > 1 ? segments[0] : segments.join('/')}`\n}\n\nfunction machineIndexScopePath(\n source: URL,\n documents: Array<MigrationFetchResponse | null>,\n): string | null {\n const candidates = new Set<string>()\n for (const document of documents) {\n if (!document) continue\n const references = [...headerLinks(document)]\n if (/html/i.test(document.contentType)) {\n const $ = load(document.body)\n references.push(...$('link[href], a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter((href) => /\\/(?:llms(?:-full)?\\.txt|sitemap\\.xml)(?:[?#]|$)/i.test(href)))\n }\n for (const reference of references) {\n try {\n const indexUrl = new URL(reference, document.finalUrl)\n if (indexUrl.origin !== source.origin) continue\n const scope = indexUrl.pathname.replace(/\\/(?:llms(?:-full)?\\.txt|sitemap\\.xml)$/i, '') || '/'\n if (isInScope(source, source, scope)) candidates.add(scope)\n } catch {\n // Malformed discovery hints are ignored just like malformed page links.\n }\n }\n }\n return [...candidates].sort((left, right) => right.length - left.length)[0] ?? null\n}\n\nfunction isInScope(url: URL, source: URL, scopePath: string): boolean {\n if (url.origin !== source.origin || !['http:', 'https:'].includes(url.protocol)) return false\n const path = url.pathname.replace(/\\/+$/, '') || '/'\n if (scopePath === '/') return true\n return path === scopePath || path === `${scopePath}.md` || path.startsWith(`${scopePath}/`)\n}\n\nfunction normalizeCandidate(value: string, base: URL, source: URL, scopePath: string): URL | null {\n try {\n const url = new URL(value, base)\n url.hash = ''\n if (!isInScope(url, source, scopePath)) return null\n if (url.pathname.startsWith('/cdn-cgi/')) return null\n if (/\\/(?:llms(?:-full)?|robots)\\.txt$/i.test(url.pathname)\n || /\\/sitemap\\.xml$/i.test(url.pathname)) return null\n if (/\\.(?:avif|bmp|gif|ico|jpe?g|mp[34]|pdf|png|svg|ya?ml|webm|webp|zip)$/i.test(url.pathname)\n || /\\/(?:openapi|swagger|asyncapi)[^/]*\\.json$/i.test(url.pathname)) return null\n return url\n } catch {\n return null\n }\n}\n\nfunction candidateIdentity(url: URL): string {\n const pathname = url.pathname.replace(/\\.mdx?$/i, '').replace(/\\/+$/, '') || '/'\n return `${url.origin}${pathname}${url.search}`\n}\n\nfunction pageIdForUrl(url: URL, scopePath: string): string | null {\n let path = url.pathname.replace(/\\/+$/, '')\n if (scopePath !== '/') {\n if (path === `${scopePath}.md`) path = ''\n else if (path === scopePath) path = ''\n else if (path.startsWith(`${scopePath}/`)) path = path.slice(scopePath.length + 1)\n }\n return pageIdFromReference(path.replace(/^\\/+/, '') || 'introduction', true)\n}\n\nfunction canonicalLocalizedPageId(id: string): string {\n const [segment, ...rest] = id.split('/')\n if (LOCALE_CODES.has(segment)) return rest.length > 0 ? id : `${segment}/introduction`\n for (const locale of LOCALE_CODES) {\n if (segment !== `${locale}-api-reference`) continue\n return [locale, 'api-reference', ...rest].join('/')\n }\n return id\n}\n\nfunction detectUrlPlatform(document: MigrationFetchResponse): MigrationPlatform {\n const headers = Object.entries(document.headers ?? {})\n .map(([key, value]) => `${key}:${value ?? ''}`)\n .join(' ')\n const value = `${document.body.slice(0, 200_000)} ${headers}`.toLowerCase()\n if (value.includes('__mintlify') || value.includes('/mintlify-assets/')\n || value.includes('x-mintlify-') || value.includes('/_mintlify/')) return 'mintlify'\n if (value.includes('docusaurus') || value.includes('__docusaurus')) return 'docusaurus'\n if (value.includes('gitbook')) return 'gitbook'\n if (value.includes('nextra')) return 'nextra'\n if (value.includes('vitepress')) return 'vitepress'\n if (value.includes('starlight')) return 'starlight'\n return 'generic'\n}\n\nfunction jsonObjectAfterKey(value: string, key: string): Record<string, unknown> | null {\n let cursor = 0\n const marker = `\"${key}\":`\n while (cursor < value.length) {\n const markerIndex = value.indexOf(marker, cursor)\n if (markerIndex < 0) return null\n let start = markerIndex + marker.length\n while (/\\s/.test(value[start] ?? '')) start += 1\n if (value[start] !== '{') {\n cursor = start + 1\n continue\n }\n let depth = 0\n let isQuoted = false\n let isEscaped = false\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (isQuoted) {\n if (isEscaped) isEscaped = false\n else if (character === '\\\\') isEscaped = true\n else if (character === '\"') isQuoted = false\n continue\n }\n if (character === '\"') {\n isQuoted = true\n continue\n }\n if (character === '{') depth += 1\n if (character === '}') {\n depth -= 1\n if (depth !== 0) continue\n try {\n const parsed = JSON.parse(value.slice(start, index + 1)) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : null\n } catch {\n break\n }\n }\n }\n cursor = start + 1\n }\n return null\n}\n\n/**\n * Current Mintlify themes embed the resolved docs config and scoped navigation\n * in React Flight. Reading that data is substantially more faithful than\n * inferring information architecture from whichever responsive nav is visible.\n */\nfunction embeddedMintlifyConfig(body: string): Record<string, unknown> | null {\n const $ = load(body)\n const flightPayloads: Array<string> = []\n $('script').each((_index, element) => {\n const script = $(element).text()\n for (const match of script.matchAll(/self\\.__next_f\\.push\\(\\[1,(\"(?:\\\\.|[^\"\\\\])*\")\\]\\)/g)) {\n try {\n const payload = JSON.parse(match[1])\n if (typeof payload === 'string') flightPayloads.push(payload)\n } catch {\n // Older or customized shells fall back to bounded DOM inference.\n }\n }\n })\n if (flightPayloads.length === 0) return null\n const payload = flightPayloads.join('\\n')\n const docsConfig = jsonObjectAfterKey(payload, 'docsConfig')\n const scopedNavigation = jsonObjectAfterKey(payload, 'scopedNav')\n if (!docsConfig && !scopedNavigation) return null\n return {\n ...(docsConfig ?? {}),\n ...(scopedNavigation ? { navigation: scopedNavigation } : {}),\n }\n}\n\nfunction plainDescription(value: string): string {\n return value\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1')\n .replace(/[`*_>#-]/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 240)\n}\n\nfunction withoutFencedCode(body: string): string {\n let fenceCharacter = ''\n let fenceLength = 0\n return body.split('\\n').map((line) => {\n const match = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (match && !fenceCharacter) {\n fenceCharacter = match[1][0]\n fenceLength = match[1].length\n return ''\n }\n if (match && match[1][0] === fenceCharacter && match[1].length >= fenceLength\n && match[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n return ''\n }\n return fenceCharacter ? '' : line\n }).join('\\n')\n}\n\nfunction eventHandlerPropEnd(value: string, start: number): number | null {\n const opening = value[start]\n if (opening === '\"' || opening === \"'\") {\n for (let index = start + 1; index < value.length; index += 1) {\n if (value[index] === opening && value[index - 1] !== '\\\\') return index + 1\n }\n return null\n }\n if (opening !== '{') {\n const match = value.slice(start).match(/^[^\\s>]+/)\n return match ? start + match[0].length : null\n }\n let depth = 0\n let quote = ''\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (quote) {\n if (character === quote && value[index - 1] !== '\\\\') quote = ''\n continue\n }\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character\n continue\n }\n if (character === '{') depth += 1\n if (character === '}') {\n depth -= 1\n if (depth === 0) return index + 1\n }\n }\n return null\n}\n\nfunction stripEventHandlerProps(line: string): string {\n const matcher = /\\s+on[A-Z][A-Za-z0-9]*\\s*=\\s*/g\n let cursor = 0\n let result = ''\n for (const match of line.matchAll(matcher)) {\n const start = match.index\n const valueStart = start + match[0].length\n const end = eventHandlerPropEnd(line, valueStart)\n if (end === null) continue\n result += line.slice(cursor, start)\n cursor = end\n }\n return cursor === 0 ? line : `${result}${line.slice(cursor)}`\n}\n\nfunction isSafePortableUrl(value: string): boolean {\n try {\n const parsed = new URL(value, 'https://relative.thally.invalid')\n return ['http:', 'https:', 'mailto:', 'tel:'].includes(parsed.protocol)\n } catch {\n return false\n }\n}\n\nfunction decodeHtmlAttribute(value: string): string {\n const document = load(`<i data-thally-value=\"${value.replace(/\"/g, '"')}\"></i>`)\n return document('i').attr('data-thally-value') ?? ''\n}\n\n/** Escape imported copy for Markdown text and MDX's additional delimiters. */\nfunction escapeMarkdownText(value: string, escapeTableSeparator = false): string {\n let escaped = ''\n for (const character of value) {\n if (character === '\\\\') escaped += '\\\\\\\\'\n else if (character === '[' || character === ']') escaped += `\\\\${character}`\n else if (character === '<') escaped += '<'\n else if (character === '>') escaped += '>'\n else if (character === '{') escaped += '{'\n else if (character === '}') escaped += '}'\n else if (character === '|' && escapeTableSeparator) escaped += '\\\\|'\n else escaped += character\n }\n return escaped\n}\n\nfunction markdownLinkDestination(value: string): string | null {\n try {\n return encodeURI(value)\n .replace(/\\(/g, '%28')\n .replace(/\\)/g, '%29')\n .replace(/&/g, '&')\n } catch {\n return null\n }\n}\n\nfunction htmlOpeningTagEnd(value: string, start: number): number | null {\n let quote = ''\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (quote) {\n if (character === quote) quote = ''\n continue\n }\n if (character === '\"' || character === \"'\") {\n quote = character\n continue\n }\n if (character === '>') return index + 1\n }\n return null\n}\n\nfunction replacePortableHtmlImages(value: string): string {\n const matcher = /<img\\b/gi\n let cursor = 0\n let output = ''\n for (const match of value.matchAll(matcher)) {\n const start = match.index\n if (start < cursor) continue\n const end = htmlOpeningTagEnd(value, start + match[0].length)\n if (end === null) continue\n const fragment = load(value.slice(start, end))\n const image = fragment('img').first()\n const source = image.attr('src')\n const destination = source && isSafePortableUrl(source) ? markdownLinkDestination(source) : null\n const alternative = escapeMarkdownText(image.attr('alt') ?? '')\n output += value.slice(cursor, start)\n output += destination ? `` : alternative\n cursor = end\n }\n return cursor === 0 ? value : `${output}${value.slice(cursor)}`\n}\n\nfunction replacePortableHtmlAnchors(value: string): string {\n const matcher = /<a\\b/gi\n let cursor = 0\n let output = ''\n for (const match of value.matchAll(matcher)) {\n const start = match.index\n if (start < cursor) continue\n const openingEnd = htmlOpeningTagEnd(value, start + match[0].length)\n if (openingEnd === null) continue\n const closingMatch = /<\\/a\\s*>/gi\n closingMatch.lastIndex = openingEnd\n const closing = closingMatch.exec(value)\n if (!closing) continue\n const end = closing.index + closing[0].length\n const fragment = load(value.slice(start, end))\n const anchor = fragment('a').first()\n const href = anchor.attr('href')\n const label = escapeMarkdownText(anchor.text().replace(/\\s+/g, ' ').trim())\n const destination = href && isSafePortableUrl(href) ? markdownLinkDestination(href) : null\n output += value.slice(cursor, start)\n output += destination ? `[${label}](${destination})` : label\n cursor = end\n }\n return cursor === 0 ? value : `${output}${value.slice(cursor)}`\n}\n\nfunction markdownNodeText(node: RemoteMarkdownNode): string {\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'image' || node.type === 'imageReference') return node.alt ?? ''\n return (node.children ?? []).map(markdownNodeText).join('')\n}\n\n/**\n * Remove unsafe Markdown links using the actual Markdown/MDX parse tree. This\n * catches entity-encoded schemes and balanced destinations that regexes cannot\n * classify reliably, while leaving code fences and ordinary prose untouched.\n */\nfunction sanitizeMarkdownUrls(value: string): string | null {\n let root: RemoteMarkdownNode\n try {\n root = remoteMarkdownParser.parse(value) as RemoteMarkdownNode\n } catch {\n return null\n }\n\n let hasUnsafeMdxSyntax = false\n const validateMdxSyntax = (node: RemoteMarkdownNode) => {\n if (node.type === 'mdxTextExpression'\n || node.type === 'mdxFlowExpression'\n || node.type === 'mdxjsEsm') {\n hasUnsafeMdxSyntax = true\n return\n }\n if (node.type === 'mdxJsxTextElement' || node.type === 'mdxJsxFlowElement') {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== 'mdxJsxAttribute' || !attribute.name\n || /^on[A-Z]/.test(attribute.name)) {\n hasUnsafeMdxSyntax = true\n return\n }\n let staticValue: unknown = attribute.value\n if (attribute.value && typeof attribute.value === 'object') {\n if (attribute.value.type !== 'mdxJsxAttributeValueExpression') {\n hasUnsafeMdxSyntax = true\n return\n }\n try {\n staticValue = JSON.parse(attribute.value.value)\n } catch {\n hasUnsafeMdxSyntax = true\n return\n }\n }\n if (PORTABLE_URL_PROP_NAMES.has(attribute.name)\n && (typeof staticValue !== 'string'\n || !isSafePortableUrl(decodeHtmlAttribute(staticValue)))) {\n hasUnsafeMdxSyntax = true\n return\n }\n }\n }\n for (const child of node.children ?? []) validateMdxSyntax(child)\n }\n validateMdxSyntax(root)\n if (hasUnsafeMdxSyntax) return null\n\n const unsafeDefinitions = new Set<string>()\n const visitDefinitions = (node: RemoteMarkdownNode) => {\n if (node.type === 'definition' && node.identifier && node.url\n && !isSafePortableUrl(node.url)) unsafeDefinitions.add(node.identifier.toLowerCase())\n for (const child of node.children ?? []) visitDefinitions(child)\n }\n visitDefinitions(root)\n\n const replacements: Array<{ start: number; end: number; value: string }> = []\n const replaceNode = (node: RemoteMarkdownNode, replacement: string): boolean => {\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n if (start === undefined || end === undefined) return false\n replacements.push({ start, end, value: replacement })\n return true\n }\n const visitUrls = (node: RemoteMarkdownNode) => {\n const hasUnsafeDirectUrl = (node.type === 'link' || node.type === 'image')\n && typeof node.url === 'string'\n && !isSafePortableUrl(node.url)\n const hasUnsafeReference = (node.type === 'linkReference' || node.type === 'imageReference')\n && typeof node.identifier === 'string'\n && unsafeDefinitions.has(node.identifier.toLowerCase())\n if (hasUnsafeDirectUrl || hasUnsafeReference) {\n if (replaceNode(node, escapeMarkdownText(markdownNodeText(node)))) return\n }\n if (node.type === 'definition' && node.identifier\n && unsafeDefinitions.has(node.identifier.toLowerCase())) {\n if (replaceNode(node, '')) return\n }\n for (const child of node.children ?? []) visitUrls(child)\n }\n visitUrls(root)\n\n return replacements\n .sort((left, right) => right.start - left.start)\n .reduce((result, replacement) => (\n `${result.slice(0, replacement.start)}${replacement.value}${result.slice(replacement.end)}`\n ), value)\n}\n\nfunction hasUnsafePortableUrlProp(value: string): boolean {\n const quotedProps = new RegExp(`\\\\b(?:${PORTABLE_URL_PROPS})\\\\s*=\\\\s*(['\"])([^'\"\\\\r\\\\n]*)\\\\1`, 'gi')\n for (const match of value.matchAll(quotedProps)) {\n if (!isSafePortableUrl(decodeHtmlAttribute(match[2]))) return true\n }\n const expressionProps = new RegExp(`\\\\b(?:${PORTABLE_URL_PROPS})\\\\s*=\\\\s*\\\\{\\\\s*(\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\")\\\\s*\\\\}`, 'gi')\n for (const match of value.matchAll(expressionProps)) {\n try {\n if (!isSafePortableUrl(decodeHtmlAttribute(JSON.parse(match[1])))) return true\n } catch {\n return true\n }\n }\n return false\n}\n\nfunction portableHtmlToMarkdown(value: string): string {\n return replacePortableHtmlAnchors(replacePortableHtmlImages(value))\n .replace(/<span\\b[^>]*>|<\\/span>/gi, '')\n .replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_original, level: string, content: string) => {\n return `\\n${'#'.repeat(Number(level))} ${content.trim()}\\n`\n })\n .replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_original, content: string) => `\\n${content.trim()}\\n`)\n .replace(/<br\\s*\\/?\\s*>/gi, '\\n')\n .replace(/<\\/?(?:article|div|main|section)\\b[^>]*>/gi, '')\n}\n\nfunction transformMarkdownProse(body: string, transform: (value: string) => string): string {\n const output: Array<string> = []\n let prose: Array<string> = []\n let fenceCharacter = ''\n let fenceLength = 0\n const flushProse = () => {\n if (prose.length === 0) return\n output.push(transform(prose.join('\\n')))\n prose = []\n }\n for (const line of body.split('\\n')) {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (fence && !fenceCharacter) {\n flushProse()\n fenceCharacter = fence[1][0]\n fenceLength = fence[1].length\n output.push(line)\n continue\n }\n if (fenceCharacter) {\n output.push(line)\n if (fence && fence[1][0] === fenceCharacter && fence[1].length >= fenceLength\n && fence[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n }\n continue\n }\n prose.push(line)\n }\n flushProse()\n return output.join('\\n')\n}\n\nfunction sanitizeRemoteMarkdown(body: string): string | null {\n let fenceCharacter = ''\n let fenceLength = 0\n const portableBody = transformMarkdownProse(body, portableHtmlToMarkdown)\n const sanitized = portableBody.split('\\n').map((line) => {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (fence && !fenceCharacter) {\n fenceCharacter = fence[1][0]\n fenceLength = fence[1].length\n return line\n }\n if (fence && fence[1][0] === fenceCharacter && fence[1].length >= fenceLength\n && fence[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n return line\n }\n if (fenceCharacter) return line\n return portableHtmlToMarkdown(stripEventHandlerProps(line\n // Remove obviously unsafe image destinations before MDX parsing. A data\n // URL can itself contain raw `<svg ...>` syntax that makes an otherwise\n // removable Markdown image fail the MDX grammar before the AST exists.\n .replace(/!\\[([^\\]]*)\\]\\(\\s*([^)]+)\\)/g, (original, alternative: string, destination: string) => (\n isSafePortableUrl(decodeHtmlAttribute(destination.replace(/^<|>$/g, '')))\n ? original\n : escapeMarkdownText(alternative)\n ))))\n }).join('\\n')\n const urlSafeMarkdown = sanitizeMarkdownUrls(sanitized)\n if (urlSafeMarkdown === null) return null\n const executable = withoutFencedCode(urlSafeMarkdown)\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, '')\n .replace(/<(?:https?:\\/\\/|mailto:)[^>]+>/gi, '')\n .replace(/(`+)[\\s\\S]*?\\1/g, '')\n if (/^\\s*(?:import|export)\\s/m.test(executable)) return null\n // A public Markdown endpoint is still attacker-controlled MDX. Preserve\n // known documentation primitives and JSON-literal props, but never compile\n // executable expressions, raw HTML, event handlers, or local components.\n let hasUnsafeExpression = false\n const withoutStaticProps = executable.replace(/=\\{([^{}\\n]*)\\}/g, (original, value: string) => {\n try {\n JSON.parse(value)\n return '=\"\"'\n } catch {\n hasUnsafeExpression = true\n return original\n }\n }).replace(/\\\\[{}]/g, '')\n if (hasUnsafeExpression || /[{}]/.test(withoutStaticProps)\n || /\\bon[A-Z][A-Za-z]*\\s*=/g.test(withoutStaticProps)\n || hasUnsafePortableUrlProp(executable)) return null\n for (const match of withoutStaticProps.matchAll(/<\\/?([A-Za-z][A-Za-z0-9.]*)(?:\\s|>|\\/)/g)) {\n const component = match[1].split('.', 1)[0]\n if (!PORTABLE_MDX_COMPONENTS.has(component)) return null\n }\n return urlSafeMarkdown\n}\n\nfunction migratedHref(\n href: string,\n currentUrl: URL,\n source: URL,\n scopePath: string,\n importedIds: Set<string>,\n sourceHomePageId?: string,\n): string {\n if (/^(?:javascript|data|vbscript):/i.test(href)) return '#'\n if (href.startsWith('#') || /^(?:mailto|tel):/i.test(href)) return href\n try {\n const target = new URL(href, currentUrl)\n if (target.origin !== source.origin) return href\n if (scopePath === '/' && candidateIdentity(target) === candidateIdentity(source)) {\n return `/${target.search}${target.hash}`\n }\n let path = target.pathname\n if (scopePath !== '/' && (path === scopePath || path.startsWith(`${scopePath}/`))) {\n path = path.slice(scopePath.length)\n }\n const id = pageIdFromReference(path.replace(/^\\/+/, '') || 'introduction')\n const localizedId = id ? canonicalLocalizedPageId(id) : id\n const destinationId = localizedId === sourceHomePageId ? 'introduction' : localizedId\n let importedDestinationId = destinationId && importedIds.has(destinationId)\n ? destinationId\n : undefined\n if (destinationId && !importedDestinationId) {\n importedDestinationId = [`${destinationId}/overview`, `${destinationId}/introduction`]\n .find((candidate) => importedIds.has(candidate))\n ?? [...importedIds].find((candidate) => candidate.startsWith(`${destinationId}/`))\n }\n if (importedDestinationId) {\n const destination = importedDestinationId === 'introduction' ? '/' : `/${importedDestinationId}`\n return `${destination}${target.search}${target.hash}`\n }\n // Same-origin marketing and intentionally missing example links remain\n // valid external URLs instead of becoming broken links in the new site.\n return target.toString()\n } catch {\n return href\n }\n}\n\nfunction rewriteInternalLinks(\n body: string,\n currentUrl: URL,\n source: URL,\n scopePath: string,\n importedIds: Set<string>,\n sourceHomePageId?: string,\n): string {\n const markdown = body.replace(/(?<!!)\\[([^\\]]+)\\]\\(([^)\\s]+)(\\s+['\"][^'\"]*['\"])?\\)/g, (\n original,\n label: string,\n href: string,\n title = '',\n ) => {\n const destination = migratedHref(href, currentUrl, source, scopePath, importedIds, sourceHomePageId)\n return destination === href ? original : `[${label}](${destination}${title})`\n })\n return markdown.replace(/\\bhref=(['\"])([^'\"]+)\\1/g, (_original, quote: string, href: string) => {\n const destination = migratedHref(href, currentUrl, source, scopePath, importedIds, sourceHomePageId)\n return `href=${quote}${destination}${quote}`\n })\n}\n\nfunction remoteMarkdownMetadata(body: string): {\n content: string\n title?: string\n description?: string\n sidebarTitle?: string\n tag?: string\n mode?: string\n hidden?: boolean\n noindex?: boolean\n} {\n if (!/^---\\r?\\n/.test(body)) return { content: body }\n const end = body.slice(4, 65_540).search(/\\r?\\n---(?:\\r?\\n|$)/)\n if (end < 0) return { content: body }\n const frontmatter = body.slice(4, end + 4)\n const contentStart = end + 4 + body.slice(end + 4).match(/^\\r?\\n---(?:\\r?\\n|$)/)![0].length\n function scalar(key: string): string | undefined {\n const value = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, 'm'))?.[1].trim()\n if (!value) return undefined\n if (/^['\"].*['\"]$/.test(value)) {\n try {\n const parsed = JSON.parse(value.replace(/^'/, '\"').replace(/'$/, '\"'))\n return typeof parsed === 'string' ? parsed : undefined\n } catch {\n return value.slice(1, -1)\n }\n }\n return value.slice(0, 500)\n }\n return {\n content: body.slice(contentStart),\n title: scalar('title'),\n description: scalar('description'),\n sidebarTitle: scalar('sidebarTitle'),\n tag: scalar('tag'),\n mode: scalar('mode'),\n hidden: scalar('hidden') === 'true' ? true : undefined,\n noindex: scalar('noindex') === 'true' ? true : undefined,\n }\n}\n\nfunction stripMintlifyDocumentationIndex(body: string): string {\n const lines = body.split(/\\r?\\n/)\n if (!/^>\\s*##\\s+Documentation Index\\s*$/i.test(lines[0] ?? '')\n || !/^>.*\\/llms(?:-full)?\\.txt/i.test(lines[1] ?? '')\n || !/^>.*discover all available pages/i.test(lines[2] ?? '')) return body\n let index = 3\n while (index < lines.length && /^>/.test(lines[index])) index += 1\n while (index < lines.length && lines[index].trim() === '') index += 1\n return lines.slice(index).join('\\n')\n}\n\nfunction extractEmbeddedOpenApi(content: string): {\n content: string\n openapi?: string\n fragment?: EmbeddedOpenApiFragment\n} {\n const fencePattern = /^\\s{0,3}(`{3,}|~{3,})(?:yaml|yml|json)\\s+(\\S+\\.(?:yaml|yml|json))\\s+(delete|get|head|options|patch|post|put|trace)\\s+(\\/\\S+)\\s*\\r?\\n([\\s\\S]*?)^\\s{0,3}\\1\\s*$/im\n const match = fencePattern.exec(content)\n if (!match) return { content }\n try {\n const parsed = parseYaml(match[5], { maxAliasCount: 50 })\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { content }\n const document = parsed as Record<string, unknown>\n if (typeof document.openapi !== 'string' && typeof document.swagger !== 'string') return { content }\n const method = match[3].toUpperCase()\n const path = match[4]\n const paths = document.paths\n if (!paths || typeof paths !== 'object' || Array.isArray(paths)) return { content }\n const pathItem = (paths as Record<string, unknown>)[path]\n if (!pathItem || typeof pathItem !== 'object' || Array.isArray(pathItem)\n || !(match[3].toLowerCase() in pathItem)) return { content }\n const before = content.slice(0, match.index).replace(/(?:^|\\n)##\\s+OpenAPI\\s*\\n\\s*$/i, '\\n')\n const after = content.slice(match.index + match[0].length)\n return {\n content: `${before}${after}`.trim(),\n openapi: `${method} ${path}`,\n fragment: {\n method,\n path,\n document,\n },\n }\n } catch {\n return { content }\n }\n}\n\nfunction markdownPage(document: MigrationFetchResponse, id: string, platform: MigrationPlatform): {\n page: MigrationPage | null\n openApiFragment?: EmbeddedOpenApiFragment\n} {\n const parsed = remoteMarkdownMetadata(document.body)\n let content = stripMintlifyDocumentationIndex(parsed.content).trimStart()\n const titleMatch = content.match(/^#\\s+(.+)\\r?\\n/)\n const title = parsed.title ?? titleMatch?.[1] ?? id.split('/').at(-1) ?? 'Introduction'\n if (titleMatch) content = content.slice(titleMatch[0].length).trimStart()\n let description = parsed.description\n if (!description) {\n const quoteMatch = content.match(/^(>[^\\r\\n]*(?:\\r?\\n>[^\\r\\n]*)*)\\r?\\n/)\n if (quoteMatch) {\n description = plainDescription(quoteMatch[1].replace(/^>\\s?/gm, ''))\n content = content.slice(quoteMatch[0].length).trimStart()\n }\n }\n // Re-emit only scalar metadata we parsed ourselves. The shared YAML parser\n // handles trusted repository sources but never receives attacker-controlled\n // aliases from a public URL.\n const embeddedOpenApi = extractEmbeddedOpenApi(content)\n const raw = [\n '---',\n `title: ${JSON.stringify(title)}`,\n ...(description ? [`description: ${JSON.stringify(description)}`] : []),\n ...(parsed.sidebarTitle ? [`sidebarTitle: ${JSON.stringify(parsed.sidebarTitle)}`] : []),\n ...(parsed.tag ? [`tag: ${JSON.stringify(parsed.tag)}`] : []),\n ...(parsed.mode ? [`mode: ${JSON.stringify(parsed.mode)}`] : []),\n ...(parsed.hidden ? ['hidden: true'] : []),\n ...(parsed.noindex ? ['noindex: true'] : []),\n ...(embeddedOpenApi.openapi ? [`openapi: ${JSON.stringify(embeddedOpenApi.openapi)}`] : []),\n '---',\n '',\n embeddedOpenApi.content,\n ].join('\\n')\n return {\n // The crawler knows the source platform (detected or caller-provided)\n // before it ever parses a page; an omitted platform would otherwise\n // apply every platform's textual renames to content of unknown origin.\n page: parseMarkdownPage({ id, raw, source: document.finalUrl.toString(), platform }),\n openApiFragment: embeddedOpenApi.fragment,\n }\n}\n\nfunction mergeRecord(target: Record<string, unknown>, source: unknown): void {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return\n for (const [key, value] of Object.entries(source)) {\n if (['__proto__', 'constructor', 'prototype'].includes(key)) continue\n if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = value\n continue\n }\n const current = target[key]\n if (current && value && typeof current === 'object' && typeof value === 'object'\n && !Array.isArray(current) && !Array.isArray(value)) {\n mergeRecord(current as Record<string, unknown>, value)\n }\n }\n}\n\nfunction mergeEmbeddedOpenApi(fragments: Array<EmbeddedOpenApiFragment>): Uint8Array | null {\n const first = fragments[0]\n if (!first) return null\n const combined: Record<string, unknown> = {\n ...first.document,\n paths: {},\n components: {},\n }\n const combinedPaths = combined.paths as Record<string, unknown>\n const combinedComponents = combined.components as Record<string, unknown>\n const tags = new Map<string, unknown>()\n for (const fragment of fragments) {\n const sourcePaths = fragment.document.paths as Record<string, unknown>\n const sourcePathItem = sourcePaths?.[fragment.path]\n if (!sourcePathItem || typeof sourcePathItem !== 'object' || Array.isArray(sourcePathItem)) continue\n const sourceOperation = (sourcePathItem as Record<string, unknown>)[fragment.method.toLowerCase()]\n if (!sourceOperation || typeof sourceOperation !== 'object' || Array.isArray(sourceOperation)) continue\n const operation = { ...(sourceOperation as Record<string, unknown>) }\n if (!operation.servers && Array.isArray(fragment.document.servers)) operation.servers = fragment.document.servers\n if (!operation.security && Array.isArray(fragment.document.security)) operation.security = fragment.document.security\n const existingPath = combinedPaths[fragment.path]\n const pathItem = existingPath && typeof existingPath === 'object' && !Array.isArray(existingPath)\n ? existingPath as Record<string, unknown>\n : {}\n for (const sharedKey of ['parameters', 'servers', 'summary', 'description']) {\n const sharedValue = (sourcePathItem as Record<string, unknown>)[sharedKey]\n if (sharedValue !== undefined && pathItem[sharedKey] === undefined) pathItem[sharedKey] = sharedValue\n }\n pathItem[fragment.method.toLowerCase()] = operation\n combinedPaths[fragment.path] = pathItem\n mergeRecord(combinedComponents, fragment.document.components)\n for (const tag of Array.isArray(fragment.document.tags) ? fragment.document.tags : []) {\n if (!tag || typeof tag !== 'object' || Array.isArray(tag)) continue\n const name = (tag as Record<string, unknown>).name\n if (typeof name === 'string' && !tags.has(name)) tags.set(name, tag)\n }\n }\n if (Object.keys(combinedPaths).length === 0) return null\n if (Object.keys(combinedComponents).length === 0) delete combined.components\n if (tags.size > 0) combined.tags = [...tags.values()]\n return new TextEncoder().encode(stringifyYaml(combined))\n}\n\nfunction htmlPage(\n document: MigrationFetchResponse,\n id: string,\n): { page: MigrationPage | null; links: Array<string> } {\n const $ = load(document.body)\n const links = $('nav a[href], main a[href], article a[href], [role=\"main\"] a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter(Boolean)\n const title = $('main h1, article h1, h1').first().text().trim()\n || $('meta[property=\"og:title\"]').attr('content')?.trim()\n || $('title').text().split('|')[0].trim()\n const description = $('meta[name=\"description\"]').attr('content')?.trim()\n || $('meta[property=\"og:description\"]').attr('content')?.trim()\n const content = $('main article, article, main, [role=\"main\"]').first()\n const root = content.length ? content : $('body')\n root.find('script,style,noscript,nav,header,footer,aside,form,button,svg,iframe,object,embed,link,meta').remove()\n root.find('.theme-doc-version-badge,.theme-doc-breadcrumbs,.theme-doc-toc-mobile,.table-of-contents,.hash-link').remove()\n root.find('a[href]').each((_index, element) => {\n const href = $(element).attr('href')\n if (!href) return\n try {\n const resolved = new URL(href, document.finalUrl)\n if (['http:', 'https:', 'mailto:', 'tel:'].includes(resolved.protocol)) {\n $(element).attr('href', resolved.toString())\n } else {\n $(element).removeAttr('href')\n }\n } catch {\n $(element).removeAttr('href')\n }\n })\n root.find('img[src]').each((_index, element) => {\n const src = $(element).attr('src')\n if (!src) return\n try {\n const resolved = new URL(src, document.finalUrl)\n if (['http:', 'https:'].includes(resolved.protocol)) {\n $(element).attr('src', resolved.toString())\n } else {\n $(element).removeAttr('src')\n }\n } catch {\n $(element).removeAttr('src')\n }\n })\n const turndown = new TurndownService({ codeBlockStyle: 'fenced', emDelimiter: '_', headingStyle: 'atx' })\n turndown.remove(['script', 'style', 'noscript'])\n turndown.addRule('docusaurus-admonition', {\n filter: (node) => node.nodeName === 'DIV'\n && (node as HTMLElement).classList.contains('theme-admonition'),\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const className = element.className\n const tag = /admonition-(?:danger)/.test(className)\n ? 'Error'\n : /admonition-(?:caution|warning)/.test(className)\n ? 'Warning'\n : /admonition-info/.test(className)\n ? 'Info'\n : 'Note'\n const fragment = load(element.outerHTML)\n const clone = fragment('.theme-admonition').first()\n const title = clone.find('[class*=\"admonitionHeading\"],.admonition-heading').first()\n const titleText = title.text().trim()\n title.remove()\n const markdown = turndown.turndown(clone.html() ?? '').trim()\n return `\\n\\n<${tag}>\\n${titleText ? `**${titleText}**\\n\\n` : ''}${markdown}\\n</${tag}>\\n\\n`\n },\n })\n turndown.addRule('docusaurus-tabs', {\n filter: (node) => node.nodeName === 'DIV'\n && (node as HTMLElement).classList.contains('tabs-container'),\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const fragment = load(element.outerHTML)\n const container = fragment('.tabs-container').first()\n const labels = container.children('ul.tabs').children('li').toArray()\n .map((item) => fragment(item).text().trim() || 'Tab')\n const panels = container.children('div[role=\"tabpanel\"]').toArray()\n if (panels.length === 0) return _content\n const tabs = panels.map((panel, index) => {\n const title = (labels[index] ?? `Tab ${index + 1}`).replace(/\"/g, '"')\n return `<Tab title=\"${title}\">\\n${turndown.turndown(fragment(panel).html() ?? '').trim()}\\n</Tab>`\n })\n return `\\n\\n<Tabs>\\n${tabs.join('\\n\\n')}\\n</Tabs>\\n\\n`\n },\n })\n turndown.addRule('gfm-table', {\n filter: 'table',\n replacement: (_content, node) => {\n const fragment = load((node as HTMLElement).outerHTML)\n const rows = fragment('tr').toArray().map((row) => (\n fragment(row).children('th,td').toArray().map((cell) => escapeMarkdownText(\n fragment(cell).text().replace(/\\s+/g, ' ').trim(),\n true,\n ))\n )).filter((row) => row.length > 0)\n if (rows.length === 0) return ''\n const width = Math.max(...rows.map((row) => row.length))\n const normalized = rows.map((row) => [...row, ...Array<string>(width - row.length).fill('')])\n return `\\n\\n| ${normalized[0].join(' | ')} |\\n| ${Array<string>(width).fill('---').join(' | ')} |\\n${normalized.slice(1).map((row) => `| ${row.join(' | ')} |`).join('\\n')}\\n\\n`\n },\n })\n turndown.addRule('migration-safe-fenced-code', {\n filter: (node) => node.nodeName === 'PRE',\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const fragment = load(element.outerHTML)\n const tokenLines = fragment('.token-line').toArray()\n const code = (tokenLines.length > 0\n ? tokenLines.map((line) => fragment(line).text()).join('\\n')\n : fragment('pre').text()).replace(/\\n$/, '')\n const language = fragment('code').attr('class')?.match(/(?:language-|lang-)([A-Za-z0-9_+-]+)/)?.[1] ?? ''\n const longestFence = Math.max(0, ...[...code.matchAll(/`+/g)].map((match) => match[0].length))\n const fence = '`'.repeat(Math.max(3, longestFence + 1))\n return `\\n\\n${fence}${language}\\n${code}\\n${fence}\\n\\n`\n },\n })\n const escape = turndown.escape.bind(turndown)\n turndown.escape = (text: string) => escape(text).replace(/[<{]/g, (match) => `\\\\${match}`)\n const body = turndown.turndown(root.html() ?? '').trim()\n // Docusaurus can intentionally publish title-only reference/partial pages.\n // Keep those real article routes while still rejecting empty search/app\n // shells that happen to expose a document title.\n if (!title || (body.length < 40 && $('article').length === 0)) return { page: null, links }\n return {\n page: {\n id,\n navigationId: id,\n title,\n description: description || plainDescription(body) || `Documentation imported from ${document.finalUrl.hostname}.`,\n keywords: [],\n body,\n source: document.finalUrl.toString(),\n },\n links,\n }\n}\n\nfunction htmlNavigationLinks(document: MigrationFetchResponse): Array<string> {\n const $ = load(document.body)\n return $('.nav-tabs a[href], nav a[href], aside a[href], [role=\"navigation\"] a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter(Boolean)\n}\n\ninterface SourceNavigationTab {\n section: string\n label: string\n pageId: string\n}\n\ninterface DocusaurusSidebarItem {\n label: string\n href?: string\n items?: Array<DocusaurusSidebarItem>\n isCategory?: boolean\n}\n\ninterface DocusaurusSidebarSnapshot {\n items: Array<DocusaurusSidebarItem>\n}\n\ninterface DocusaurusDiscovery {\n scopePath: string\n excludedVersionPrefixes: Array<string>\n sidebar: DocusaurusSidebarSnapshot | null\n}\n\nfunction normalizedLinkLabel(value: string): string {\n return value.replace(/\\s+/g, ' ').trim()\n}\n\nfunction readDocusaurusSidebar(document: MigrationFetchResponse): DocusaurusSidebarSnapshot | null {\n if (!/html/i.test(document.contentType)) return null\n const $ = load(document.body)\n const sidebar = $('ul.theme-doc-sidebar-menu').first()\n if (sidebar.length === 0) return null\n\n type CheerioSelector = Exclude<Parameters<ReturnType<typeof load>>[0], undefined>\n function readList(list: CheerioSelector): Array<DocusaurusSidebarItem> {\n return $(list).children('li').toArray().flatMap((item) => {\n const directLink = $(item).children('a.menu__link').first()\n const collapsibleLink = $(item)\n .children('.menu__list-item-collapsible')\n .children('a.menu__link')\n .first()\n const link = directLink.length > 0 ? directLink : collapsibleLink\n const label = normalizedLinkLabel(link.text())\n const href = link.attr('href')\n const nested = $(item).children('ul.menu__list').first()\n const children = nested.length > 0 ? readList(nested.get(0)!) : []\n const isCategory = $(item).hasClass('theme-doc-sidebar-item-category')\n || link.hasClass('menu__link--sublist')\n if (!label && children.length === 0) return []\n return [{\n label: label || 'Documentation',\n ...(href ? { href: new URL(href, document.finalUrl).toString() } : {}),\n ...(children.length > 0 ? { items: children } : {}),\n ...(isCategory ? { isCategory: true } : {}),\n }]\n })\n }\n\n return { items: readList(sidebar.get(0)!) }\n}\n\nfunction docusaurusSidebarHrefs(snapshot: DocusaurusSidebarSnapshot | null): Array<string> {\n const hrefs: Array<string> = []\n const visit = (items: Array<DocusaurusSidebarItem>) => {\n for (const item of items) {\n if (item.href) hrefs.push(item.href)\n if (item.items) visit(item.items)\n }\n }\n if (snapshot) visit(snapshot.items)\n return hrefs\n}\n\nfunction deriveDocusaurusScope(\n source: URL,\n document: MigrationFetchResponse,\n submittedScopePath: string,\n): DocusaurusDiscovery {\n const $ = load(document.body)\n const sidebar = readDocusaurusSidebar(document)\n const internalPaths = docusaurusSidebarHrefs(sidebar).flatMap((href) => {\n try {\n const url = new URL(href)\n return url.origin === source.origin ? [url.pathname.replace(/\\/+$/, '') || '/'] : []\n } catch {\n return []\n }\n })\n const counts = new Map<string, number>()\n for (const path of internalPaths) {\n const segments = path.split('/').filter(Boolean)\n for (let length = 1; length < segments.length; length++) {\n const prefix = `/${segments.slice(0, length).join('/')}`\n counts.set(prefix, (counts.get(prefix) ?? 0) + 1)\n }\n }\n const threshold = Math.max(2, Math.ceil(internalPaths.length * 0.6))\n const scopePath = [...counts]\n .filter(([, count]) => count >= threshold)\n .sort((left, right) => right[0].split('/').length - left[0].split('/').length\n || right[1] - left[1])[0]?.[0]\n ?? submittedScopePath\n\n const excludedVersionPrefixes = $('.dropdown__menu a[href]').toArray().flatMap((element) => {\n const href = $(element).attr('href')\n if (!href) return []\n try {\n const target = new URL(href, document.finalUrl)\n if (target.origin !== source.origin || !isInScope(target, source, scopePath)) return []\n const relativePath = target.pathname.slice(scopePath.length).replace(/^\\/+/, '')\n const version = relativePath.split('/', 1)[0]\n if (!/^(?:legacy|next|v\\d[\\w.-]*)$/i.test(version)) return []\n return [`${scopePath}/${version}`]\n } catch {\n return []\n }\n })\n\n return {\n scopePath,\n excludedVersionPrefixes: [...new Set(excludedVersionPrefixes)],\n sidebar,\n }\n}\n\nfunction docusaurusRouteIdForUrl(url: URL, scopePath: string): string | null {\n let path = url.pathname.replace(/\\/+$/, '')\n if (scopePath === '/') path = path.replace(/^\\/+/, '')\n else if (path === scopePath) path = ''\n else if (path.startsWith(`${scopePath}/`)) path = path.slice(scopePath.length + 1)\n else return null\n const segments = path.split('/').filter(Boolean).map((segment) => {\n let decoded = segment\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n // Preserve malformed source segments as literal route input.\n }\n return decoded\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/(^-|-$)/g, '')\n }).filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\nfunction storageIdForDocusaurusRoute(routeId: string): string {\n return /(?:^|\\/)(?:index|readme)$/i.test(routeId) ? `${routeId}/index` : routeId\n}\n\nfunction docusaurusNavigationFromSnapshots(\n snapshots: Array<DocusaurusSidebarSnapshot>,\n pages: Array<MigrationPage>,\n scopePath: string,\n): ReturnType<typeof buildNavigationFromPages> {\n const imported = new Set(pages.map((page) => page.navigationId))\n const claimed = new Set<string>()\n const uniqueSnapshots = [...new Map(snapshots.map((snapshot) => [\n JSON.stringify(snapshot.items),\n snapshot,\n ])).values()]\n const mergedSnapshots: Array<DocusaurusSidebarSnapshot> = []\n function mergeItems(\n target: Array<DocusaurusSidebarItem>,\n incoming: Array<DocusaurusSidebarItem>,\n ): void {\n for (const item of incoming) {\n const existing = target.find((candidate) => candidate.label === item.label\n && (candidate.items || item.items))\n ?? target.find((candidate) => candidate.label === item.label && candidate.href === item.href)\n if (!existing) {\n target.push(structuredClone(item))\n continue\n }\n if (!existing.href && item.href) existing.href = item.href\n if (item.items) {\n existing.items ??= []\n mergeItems(existing.items, item.items)\n }\n }\n }\n for (const snapshot of uniqueSnapshots) {\n const incomingLabels = new Set(snapshot.items.map((item) => item.label))\n const cluster = mergedSnapshots.find((candidate) => {\n const candidateLabels = new Set(candidate.items.map((item) => item.label))\n const overlap = [...incomingLabels].filter((label) => candidateLabels.has(label)).length\n return overlap >= Math.max(2, Math.ceil(Math.min(incomingLabels.size, candidateLabels.size) * 0.5))\n })\n if (cluster) mergeItems(cluster.items, snapshot.items)\n else mergedSnapshots.push(structuredClone(snapshot))\n }\n const pageIdsFor = (snapshot: DocusaurusSidebarSnapshot): Array<string> => docusaurusSidebarHrefs(snapshot)\n .flatMap((href) => {\n const id = docusaurusRouteIdForUrl(new URL(href), scopePath)\n return id && imported.has(id) ? [id] : []\n })\n mergedSnapshots.sort((left, right) => pageIdsFor(right).length - pageIdsFor(left).length)\n\n const tabs = mergedSnapshots.flatMap((snapshot, snapshotIndex) => {\n function convert(items: Array<DocusaurusSidebarItem>): Array<string | MigrationNavigationGroup> {\n const converted: Array<string | MigrationNavigationGroup> = []\n for (const item of items) {\n const routeId = item.href\n ? docusaurusRouteIdForUrl(new URL(item.href), scopePath)\n : null\n const page = routeId && imported.has(routeId) && !claimed.has(routeId) ? routeId : null\n if (page) claimed.add(page)\n const children = item.items ? convert(item.items) : []\n if (children.length > 0 || item.isCategory) {\n converted.push({ group: item.label, pages: page ? [page, ...children] : children })\n continue\n }\n if (page) converted.push(page)\n }\n return converted\n }\n const converted = convert(snapshot.items)\n const loosePages = converted.filter((item): item is string => typeof item === 'string')\n const groups = converted.filter((item): item is Exclude<typeof item, string> => typeof item !== 'string')\n if (loosePages.length > 0) groups.unshift({ group: 'Overview', pages: loosePages })\n if (groups.length === 0) return []\n const snapshotPageIds = pageIdsFor(snapshot)\n const firstSegments = new Set(snapshotPageIds.map((id) => id.split('/', 1)[0]))\n const tab = snapshotIndex > 0 && firstSegments.size === 1\n ? normalizedLinkLabel([...firstSegments][0].replace(/[-_]/g, ' ')).replace(/\\b\\w/g, (letter) => letter.toUpperCase())\n : 'Documentation'\n return [{ tab, groups }]\n })\n\n const additional = pages\n .map((page) => page.navigationId)\n .filter((id) => !claimed.has(id))\n if (additional.length > 0) {\n if (tabs.length === 0) return buildNavigationFromPages(pages)\n tabs[0].groups?.push({ group: 'Additional', pages: additional })\n }\n return { tabs }\n}\n\nfunction htmlTopLevelNavigation(\n document: MigrationFetchResponse,\n source: URL,\n scopePath: string,\n): Array<SourceNavigationTab> {\n const $ = load(document.body)\n interface NavigationCandidate {\n entries: Array<SourceNavigationTab>\n anchorCount: number\n }\n const collectCandidates = (selector: string): Array<NavigationCandidate> => {\n const candidates: Array<NavigationCandidate> = []\n $(selector).each((_containerIndex, container) => {\n const entries: Array<SourceNavigationTab> = []\n const seenSections = new Set<string>()\n let anchorCount = 0\n $(container).find('a[href]').each((_index, element) => {\n const label = $(element).text().replace(/\\s+/g, ' ').trim()\n const href = $(element).attr('href')\n if (!label || !href) return\n try {\n const target = new URL(href, document.finalUrl)\n if (!isInScope(target, source, scopePath)) return\n anchorCount += 1\n const targetId = canonicalLocalizedPageId(pageIdForUrl(target, scopePath) ?? '')\n const pageId = targetId\n const section = targetId.split('/', 1)[0] || 'introduction'\n if (!pageId || seenSections.has(section)) return\n seenSections.add(section)\n entries.push({ section, label, pageId })\n } catch {\n // Ignore malformed navigation targets; discovery applies the same rule.\n }\n })\n if (entries.length > 1) {\n candidates.push({ entries, anchorCount })\n }\n })\n return candidates\n }\n // Mintlify marks its product-tab strip consistently. Prefer that explicit\n // platform signal; generic nav elements usually describe only the sidebar.\n const tabCandidates = collectCandidates('.nav-tabs')\n const candidates = tabCandidates.length > 0\n ? tabCandidates\n : collectCandidates('nav, [role=\"navigation\"]')\n const entries = candidates.sort((left, right) => {\n const densityDifference = (right.entries.length / right.anchorCount)\n - (left.entries.length / left.anchorCount)\n return densityDifference || right.entries.length - left.entries.length\n })[0]?.entries ?? []\n // A product switcher with dozens of entries is invariably a sidebar or\n // responsive page strip, not authored top-level navigation. Refuse to turn\n // that ambiguity into an unusable header.\n const normalizedLabels = entries.map((entry) => entry.label.trim().toLowerCase())\n if (entries.length > 12 || new Set(normalizedLabels).size !== normalizedLabels.length) return []\n return entries\n}\n\nfunction remapNavigationHome(\n config: MigrationBundle['docsConfig'],\n sourceHomePageId: string | undefined,\n): MigrationBundle['docsConfig'] {\n if (!sourceHomePageId || sourceHomePageId === 'introduction') return config\n const remapPages = (\n pages: Array<string | MigrationNavigationGroup>,\n ): Array<string | MigrationNavigationGroup> => pages.map((page) => typeof page === 'string'\n ? page === sourceHomePageId ? 'introduction' : page\n : { ...page, pages: remapPages(page.pages) })\n const remapGroups = (groups: Array<MigrationNavigationGroup>): Array<MigrationNavigationGroup> => groups.map((group) => ({\n ...group,\n pages: remapPages(group.pages),\n }))\n return {\n ...config,\n tabs: config.tabs.map((tab) => ({\n ...tab,\n ...(tab.href === `/${sourceHomePageId}` ? { href: '/' } : {}),\n ...(tab.pages ? { pages: remapPages(tab.pages) } : {}),\n ...(tab.groups ? { groups: remapGroups(tab.groups) } : {}),\n })),\n }\n}\n\nfunction markdownLinks(body: string): Array<string> {\n return [...body.matchAll(/\\[[^\\]]+\\]\\(([^)\\s]+)(?:\\s+['\"][^'\"]*['\"])?\\)/g)]\n .map((match) => match[1])\n}\n\nfunction sitemapLinks(body: string): Array<string> {\n const $ = load(body, { xmlMode: true })\n return $('url > loc, sitemap > loc').map((_index, element) => $(element).text().trim()).get().filter(Boolean)\n}\n\nfunction robotsSitemaps(body: string): Array<string> {\n return body.split('\\n')\n .map((line) => line.match(/^\\s*Sitemap:\\s*(\\S+)/i)?.[1])\n .filter((value): value is string => Boolean(value))\n}\n\nfunction headerLinks(document: MigrationFetchResponse): Array<string> {\n const links: Array<string> = []\n const llms = document.headers?.['x-llms-txt']\n if (llms) links.push(llms)\n const linkHeader = document.headers?.link ?? ''\n for (const match of linkHeader.matchAll(/<([^>]+)>\\s*;[^,]*(?:rel=[\"']?(?:alternate|llms-txt)[\"']?|type=[\"']text\\/(?:markdown|plain)[\"'])/gi)) {\n links.push(match[1])\n }\n return links\n}\n\nasync function safeFetch(\n fetcher: MigrationFetcher,\n url: URL,\n accept: string,\n): Promise<MigrationFetchResponse | null> {\n try {\n return await fetcher(url, { accept })\n } catch {\n return null\n }\n}\n\n/** Crawl one public docs origin into a canonical, caller-independent bundle. */\nexport async function migrateUrl(options: UrlMigrationOptions): Promise<MigrationBundle> {\n const source = validateMigrationUrl(options.sourceUrl)\n const fetcher = options.fetcher ?? defaultMigrationFetcher\n const maxPages = Math.max(1, Math.min(options.maxPages ?? DEFAULT_MAX_PAGES, 1_000))\n const concurrency = Math.max(1, Math.min(options.concurrency ?? 5, 10))\n const maxTotalBytes = Math.max(1_000_000, Math.min(options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES, 500_000_000))\n const submittedScopePath = docsScopePath(source)\n const initial = await fetcher(source, { accept: 'text/markdown,text/html,application/xhtml+xml;q=0.9' })\n if (!isInScope(initial.finalUrl, source, submittedScopePath)) {\n throw new Error('The documentation URL redirected outside the submitted docs origin or path.')\n }\n const htmlProbe = /html/i.test(initial.contentType)\n ? initial\n : await safeFetch(fetcher, source, 'text/html,application/xhtml+xml')\n // Content negotiation must not let an HTML-only redirect escape the path\n // boundary already validated for the submitted documentation response.\n const scopedHtmlProbe = htmlProbe && isInScope(htmlProbe.finalUrl, source, submittedScopePath)\n ? htmlProbe\n : null\n const platform = options.platform ?? detectUrlPlatform(scopedHtmlProbe ?? initial)\n let docusaurusHtmlProbe = platform === 'docusaurus' ? scopedHtmlProbe : null\n if (docusaurusHtmlProbe && !readDocusaurusSidebar(docusaurusHtmlProbe)) {\n const $ = load(docusaurusHtmlProbe.body)\n const docsHref = $('nav a[href]').toArray().map((element) => ({\n href: $(element).attr('href'),\n label: normalizedLinkLabel($(element).text()),\n })).find((link) => /^docs(?:umentation)?$/i.test(link.label))?.href\n if (docsHref) {\n try {\n const docsUrl = new URL(docsHref, docusaurusHtmlProbe.finalUrl)\n if (docsUrl.origin === source.origin && isInScope(docsUrl, source, submittedScopePath)) {\n const probe = await safeFetch(fetcher, docsUrl, 'text/html,application/xhtml+xml')\n if (probe && probe.finalUrl.origin === source.origin && /html/i.test(probe.contentType)) {\n docusaurusHtmlProbe = probe\n }\n }\n } catch {\n // A malformed navbar link falls back to the submitted path boundary.\n }\n }\n }\n const docusaurusDiscovery = platform === 'docusaurus' && docusaurusHtmlProbe\n ? deriveDocusaurusScope(source, docusaurusHtmlProbe, submittedScopePath)\n : null\n // A Mintlify site may own an entire docs origin or a path below a marketing\n // site. Its llms/sitemap location is the authoritative crawl boundary.\n const scopePath = platform === 'mintlify'\n ? machineIndexScopePath(source, [initial, scopedHtmlProbe]) ?? submittedScopePath\n : docusaurusDiscovery?.scopePath ?? submittedScopePath\n const sourceMintlifyConfig = platform === 'mintlify' && scopedHtmlProbe && /html/i.test(scopedHtmlProbe.contentType)\n ? embeddedMintlifyConfig(scopedHtmlProbe.body)\n : null\n const sourceMintlifyProjection = sourceMintlifyConfig\n ? projectMintlifyNavigation(sourceMintlifyConfig, { pathPrefix: scopePath })\n : null\n const hasStructuredMintlifyNavigation = Boolean(\n sourceMintlifyProjection?.docsConfig.tabs.length\n && sourceMintlifyProjection.pageReferences.length,\n )\n const sourceTopLevelNavigation = platform === 'mintlify' && !hasStructuredMintlifyNavigation\n && scopedHtmlProbe && /html/i.test(scopedHtmlProbe.contentType)\n ? htmlTopLevelNavigation(scopedHtmlProbe, source, scopePath)\n : undefined\n // The submitted URL can be any page. Mintlify's first authored product tab,\n // rather than the submitted page, defines which source page becomes `/`.\n // Older single-section themes do not expose a tab strip, so they retain the\n // legacy dedicated-origin fallback when no authored home can be recovered.\n const sourceHomePageId = sourceMintlifyProjection?.pageReferences[0]?.navigationId\n ?? sourceTopLevelNavigation?.[0]?.pageId\n ?? (platform === 'mintlify' && scopePath === '/'\n ? canonicalLocalizedPageId(pageIdForUrl(source, scopePath) ?? '') || undefined\n : undefined)\n const cache = new Map([[source.toString(), initial]])\n if (docusaurusHtmlProbe) cache.set(docusaurusHtmlProbe.finalUrl.toString(), docusaurusHtmlProbe)\n const queue: Array<URL> = [source]\n const queued = new Set([candidateIdentity(source)])\n const warnings: Array<MigrationWarning> = []\n const fetchedSitemaps = new Set<string>()\n const docusaurusSidebars: Array<DocusaurusSidebarSnapshot> = docusaurusDiscovery?.sidebar\n ? [docusaurusDiscovery.sidebar]\n : []\n const docusaurusRedirects: Array<{ source: string; destination: string }> = []\n\n function enqueue(value: string, base: URL): void {\n if (queued.size >= MAX_DISCOVERED_URLS) return\n const url = normalizeCandidate(value, base, source, scopePath)\n if (!url || queued.has(candidateIdentity(url))) return\n if (platform === 'docusaurus' && url.pathname.replace(/\\/+$/, '') === `${scopePath}/search`) return\n if (docusaurusDiscovery?.excludedVersionPrefixes.some((prefix) => {\n const path = url.pathname.replace(/\\/+$/, '')\n return path === prefix || path.startsWith(`${prefix}/`)\n })) return\n queued.add(candidateIdentity(url))\n queue.push(url)\n }\n\n for (const reference of sourceMintlifyProjection?.pageReferences ?? []) {\n let href = reference.ref\n if (scopePath !== '/' && href.startsWith('/')\n && href !== scopePath && !href.startsWith(`${scopePath}/`)) {\n href = `${scopePath}${href}`\n }\n enqueue(href, source)\n }\n\n // Mintlify renders the authored navigation into the HTML shell. Seed the\n // queue from that order before machine indexes add completeness fallbacks.\n const navigationProbe = docusaurusHtmlProbe ?? scopedHtmlProbe\n if (navigationProbe && /html/i.test(navigationProbe.contentType)) {\n for (const link of htmlNavigationLinks(navigationProbe)) enqueue(link, navigationProbe.finalUrl)\n }\n\n async function discoverDocumentLinks(document: MigrationFetchResponse, depth = 0): Promise<void> {\n const links = sitemapLinks(document.body)\n for (const link of links) {\n let url: URL\n try {\n url = new URL(link, document.finalUrl)\n } catch {\n continue\n }\n if (depth < 2 && /\\.xml(?:$|\\?)/i.test(url.pathname)) {\n if (url.origin !== source.origin || fetchedSitemaps.size >= MAX_SITEMAP_DOCUMENTS\n || fetchedSitemaps.has(url.toString())) continue\n fetchedSitemaps.add(url.toString())\n const nested = await safeFetch(fetcher, url, 'application/xml,text/xml')\n if (nested && nested.finalUrl.origin === source.origin) await discoverDocumentLinks(nested, depth + 1)\n } else {\n enqueue(link, document.finalUrl)\n }\n }\n }\n\n for (const link of headerLinks(initial)) {\n let url: URL\n try {\n url = new URL(link, initial.finalUrl)\n } catch {\n continue\n }\n if (url.origin !== source.origin) continue\n const document = await safeFetch(fetcher, url, 'text/plain,text/markdown')\n if (!document || document.finalUrl.origin !== source.origin) continue\n for (const candidate of markdownLinks(document.body)) enqueue(candidate, document.finalUrl)\n }\n\n const pathRoot = scopePath === '/' ? source.origin : `${source.origin}${scopePath}`\n const discoveryUrls = [\n new URL('/llms.txt', source.origin),\n new URL(`${pathRoot.replace(source.origin, '')}/llms.txt`, source.origin),\n new URL('/robots.txt', source.origin),\n new URL('/sitemap.xml', source.origin),\n new URL(`${pathRoot.replace(source.origin, '')}/sitemap.xml`, source.origin),\n ]\n const uniqueDiscovery = [...new Map(discoveryUrls.map((url) => [url.toString(), url])).values()]\n for (const url of uniqueDiscovery) {\n const document = await safeFetch(fetcher, url, 'text/plain,application/xml,text/xml;q=0.9')\n if (!document || document.finalUrl.origin !== source.origin) continue\n const isRobots = url.pathname.endsWith('robots.txt')\n const isSitemap = url.pathname.endsWith('sitemap.xml') || document.contentType.includes('xml')\n if (isRobots) {\n for (const link of robotsSitemaps(document.body)) {\n let sitemapUrl: URL\n try {\n sitemapUrl = new URL(link, document.finalUrl)\n } catch {\n continue\n }\n if (sitemapUrl.origin !== source.origin || fetchedSitemaps.size >= MAX_SITEMAP_DOCUMENTS\n || fetchedSitemaps.has(sitemapUrl.toString())) continue\n fetchedSitemaps.add(sitemapUrl.toString())\n const sitemap = await safeFetch(fetcher, sitemapUrl, 'application/xml,text/xml')\n if (sitemap && sitemap.finalUrl.origin === source.origin) await discoverDocumentLinks(sitemap)\n }\n } else if (isSitemap) {\n await discoverDocumentLinks(document)\n } else {\n for (const link of markdownLinks(document.body)) enqueue(link, document.finalUrl)\n }\n }\n\n const pages: Array<MigrationPage> = []\n const openApiFragments: Array<EmbeddedOpenApiFragment> = []\n const seenIds = new Set<string>()\n const seenSources = new Set<string>()\n const visited = new Set<string>()\n let importedBytes = 0\n let isByteBudgetExhausted = false\n while (queue.length > 0 && pages.length < maxPages && !isByteBudgetExhausted) {\n const batch: Array<URL> = []\n while (queue.length > 0 && batch.length < Math.min(concurrency, maxPages - pages.length)) {\n const candidate = queue.shift()\n if (!candidate || visited.has(candidate.toString())) continue\n visited.add(candidate.toString())\n batch.push(candidate)\n }\n if (batch.length === 0) continue\n const results = await Promise.all(batch.map(async (candidate) => {\n let document = cache.get(candidate.toString())\n ?? await safeFetch(fetcher, candidate, 'text/markdown,text/html,application/xhtml+xml;q=0.9')\n if (!document) {\n return { candidate, page: null, links: [] as Array<string>, failure: true }\n }\n if (!isInScope(document.finalUrl, source, scopePath)) {\n return { candidate, page: null, links: [] as Array<string>, failure: false }\n }\n const isMarkdown = /(?:markdown|text\\/plain)/i.test(document.contentType)\n || /\\.mdx?$/i.test(document.finalUrl.pathname)\n if (!isMarkdown && !/\\.mdx?$/i.test(candidate.pathname)) {\n const markdownUrl = new URL(candidate)\n markdownUrl.pathname = `${markdownUrl.pathname.replace(/\\/$/, '')}.md`\n const markdownDocument = await safeFetch(fetcher, markdownUrl, 'text/markdown,text/plain')\n if (markdownDocument && isInScope(markdownDocument.finalUrl, source, scopePath)\n && /(?:markdown|text\\/plain)/i.test(markdownDocument.contentType)) {\n document = markdownDocument\n }\n }\n const isResolvedMarkdown = /(?:markdown|text\\/plain)/i.test(document.contentType)\n || /\\.mdx?$/i.test(document.finalUrl.pathname)\n const sanitizedMarkdown = isResolvedMarkdown ? sanitizeRemoteMarkdown(document.body) : null\n if (isResolvedMarkdown && sanitizedMarkdown === null) {\n const htmlUrl = new URL(candidate)\n htmlUrl.pathname = htmlUrl.pathname.replace(/\\.mdx?$/i, '') || '/'\n const htmlDocument = await safeFetch(fetcher, htmlUrl, 'text/html,application/xhtml+xml')\n if (htmlDocument && isInScope(htmlDocument.finalUrl, source, scopePath)\n && /html/i.test(htmlDocument.contentType)) {\n document = htmlDocument\n } else {\n // Never recover by compiling the rejected MDX. A source that does\n // not expose a safe rendered representation is skipped instead.\n return { candidate, page: null, links: [] as Array<string>, failure: false }\n }\n } else if (sanitizedMarkdown !== null) {\n document = { ...document, body: sanitizedMarkdown }\n }\n const responseBytes = Buffer.byteLength(document.body, 'utf8')\n if (importedBytes + responseBytes > maxTotalBytes) {\n isByteBudgetExhausted = true\n return { candidate, page: null, links: [] as Array<string>, failure: false, budgetExceeded: true }\n }\n importedBytes += responseBytes\n const discoveredNavigationId = platform === 'docusaurus'\n ? docusaurusRouteIdForUrl(document.finalUrl, scopePath)\n ?? docusaurusRouteIdForUrl(candidate, scopePath)\n : pageIdForUrl(document.finalUrl, scopePath)\n ?? pageIdForUrl(candidate, scopePath)\n const navigationId = discoveredNavigationId\n && canonicalLocalizedPageId(discoveredNavigationId) === sourceHomePageId\n ? 'introduction'\n : discoveredNavigationId\n if (!navigationId) return { candidate, page: null, links: [] as Array<string>, failure: false }\n const id = platform === 'docusaurus'\n ? storageIdForDocusaurusRoute(navigationId)\n : navigationId\n if (/(?:markdown|text\\/plain)/i.test(document.contentType) || /\\.mdx?$/i.test(document.finalUrl.pathname)) {\n const markdown = markdownPage(document, id, platform)\n if (markdown.page) markdown.page.navigationId = navigationId\n return {\n candidate,\n page: markdown.page,\n openApiFragment: markdown.openApiFragment,\n links: markdownLinks(document.body),\n base: document.finalUrl,\n failure: false,\n }\n }\n const extracted = htmlPage(document, id)\n if (extracted.page) extracted.page.navigationId = navigationId\n const sidebar = platform === 'docusaurus' ? readDocusaurusSidebar(document) : null\n return { candidate, page: extracted.page, links: extracted.links, base: document.finalUrl, sidebar, failure: false }\n }))\n for (const result of results) {\n if (result.failure) {\n warnings.push({ code: 'fetch-failed', message: 'A discovered documentation page could not be fetched.', source: result.candidate.toString() })\n continue\n }\n if (result.budgetExceeded) continue\n if (result.page && platform !== 'docusaurus') {\n result.page.id = canonicalLocalizedPageId(result.page.id)\n result.page.navigationId = canonicalLocalizedPageId(result.page.navigationId)\n }\n const sourceIdentity = result.page\n ? candidateIdentity(new URL(result.page.source))\n : null\n if (result.page && sourceIdentity && !seenSources.has(sourceIdentity)\n && !seenIds.has(result.page.id) && pages.length < maxPages) {\n pages.push(result.page)\n if ('openApiFragment' in result && result.openApiFragment) {\n openApiFragments.push(result.openApiFragment)\n }\n seenIds.add(result.page.id)\n seenSources.add(sourceIdentity)\n }\n if (platform === 'docusaurus' && result.page) {\n const candidateRoute = docusaurusRouteIdForUrl(result.candidate, scopePath)\n if (candidateRoute && candidateRoute !== result.page.navigationId) {\n docusaurusRedirects.push({\n source: candidateRoute === 'introduction' ? '/' : `/${candidateRoute}`,\n destination: result.page.navigationId === 'introduction' ? '/' : `/${result.page.navigationId}`,\n })\n }\n }\n if ('sidebar' in result && result.sidebar) docusaurusSidebars.push(result.sidebar)\n for (const link of result.links) enqueue(link, result.base ?? result.candidate)\n }\n }\n\n if (pages.length === 0) throw new Error('No readable documentation pages were found at that URL.')\n for (const page of pages) {\n const [locale, ...navigationSegments] = page.id.split('/')\n if (LOCALE_CODES.has(locale)) {\n if (navigationSegments.length === 0) page.id = `${locale}/introduction`\n page.locale = locale\n page.navigationId = navigationSegments.join('/') || 'introduction'\n }\n }\n const importedIds = new Set(pages.map((page) => page.navigationId))\n for (const page of pages) {\n page.body = rewriteInternalLinks(\n page.body,\n new URL(page.source),\n source,\n scopePath,\n importedIds,\n sourceHomePageId,\n )\n }\n if (isByteBudgetExhausted) {\n warnings.push({ code: 'limit-reached', message: `Import stopped after reaching the ${Math.round(maxTotalBytes / 1_000_000)} MB content budget.` })\n } else if (queue.length > 0 || queued.size >= MAX_DISCOVERED_URLS) {\n warnings.push({ code: 'limit-reached', message: `Import stopped after ${pages.length} pages; narrow the URL or raise the caller limit to import more.` })\n }\n const topLevelNavigation = sourceTopLevelNavigation?.map((entry) => ({\n ...entry,\n pageId: entry.pageId === sourceHomePageId ? 'introduction' : entry.pageId,\n }))\n let docsConfig = platform === 'docusaurus'\n ? docusaurusNavigationFromSnapshots(docusaurusSidebars, pages, scopePath)\n : hasStructuredMintlifyNavigation && sourceMintlifyProjection\n ? remapNavigationHome(sourceMintlifyProjection.docsConfig, sourceHomePageId)\n : buildNavigationFromPages(pages, {\n topLevelTabs: platform === 'mintlify',\n topLevelNavigation,\n })\n if (sourceMintlifyProjection) warnings.push(...sourceMintlifyProjection.warnings)\n if (docusaurusRedirects.length > 0) {\n docsConfig.redirects = [...new Map(docusaurusRedirects.map((redirect) => [\n `${redirect.source}:${redirect.destination}`,\n redirect,\n ])).values()]\n }\n const openApiAsset = mergeEmbeddedOpenApi(openApiFragments)\n if (openApiAsset) {\n const operationPageIds = new Set(pages.filter((page) => page.openapi).map((page) => page.navigationId))\n const containsOperation = (\n navigationPages: Array<string | MigrationNavigationGroup> = [],\n ): boolean => navigationPages.some((page) => typeof page === 'string'\n ? operationPageIds.has(page)\n : containsOperation(page.pages))\n const apiTab = docsConfig.tabs.find((tab) => (\n containsOperation(tab.pages) || containsOperation(tab.groups)\n )) ?? docsConfig.tabs[0]\n if (apiTab) {\n // Migrated operation pages preserve the source URLs and sidebar order.\n // The spec is still configured for operation rendering, but its derived\n // `/api/*` navigation would duplicate every imported endpoint.\n apiTab.api = { source: '/openapi.yaml', navigation: false }\n }\n }\n const locales = [...new Set(pages.map((page) => page.locale).filter((value): value is string => Boolean(value)))]\n if (locales.length > 0) {\n docsConfig.i18n = {\n defaultLocale: 'en',\n locales: [\n { code: 'en', label: 'English' },\n ...locales.filter((locale) => locale !== 'en').map((locale) => ({ code: locale, label: locale.toUpperCase() })),\n ],\n }\n }\n if (platform === 'mintlify') docsConfig = addMintlifyDirectoryRedirects(docsConfig, pages)\n return {\n sourceUrl: source.toString(),\n sourceKind: 'url',\n platform,\n pages,\n assets: openApiAsset ? [{ path: 'openapi.yaml', content: openApiAsset }] : [],\n docsConfig,\n ...(sourceMintlifyConfig ? {\n site: {\n ...(typeof sourceMintlifyConfig.name === 'string' ? { name: sourceMintlifyConfig.name } : {}),\n ...(typeof sourceMintlifyConfig.description === 'string' ? { description: sourceMintlifyConfig.description } : {}),\n },\n } : {}),\n warnings,\n stats: {\n discovered: visited.size,\n imported: pages.length,\n skipped: Math.max(0, visited.size - pages.length),\n },\n }\n}\n","/**\n * Resolve repository-authored remote OpenAPI references before materializing a\n * site. The local downloader pins a publicly resolved address for each HTTPS\n * hop; hosted callers may inject their own DNS-pinned fetch boundary.\n */\nimport { createHash } from 'node:crypto'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { isIP } from 'node:net'\n\nimport { parse as parseYaml } from 'yaml'\n\nimport type { MigrationBundle, MigrationFetcher } from './types.js'\n\nconst MAX_SPEC_BYTES = 25_000_000\nconst MAX_REDIRECTS = 3\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n const parts = address.split('.').map(Number)\n if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false\n const [a, b] = parts\n return !(a === 0 || a === 10 || a === 127 || a >= 224\n || (a === 100 && b >= 64 && b <= 127)\n || (a === 169 && b === 254)\n || (a === 172 && b >= 16 && b <= 31)\n || (a === 192 && (b === 0 || b === 168))\n || (a === 198 && (b === 18 || b === 19))\n || (a === 203 && b === 0)\n || (a === 198 && b === 51))\n }\n // Global unicast only. This excludes loopback, link-local, unique-local,\n // mapped IPv4, multicast, and every host-local address family.\n return family === 6 && /^[23][0-9a-f]{0,3}:/i.test(address)\n && !/^2001:db8:/i.test(address)\n}\n\nfunction validatedSpecUrl(value: string): URL {\n const url = new URL(value)\n if (url.protocol !== 'https:' || url.username || url.password || isIP(url.hostname)) {\n throw new Error('Remote OpenAPI references must use an HTTPS domain without credentials or an IP literal.')\n }\n url.hash = ''\n return url\n}\n\nasync function getPinnedAddress(url: URL): Promise<{ address: string; family: 4 | 6 }> {\n const addresses = await lookup(url.hostname, { all: true })\n if (addresses.length === 0 || addresses.some((candidate) => !isPublicAddress(candidate.address, candidate.family))) {\n throw new Error('The OpenAPI host did not resolve exclusively to public addresses.')\n }\n return addresses[0] as { address: string; family: 4 | 6 }\n}\n\ninterface SpecResponse {\n status: number\n location?: string\n body: Buffer\n}\n\nasync function requestPinnedSpec(url: URL): Promise<SpecResponse> {\n const pinned = await getPinnedAddress(url)\n return new Promise((resolve, reject) => {\n const req = request(url, {\n headers: { Accept: 'application/json, application/yaml, text/yaml, */*', 'User-Agent': 'Thally-Migrate/1.0 (+https://thally.io)' },\n signal: AbortSignal.timeout(30_000),\n // Node's dual-stack connector asks lookup for `all: true`; that\n // callback must receive address records, not a single address string.\n lookup: (_hostname, options, callback) => {\n if (typeof options === 'object' && options.all) callback(null, [pinned])\n else callback(null, pinned.address, pinned.family)\n },\n }, (response) => {\n const status = response.statusCode ?? 0\n if (status >= 300 && status < 400) {\n response.resume()\n resolve({ status, location: response.headers.location, body: Buffer.alloc(0) })\n return\n }\n if (status < 200 || status >= 300) {\n response.resume()\n reject(new Error(`OpenAPI server returned ${status}.`))\n return\n }\n const statedBytes = Number(response.headers['content-length'] ?? 0)\n if (statedBytes > MAX_SPEC_BYTES) {\n response.destroy()\n reject(new Error('Remote OpenAPI spec exceeds the 25 MB import limit.'))\n return\n }\n const chunks: Array<Buffer> = []\n let bytes = 0\n response.on('data', (chunk: Buffer) => {\n bytes += chunk.length\n if (bytes > MAX_SPEC_BYTES) {\n response.destroy(new Error('Remote OpenAPI spec exceeds the 25 MB import limit.'))\n return\n }\n chunks.push(chunk)\n })\n response.on('end', () => resolve({ status, body: Buffer.concat(chunks) }))\n response.on('error', reject)\n })\n req.on('error', reject)\n req.end()\n })\n}\n\nasync function downloadSpec(value: string, fetcher?: MigrationFetcher): Promise<Buffer> {\n let url = validatedSpecUrl(value)\n if (fetcher) {\n const response = await fetcher(url, { accept: 'application/json, application/yaml, text/yaml' })\n validatedSpecUrl(response.finalUrl.toString())\n const body = Buffer.from(response.body)\n if (body.length > MAX_SPEC_BYTES) throw new Error('Remote OpenAPI spec exceeds the 25 MB import limit.')\n return body\n }\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n const response = await requestPinnedSpec(url)\n if (response.status >= 300 && response.status < 400) {\n if (!response.location || hop === MAX_REDIRECTS) throw new Error('Remote OpenAPI spec redirected too many times.')\n url = validatedSpecUrl(new URL(response.location, url).toString())\n continue\n }\n return response.body\n }\n throw new Error('Remote OpenAPI spec redirected too many times.')\n}\n\ninterface OpenApiOperation {\n method: string\n path: string\n tag: string\n summary: string\n}\n\nfunction parseOpenApi(content: Buffer, extension: string): Array<OpenApiOperation> {\n const text = content.toString('utf8')\n // A remote endpoint may serve YAML from a path without a .yaml suffix.\n const parsed = extension === 'yaml' || !text.trimStart().startsWith('{')\n ? parseYaml(text) as unknown\n : JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('OpenAPI spec is not an object.')\n const document = parsed as Record<string, unknown>\n if (typeof document.openapi !== 'string' || !/^3\\./.test(document.openapi)) {\n throw new Error('Remote specification is not OpenAPI 3.x.')\n }\n if (!document.paths || typeof document.paths !== 'object' || Array.isArray(document.paths)) {\n throw new Error('Remote OpenAPI spec has no paths object.')\n }\n const paths = Object.entries(document.paths as Record<string, unknown>)\n if (paths.length > 5_000) throw new Error('Remote OpenAPI spec has too many paths to import.')\n const operations: Array<OpenApiOperation> = []\n for (const [path, value] of paths) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) continue\n for (const [method, raw] of Object.entries(value as Record<string, unknown>)) {\n if (!/^(get|post|put|patch|delete|head|options|trace)$/i.test(method)\n || !raw || typeof raw !== 'object' || Array.isArray(raw)) continue\n const operation = raw as Record<string, unknown>\n const tags = Array.isArray(operation.tags) ? operation.tags : []\n operations.push({\n method: method.toLowerCase(),\n path,\n tag: typeof tags[0] === 'string' ? tags[0] : 'API Reference',\n summary: typeof operation.summary === 'string' ? operation.summary : String(operation.operationId ?? ''),\n })\n }\n }\n return operations\n}\n\nfunction slug(value: string): string {\n return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n}\n\nfunction operationTarget(operation: OpenApiOperation): string {\n const path = operation.path.split('/').filter(Boolean)\n .map((part) => part.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9-]/g, '-').replace(/-+/g, '-').toLowerCase())\n return `/api/default/${[...path, operation.method].join('/')}`\n}\n\n/**\n * Attach safely downloaded specs to the exact authored API tabs. Source links\n * to Mintlify's tag/summary routes receive redirects only when an operation\n * can be identified uniquely; guessing would silently route to wrong APIs.\n */\nexport async function hydrateRemoteApiSpecs(bundle: MigrationBundle, fetcher?: MigrationFetcher): Promise<MigrationBundle> {\n if (!bundle.remoteApiSpecs?.length) return bundle\n const assets = [...bundle.assets]\n const tabs = bundle.docsConfig.tabs.map((tab) => ({ ...tab }))\n const redirects = [...(bundle.docsConfig.redirects ?? [])]\n const warnings = [...bundle.warnings]\n const authoredLinks = new Set<string>()\n for (const page of bundle.pages) {\n // Scan path-shaped tokens once, then inspect segments without nested\n // regex quantifiers. Authored pages may be arbitrarily long or hostile.\n for (const match of page.body.matchAll(/\\/[a-z0-9_/-]+/gi)) {\n const segments = match[0].split('/').filter(Boolean)\n if (segments.length < 3) continue\n const section = segments[0].toLowerCase()\n if (section.includes('api') || section.includes('reference')) authoredLinks.add(match[0])\n }\n }\n for (const reference of bundle.remoteApiSpecs) {\n for (let index = warnings.length - 1; index >= 0; index--) {\n if (warnings[index].source === reference.url && warnings[index].message.includes('requires a network download')) warnings.splice(index, 1)\n }\n try {\n const url = validatedSpecUrl(reference.url)\n const extension = /\\.ya?ml$/i.test(url.pathname) ? 'yaml' : 'json'\n const body = await downloadSpec(reference.url, fetcher)\n const operations = parseOpenApi(body, extension)\n const filename = `openapi-${createHash('sha256').update(reference.url).digest('hex').slice(0, 12)}.${extension}`\n assets.push({ path: filename, content: body })\n const tab = reference.tabLabel\n ? tabs.find((candidate) => candidate.tab === reference.tabLabel)\n : tabs.find((candidate) => candidate.tab.toLowerCase().includes('api'))\n if (tab) tab.api = { source: `/${filename}` }\n else tabs.push({ tab: reference.tabLabel ?? 'API Reference', api: { source: `/${filename}` } })\n\n const routes = new Map<string, string | null>()\n for (const operation of operations) {\n const key = `${slug(operation.tag)}/${slug(operation.summary)}`\n if (routes.has(key)) routes.set(key, null)\n else routes.set(key, operationTarget(operation))\n }\n const existingSources = new Set(redirects.map((redirect) => redirect.source))\n for (const source of authoredLinks) {\n const parts = source.split('/').filter(Boolean)\n const key = parts.slice(-2).join('/')\n const destination = routes.get(key)\n if (!destination || existingSources.has(source)) continue\n redirects.push({ source, destination, permanent: false })\n existingSources.add(source)\n }\n } catch (error) {\n warnings.push({\n code: 'fetch-failed',\n source: reference.url,\n message: `Remote OpenAPI spec could not be imported: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n return {\n ...bundle,\n assets,\n docsConfig: { ...bundle.docsConfig, tabs, ...(redirects.length > 0 ? { redirects } : {}) },\n warnings,\n }\n}\n"],"mappings":";AAUA,SAAS,eAAAA,oBAAmB;AAC5B,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA,cAAAC;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,qBAAqB;AAC9B,SAAS,YAAAC,WAAU,WAAAC,UAAS,WAAAC,UAAS,cAAAC,aAAY,YAAAC,WAAU,WAAW,aAAa,OAAAC,YAAW;AAE9F,SAAS,SAASC,kBAAiB;AACnC,YAAYC,SAAQ;;;ACvBpB,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,oBAAoB;AACpD,SAAS,UAAU,SAAS,SAAS,YAAAC,WAAU,WAAAC,gBAAe;AAC9D,OAAO,aAAa;AACpB,OAAO,oBAAoB;AAC3B,OAAOC,gBAAe;AACtB,OAAOC,kBAAiB;AACxB,OAAO,QAAQ;AACf,SAAS,WAAAC,gBAAe;;;ACFxB,SAAS,SAAS,iBAAiB;AAenC,SAAS,wBAAwB,QAAyC;AACxE,QAAM,OAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,CAAC,uBAAuB,KAAK,IAAI,EAAG;AACxC,QAAI;AACF,YAAM,aAAa,UAAU,IAAI;AACjC,UAAI,cAAc,OAAO,eAAe,YAAY,CAAC,MAAM,QAAQ,UAAU,GAAG;AAC9E,eAAO,OAAO,MAAM,UAAU;AAAA,MAChC;AAAA,IACF,QAAQ;AAAA,IAER;A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AAiB,KAAK,EAAE,QAAQ,IAAI,QAAQ,GAAG,EAAE,CAAC;AAE9F,YAAM,SAAS,oBAAI,IAA2B;AAC9C,iBAAW,aAAa,YAAY;AAClC,cAAM,MAAM,GAAG,KAAK,UAAU,GAAG,CAAC,IAAI,KAAK,UAAU,OAAO,CAAC;AAC7D,YAAI,OAAO,IAAI,GAAG,EAAG,QAAO,IAAI,KAAK,IAAI;AAAA,YACpC,QAAO,IAAI,KAAK,gBAAgB,SAAS,CAAC;AAAA,MACjD;AACA,YAAM,kBAAkB,IAAI,IAAI,UAAU,IAAI,CAAC,aAAa,SAAS,MAAM,CAAC;AAC5E,iBAAW,UAAU,eAAe;AAClC,cAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,OAAO,OAAO;AAC9C,cAAM,MAAM,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACpC,cAAM,cAAc,OAAO,IAAI,GAAG;AAClC,YAAI,CAAC,eAAe,gBAAgB,IAAI,MAAM,EAAG;AACjD,kBAAU,KAAK,EAAE,QAAQ,aAAa,WAAW,MAAM,CAAC;AACxD,wBAAgB,IAAI,MAAM;AAAA,MAC5B;AAAA,IACF,SAAS,OAAO;AACd,eAAS,KAAK;AAAA,QACZ,MAAM;AAAA,QACN,QAAQ,UAAU;AAAA,QAClB,SAAS,8CAA8C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC/G,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,YAAY,EAAE,GAAG,OAAO,YAAY,MAAM,GAAI,UAAU,SAAS,IAAI,EAAE,UAAU,IAAI,CAAC,EAAG;AAAA,IACzF;AAAA,EACF;AACF;","names":["compileSync","existsSync","lstatSync","readFileSync","readdirSync","realpathSync","basename","dirname","extname","isAbsolute","relative","sep","parseYaml","ts","relative","resolve","remarkMdx","remarkParse","unified","root","normalized","closing","unified","remarkParse","remarkMdx","imports","resolve","relative","renameToProp","nextPath","inspect","node","stripDroppedSpreads","bind","root","source","existsSync","lstatSync","readFileSync","extname","posix","parseYaml","existsSync","lstatSync","readFileSync","dirname","extname","relative","existsSync","lstatSync","relative","readFileSync","dirname","value","relative","extname","objectValue","titleCase","slug","posix","lstatSync","readFileSync","existsSync","candidate","resolved","extname","parseYaml","pages","existsSync","lstatSync","readFileSync","basename","dirname","extname","relative","parseYaml","MAX_CONFIG_BYTES","objectValue","titleCase","lstatSync","parseYaml","readFileSync","existsSync","warnOnce","relative","basename","pages","extname","dirname","existsSync","lstatSync","readFileSync","readdirSync","basename","relative","dirname","resolve","extname","realpathSync","sep","compileSync","parseYaml","imports","hash","index","slug","isAbsolute","discovered","assetPaths","load","remarkMdx","remarkParse","unified","parseYaml","unified","remarkParse","remarkMdx","request","load","value","payload","parseYaml","title","converted","candidates","entries","createHash","parseYaml","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/repository.ts","../src/components.ts","../src/frontmatter.ts","../src/mdx.ts","../src/builtin-components.ts","../src/path.ts","../src/inline-extraction.ts","../src/docusaurus.ts","../src/navigation.ts","../src/fern.ts","../src/render.ts","../src/url.ts","../src/remote-api.ts"],"sourcesContent":["/**\n * Repository adapter for the shared migration engine. Traversal is bounded;\n * `scanFiles` follows a symbolic link only when its resolved real path stays\n * inside the repository checkout (this covers a submodule mounted as a\n * symlink, e.g. Oasis's `docs/core -> ../external/oasis-core/docs`) and\n * guards against a cycle, but every other directory walk in this file still\n * skips symlinks outright. Git is always invoked with an argument array so\n * source-controlled branch names can never become shell commands.\n */\n\nimport { compileSync } from '@mdx-js/mdx'\nimport { spawn } from 'node:child_process'\nimport {\n closeSync,\n existsSync,\n lstatSync,\n openSync,\n readFileSync,\n readSync,\n readdirSync,\n realpathSync,\n rmSync,\n statSync,\n} from 'node:fs'\nimport type { Dirent } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, extname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path'\n\nimport { parse as parseYaml } from 'yaml'\nimport * as ts from 'typescript'\n\nimport { createComponentMigrator, declarationsReferenceBrowserGlobal, hasAnyFunctionValuedProp, normalizeIndentedFences, propsTargetExtractedClientComponent } from './components.js'\n\nimport {\n addDocusaurusTranslatedHeadingAliases,\n expandDocusaurusDocCardLists,\n projectDocusaurusNavigation,\n readDocusaurusRedirects,\n readDocusaurusSiteOrigin,\n readDocusaurusSiteSettings,\n readDocusaurusSidebars,\n readDocusaurusThemeColor,\n rewriteDocusaurusLinks,\n resolveDocusaurusPageIdentity,\n type DocusaurusPageDescriptor,\n type DocusaurusSidebars,\n} from './docusaurus.js'\nimport type { FernApiSection } from './fern.js'\nimport { projectFernNavigation, readFernConfig } from './fern.js'\nimport { escapeFernLiteralBraces, functionDeclaredNames, parseMarkdownPage, normalizeExplicitHeadingIds, protectMathBlocks, replaceLinkWithAnchor, replaceOutsideCode, replaceUnknownComponents, rewriteFernRelativePageLinks } from './mdx.js'\nimport {\n addMintlifyDirectoryRedirects,\n addMintlifyHomepageRedirects,\n buildNavigationFromPages,\n isDocumentationExtension,\n mintlifyAllVersionPrefixes,\n mintlifyDefaultVersionPrefixes,\n mintlifyNavigationApiReferences,\n projectMintlifyNavigation,\n pruneMissingNavigationPages,\n readMintlifyConfig,\n type MintlifyApiSpecReference,\n} from './navigation.js'\nimport {\n normalizeAssetPath,\n mintlifyLocalizedReference,\n pageIdFromReference,\n resolveWithin,\n resolveWithinRoot,\n trimEdgeSlashes,\n trimTrailingSlashes,\n} from './path.js'\nimport type {\n MigrationAsset,\n MigrationBundle,\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationPlatform,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_SOURCE_FILES = 5_000\nconst MAX_PAGE_BYTES = 2_000_000\nconst MAX_ASSET_BYTES = 25_000_000\nconst MAX_TOTAL_ASSET_BYTES = 500_000_000\n/** A Git LFS pointer file's fixed opening line (the smudge filter replaces this with the real binary; skipping it during clone leaves this text in place). */\nconst GIT_LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/v1'\n\n/** A small text file starting with the fixed Git LFS pointer line, not real asset content. */\nfunction isGitLfsPointer(content: Buffer): boolean {\n return content.length < 1024 && content.toString('utf8', 0, GIT_LFS_POINTER_PREFIX.length) === GIT_LFS_POINTER_PREFIX\n}\nconst IGNORED_DIRECTORIES = new Set([\n '.git', '.github', '.next', '.turbo', '.vercel', '.vscode',\n 'node_modules', 'dist', 'build', 'coverage',\n])\n// `dist`/`build`/`coverage` are build output when found while *looking for*\n// a docs root (root-detection BFS below, which walks the whole repository\n// checkout) — but once a docs content root is actually confirmed, a\n// same-named subdirectory inside it is real content, not output (e.g.\n// oasisprotocol/docs's `docs/build/`, a live section of the site).\n// `scanFiles`'s own walk is always already confined to a confirmed content\n// root, so it uses this narrower set instead of `IGNORED_DIRECTORIES`.\nfunction isIgnoredContentDirectory(name: string): boolean {\n return name.startsWith('.') || name === 'node_modules'\n}\nconst ASSET_DIRECTORIES = new Set(['assets', 'images', 'img', 'media', 'public', 'static'])\nconst ASSET_EXTENSIONS = new Set([\n '.avif', '.bmp', '.gif', '.ico', '.jpeg', '.jpg', '.m4a', '.mp3', '.mp4',\n '.ogg', '.pdf', '.png', '.svg', '.wav', '.webm', '.webp',\n])\nconst REPOSITORY_ONLY_DOCUMENTS = new Set([\n 'agents.md', 'claude.md', 'code_of_conduct.md', 'contributing.md',\n 'license.md', 'readme.md', 'security.md',\n])\nconst SNIPPET_DIRECTORIES = new Set(['snippets', '_snippets', 'partials', '_partials'])\n// Matches a default import (`import Name from '...'`), a default-as-named\n// import (`import { default as Name } from '...'`), and a plain named import\n// (`import { Name } from '...'`) — Mintlify snippets can export either way.\nconst SNIPPET_IMPORT_PATTERN = /\\bimport\\s+(?:\\{\\s*(?:default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}|([A-Z][A-Za-z0-9_]*))\\s+from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?/g\nconst SNIPPET_VALUE_IMPORT_PATTERN = /\\bimport\\s*\\{([^{}]+)\\}\\s*from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?/g\n\n/**\n * Mintlify's `<Snippet file=\"path.mdx\" />` tag form: unlike the import form\n * above, this never needs a matching `import` statement — `file` is a path\n * relative to the project's `snippets/` directory (Mintlify's own\n * convention; see `resolveSnippetPath`'s sibling below for the actual\n * lookup). Both self-closing and paired spellings are matched; a paired\n * tag's own children (if any) are always discarded in favor of the\n * resolved snippet's real content, matching Mintlify's own renderer.\n */\nconst SNIPPET_TAG_PATTERN = /<Snippet\\s+file=(?:\"([^\"]+)\"|'([^']+)')\\s*(?:\\/>|>[\\s\\S]*?<\\/Snippet>)/g\nconst MINTIGNORE_FILENAME = '.mintignore'\ninterface IgnoreMatcher {\n add(patterns: string): IgnoreMatcher\n ignores(pathname: string): boolean\n}\n// `ignore`'s CJS default export is mistyped under NodeNext module resolution\n// (the default import resolves to the whole module namespace); load it\n// through `require` and type it locally instead of fighting the interop.\nconst createIgnoreMatcher = createRequire(import.meta.url)('ignore') as () => IgnoreMatcher\n\n/** Dotfile directories (`.tooling`, `.vale`, tool/editor config, ...) never hold docs pages. */\nfunction isIgnoredDirectory(name: string): boolean {\n return name.startsWith('.') || IGNORED_DIRECTORIES.has(name)\n}\n\nconst OPENAPI_FILENAMES = new Set([\n 'openapi.json', 'openapi.yaml', 'openapi.yml',\n 'swagger.json', 'swagger.yaml', 'swagger.yml',\n])\n\nexport interface GitHubRepositorySource {\n owner: string\n repo: string\n branch: string\n docsDir: string\n cloneUrl: string\n}\n\nexport interface RepositoryMigrationOptions {\n repositoryDir: string\n sourceUrl: string\n docsDir?: string\n platform?: MigrationPlatform\n /** @internal Prefix used by additional Docusaurus docs-plugin instances. */\n docusaurusRoutePrefix?: string\n /** @internal Prevent recursive discovery while importing one plugin root. */\n docusaurusSkipPlugins?: boolean\n /** @internal Additional docs plugins default to autogenerated navigation. */\n docusaurusSkipSidebar?: boolean\n /** @internal A version's sidebar is parsed as static data. */\n docusaurusSidebarPath?: string\n /** @internal Static assets are shared across docs-plugin instances. */\n docusaurusSkipAssets?: boolean\n /** @internal Redirects are global config, read once, not per plugin instance. */\n docusaurusSkipRedirects?: boolean\n}\n\ninterface DocusaurusPluginRoot {\n docsDir: string\n routePrefix: string\n}\n\ninterface DocusaurusArchiveRoot extends DocusaurusPluginRoot {\n label: string\n sidebarPath?: string\n}\n\nconst DOCUSAURUS_CONFIG_FILENAMES = [\n 'docusaurus.config.js',\n 'docusaurus.config.ts',\n 'docusaurus.config.mjs',\n]\n\nfunction hasDocusaurusConfig(directory: string): boolean {\n return DOCUSAURUS_CONFIG_FILENAMES.some((filename) => {\n const path = resolveWithin(directory, filename)\n return existsSync(path) && lstatSync(path).isFile()\n })\n}\n\nfunction hasMintlifyConfig(directory: string): boolean {\n return ['docs.json', 'mint.json'].some((filename) => {\n const path = resolveWithin(directory, filename)\n if (!existsSync(path) || !lstatSync(path).isFile()) return false\n if (filename === 'mint.json') return true\n try {\n const config = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>\n return String(config.$schema ?? '').includes('mintlify') || 'navigation' in config\n } catch {\n return false\n }\n })\n}\n\n/**\n * Recursively counts `.md`/`.mdx` files under `directory` (skipping\n * ignored/symlinked directories, same as the root-finding BFS above), for\n * ranking two candidate project roots against each other. Bounded so a huge\n * false-positive candidate (e.g. `node_modules` slipping past\n * `isIgnoredDirectory`) can't make root detection itself slow.\n */\nfunction countMarkdownPages(directory: string, limit = 20_000): number {\n let count = 0\n const stack: Array<string> = [directory]\n while (stack.length > 0 && count < limit) {\n const current = stack.pop()!\n let entries: Array<Dirent>\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n continue\n }\n for (const entry of entries) {\n if (entry.isSymbolicLink()) continue\n if (entry.isDirectory()) {\n if (!isIgnoredDirectory(entry.name)) stack.push(resolveWithin(current, entry.name))\n } else if (/\\.mdx?$/i.test(entry.name)) {\n count++\n }\n }\n }\n return count\n}\n\n/**\n * Multiple config files can each look like a valid project root in the same\n * repository (Infisical ships both a top-level `company/mint.json` handbook\n * and `docs/docs.json`, the real docs). Picking the first one a breadth-\n * first walk happens to reach silently imports the wrong, usually much\n * smaller, site. Rank every candidate instead: `docs.json` before\n * `mint.json` (Mintlify's own current format), then a directory literally\n * named `docs`, then whichever has the most actual content — and warn\n * whenever there was more than one candidate, so a wrong guess is visible\n * and `--docs-dir` is offered as the fix, even when the ranking picked the\n * one the caller actually wanted.\n */\nfunction pickPreferredDocsRoot(\n candidates: Array<string>,\n repositoryDir: string,\n platformLabel: string,\n warnings: Array<MigrationWarning> | undefined,\n rank?: (directory: string) => number,\n): string {\n const ranked = [...candidates].sort((left, right) => {\n const byRank = (rank?.(right) ?? 0) - (rank?.(left) ?? 0)\n if (byRank !== 0) return byRank\n const byName = (basename(right) === 'docs' ? 1 : 0) - (basename(left) === 'docs' ? 1 : 0)\n if (byName !== 0) return byName\n return countMarkdownPages(right) - countMarkdownPages(left)\n })\n const winner = ranked[0]\n if (candidates.length > 1 && warnings) {\n const relativePaths = candidates.map((candidate) => relative(repositoryDir, candidate) || '.')\n warnings.push({\n code: 'unsupported-config',\n message: `Multiple possible ${platformLabel} project roots were found (${relativePaths.join(', ')}); `\n + `${relative(repositoryDir, winner) || '.'} was picked. Pass --docs-dir to choose a different one if this is wrong.`,\n source: '.',\n })\n }\n return winner\n}\n\nfunction findMintlifyProjectRoot(repositoryDir: string, docsDir?: string, warnings?: Array<MigrationWarning>): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasMintlifyConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n const candidates: Array<string> = []\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasMintlifyConfig(current.directory)) candidates.push(current.directory)\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({ directory: resolveWithin(current.directory, entry.name), depth: current.depth + 1 })\n }\n }\n if (candidates.length === 0) return null\n return pickPreferredDocsRoot(candidates, repositoryDir, 'Mintlify', warnings, (directory) => (\n existsSync(resolveWithin(directory, 'docs.json')) ? 1 : 0\n ))\n}\n\nfunction hasFernConfig(directory: string): boolean {\n return ['docs.yml', 'fern.config.json'].every((filename) => {\n const path = resolveWithin(directory, filename)\n return existsSync(path) && lstatSync(path).isFile()\n })\n}\n\nfunction findFernProjectRoot(repositoryDir: string, docsDir?: string): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasFernConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasFernConfig(current.directory)) return current.directory\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({ directory: resolveWithin(current.directory, entry.name), depth: current.depth + 1 })\n }\n }\n return null\n}\n\nfunction findDocusaurusProjectRoot(repositoryDir: string, docsDir?: string, warnings?: Array<MigrationWarning>): string | null {\n if (docsDir !== undefined) {\n let candidate = trimTrailingSlashes(docsDir)\n while (true) {\n const path = resolveWithin(repositoryDir, candidate || '.')\n if (hasDocusaurusConfig(path)) return path\n if (!candidate) break\n const parent = dirname(candidate)\n candidate = parent === '.' ? '' : parent\n }\n }\n\n const candidates: Array<string> = []\n const queue: Array<{ directory: string; depth: number }> = [{ directory: repositoryDir, depth: 0 }]\n let visited = 0\n while (queue.length > 0 && visited < 500) {\n const current = queue.shift()!\n visited++\n if (hasDocusaurusConfig(current.directory)) candidates.push(current.directory)\n if (current.depth >= 4) continue\n for (const entry of readdirSync(current.directory, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.isSymbolicLink() || isIgnoredDirectory(entry.name)) continue\n queue.push({\n directory: resolveWithin(current.directory, entry.name),\n depth: current.depth + 1,\n })\n }\n }\n if (candidates.length === 0) return null\n return pickPreferredDocsRoot(candidates, repositoryDir, 'Docusaurus', warnings)\n}\n\nfunction readDocusaurusConfigSource(projectRoot: string): string {\n const path = DOCUSAURUS_CONFIG_FILENAMES\n .map((filename) => resolveWithin(projectRoot, filename))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile())\n if (!path || lstatSync(path).size > 1_000_000) return ''\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Scans forward from a `{` for its matching `}`, skipping over string,\n * template, and comment contents so braces inside them don't throw off the\n * depth count. Returns -1 if the object is never closed.\n */\nfunction matchingBraceIndex(source: string, openBraceIndex: number): number {\n let depth = 0\n for (let i = openBraceIndex; i < source.length; i++) {\n const ch = source[i]\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n const quote = ch\n i++\n while (i < source.length && source[i] !== quote) {\n if (source[i] === '\\\\') i++\n i++\n }\n continue\n }\n if (ch === '/' && source[i + 1] === '/') {\n const newline = source.indexOf('\\n', i)\n i = newline === -1 ? source.length : newline\n continue\n }\n if (ch === '/' && source[i + 1] === '*') {\n const end = source.indexOf('*/', i + 2)\n i = end === -1 ? source.length : end + 1\n continue\n }\n if (ch === '{') depth++\n else if (ch === '}') {\n depth--\n if (depth === 0) return i\n }\n }\n return -1\n}\n\n/** Finds a `key: 'value'` or `key: \"value\"` pair at the top level of an object body (not nested inside a further `{`, `[`, or `(`). */\nfunction topLevelStringProperty(objectBody: string, key: string): string | undefined {\n let depth = 0\n const keyPattern = new RegExp(`^${key}\\\\s*:\\\\s*(['\"])`)\n for (let i = 0; i < objectBody.length; i++) {\n const ch = objectBody[i]\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n const quote = ch\n i++\n while (i < objectBody.length && objectBody[i] !== quote) {\n if (objectBody[i] === '\\\\') i++\n i++\n }\n continue\n }\n if (ch === '/' && objectBody[i + 1] === '/') {\n const newline = objectBody.indexOf('\\n', i)\n i = newline === -1 ? objectBody.length : newline\n continue\n }\n if (ch === '/' && objectBody[i + 1] === '*') {\n const end = objectBody.indexOf('*/', i + 2)\n i = end === -1 ? objectBody.length : end + 1\n continue\n }\n if (ch === '{' || ch === '[' || ch === '(') {\n depth++\n continue\n }\n if (ch === '}' || ch === ']' || ch === ')') {\n depth--\n continue\n }\n if (depth === 0) {\n const match = keyPattern.exec(objectBody.slice(i))\n if (match) {\n const quote = match[1]\n const valueStart = i + match[0].length\n const valueEnd = objectBody.indexOf(quote, valueStart)\n if (valueEnd !== -1) return objectBody.slice(valueStart, valueEnd)\n }\n }\n }\n return undefined\n}\n\nfunction primaryDocusaurusDocsDirectory(projectRoot: string): string {\n const source = readDocusaurusConfigSource(projectRoot)\n // The classic preset's `docs: { ... }` object configures the primary docs\n // instance. Its `path` (when present) must come from directly inside that\n // object, not from a `path` belonging to a nested value (e.g. a versions\n // entry) or to an unrelated plugin's config further down the file — a\n // brace-blind regex can walk straight through the docs object's closing\n // brace into the next plugin's `path` (see the standalone content-docs\n // plugin case handled by `additionalDocusaurusPluginRoots`).\n const docsKeyMatch = source.match(/\\bdocs\\s*:\\s*\\{/)\n let configured: string | undefined\n if (docsKeyMatch?.index !== undefined) {\n const openBrace = docsKeyMatch.index + docsKeyMatch[0].length - 1\n const closeBrace = matchingBraceIndex(source, openBrace)\n if (closeBrace !== -1) {\n configured = topLevelStringProperty(source.slice(openBrace + 1, closeBrace), 'path')\n }\n }\n return trimTrailingSlashes(configured?.replace(/^\\.\\//, '') ?? '') || 'docs'\n}\n\n/** Discover archived docs and translations without evaluating project config. */\nfunction docusaurusArchiveRoots(projectRoot: string, repositoryDir: string, warnings: Array<MigrationWarning>): Array<DocusaurusArchiveRoot> {\n const archives: Array<DocusaurusArchiveRoot> = []\n const relativeRoot = relative(repositoryDir, projectRoot).replace(/\\\\/g, '/')\n const directoryNames = (directory: string): Array<string> => {\n const path = resolveWithin(projectRoot, directory)\n if (!existsSync(path) || !lstatSync(path).isDirectory()) return []\n return readdirSync(path, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())\n .map((entry) => entry.name).sort()\n }\n let versions = directoryNames('versioned_docs').filter((name) => /^version-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))\n const versionsPath = resolveWithin(projectRoot, 'versions.json')\n if (existsSync(versionsPath) && lstatSync(versionsPath).isFile()) {\n try {\n if (lstatSync(versionsPath).size > 100_000) throw new Error('file exceeds the 100 KB limit')\n const declared: unknown = JSON.parse(readFileSync(versionsPath, 'utf8'))\n if (!Array.isArray(declared) || !declared.every((value) => typeof value === 'string')) throw new Error('expected an array of version names')\n const declaredOrder = declared.map((value) => `version-${value}`)\n versions = [...declaredOrder.filter((name) => versions.includes(name)), ...versions.filter((name) => !declaredOrder.includes(name))]\n } catch (error) {\n warnings.push({ code: 'unsupported-config', message: `Docusaurus versions.json could not be read safely: ${error instanceof Error ? error.message : String(error)}` })\n }\n }\n const sidebarPath = (version: string): string | undefined => {\n const candidates = ['json', 'js', 'cjs', 'mjs', 'ts'].map((extension) => `versioned_sidebars/${version}-sidebars.${extension}`)\n return candidates.find((candidate) => {\n const path = resolveWithin(projectRoot, candidate)\n return existsSync(path) && lstatSync(path).isFile()\n })\n }\n const add = (directory: string, routePrefix: string, label: string, sidebar?: string): void => {\n const docsDir = [relativeRoot, directory].filter(Boolean).join('/')\n archives.push({ docsDir, routePrefix, label, ...(sidebar ? { sidebarPath: sidebar } : {}) })\n }\n for (const version of versions) add(`versioned_docs/${version}`, version.slice('version-'.length), `Version ${version.slice('version-'.length)}`, sidebarPath(version))\n for (const locale of directoryNames('i18n').filter((name) => /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8})*$/.test(name))) {\n const localizedRoot = `i18n/${locale}/docusaurus-plugin-content-docs`\n const current = resolveWithin(projectRoot, `${localizedRoot}/current`)\n if (existsSync(current) && lstatSync(current).isDirectory()) add(`${localizedRoot}/current`, locale, `${locale} Documentation`)\n // A translation can exist for a version no longer present in the default\n // language's versioned_docs tree; discover its files independently.\n const localizedVersions = directoryNames(localizedRoot)\n .filter((name) => /^version-[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))\n for (const version of localizedVersions) {\n const path = resolveWithin(projectRoot, `${localizedRoot}/${version}`)\n if (existsSync(path) && lstatSync(path).isDirectory()) add(`${localizedRoot}/${version}`, `${locale}/${version.slice('version-'.length)}`, `${locale} Version ${version.slice('version-'.length)}`)\n }\n }\n // Each recursive import has its own 5,000-file scan cap. Bound the number\n // of roots too, so a hostile checkout cannot multiply work indefinitely.\n if (archives.length > 48) warnings.push({ code: 'limit-reached', message: `Only the first 48 Docusaurus archived or localized docs roots were imported (${archives.length} found).` })\n return archives.slice(0, 48)\n}\n\nfunction additionalDocusaurusPluginRoots(\n repositoryDir: string,\n projectRoot: string,\n warnings: Array<MigrationWarning>,\n): Array<DocusaurusPluginRoot> {\n const source = readDocusaurusConfigSource(projectRoot)\n const plugins: Array<DocusaurusPluginRoot> = []\n // Docusaurus resolves the bare shorthand ('content-docs') to the same\n // official plugin as the full package name, so both forms are matched.\n const matcher = /['\"](?:@docusaurus\\/plugin-)?content-docs['\"][\\s\\S]{0,3000}?\\bpath\\s*:\\s*(['\"])([^'\"]+)\\1[\\s\\S]{0,1000}?\\brouteBasePath\\s*:\\s*(['\"])([^'\"]+)\\3/g\n for (const match of source.matchAll(matcher)) {\n const localPath = trimTrailingSlashes(match[2].replace(/^\\.\\//, ''))\n const routePrefix = trimEdgeSlashes(match[4])\n if (!localPath || !routePrefix) continue\n // Docusaurus resolves a content-docs instance's `path` relative to the\n // site directory (where `docusaurus.config` lives, `projectRoot` here).\n // Some monorepo sites build by copying that project root's contents up\n // into the repository root before running the generator (Playwright's\n // own `cp -r nodejs/* .` step is a real example — see the identical\n // fallback in components.ts's `resolveDependency`), so a `path` that\n // isn't found under `projectRoot` is retried directly under\n // `repositoryDir`, still confined to the repository.\n let docsDir: string | undefined\n for (const base of [projectRoot, repositoryDir]) {\n let absolute: string\n try {\n absolute = resolveWithin(base, localPath)\n } catch {\n continue\n }\n if (existsSync(absolute) && lstatSync(absolute).isDirectory()) {\n docsDir = relative(repositoryDir, absolute).replace(/\\\\/g, '/')\n break\n }\n }\n if (docsDir) {\n plugins.push({ docsDir, routePrefix })\n } else {\n warnings.push({\n code: 'unsupported-config',\n message: `The \"${routePrefix}\" docs plugin instance's path (${JSON.stringify(match[2])}) could not be found in the repository and was skipped.`,\n })\n }\n }\n return plugins\n}\n\n/** Parse and validate a public GitHub repository URL. */\nexport function parseGitHubRepositoryUrl(rawUrl: string): GitHubRepositorySource {\n let url: URL\n try {\n url = new URL(rawUrl)\n } catch {\n throw new Error(`Invalid GitHub URL: ${rawUrl}`)\n }\n if (url.protocol !== 'https:' || url.hostname.toLowerCase() !== 'github.com') {\n throw new Error('Repository migrations require an https://github.com URL.')\n }\n if (url.username || url.password || url.port) {\n throw new Error('GitHub repository URLs cannot include credentials or custom ports.')\n }\n const segments = url.pathname.split('/').filter(Boolean).map(decodeURIComponent)\n const [owner, rawRepo] = segments\n const repo = rawRepo?.replace(/\\.git$/i, '')\n const safeName = /^[A-Za-z0-9_.-]+$/\n if (!owner || !repo || !safeName.test(owner) || !safeName.test(repo)) {\n throw new Error('GitHub URL must include a valid owner and repository name.')\n }\n let branch = 'HEAD'\n let docsDir = ''\n if (segments[2] === 'tree' && segments[3]) {\n branch = segments[3]\n docsDir = segments.slice(4).join('/')\n }\n return {\n owner,\n repo,\n branch,\n docsDir,\n cloneUrl: `https://github.com/${owner}/${repo}.git`,\n }\n}\n\nconst CLONE_RETRY_ATTEMPTS = 3\nconst CLONE_RETRY_DELAY_MS = 1_000\nconst DEFAULT_CLONE_TIMEOUT_MS = 10 * 60_000\n\n/** Transient network-class git failures a retry can plausibly recover from. Also covers this module's own timeout error below. */\nconst RETRYABLE_CLONE_ERROR = /RPC failed|Recv failure|early EOF|curl \\d+|Could not resolve host|Connection (?:reset|refused|timed out)|The remote end hung up|SSL[_ ]?(?:read|connect|write) error|timed out|network is unreachable/i\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => { setTimeout(resolve, ms) })\n}\n\n/** How long a single git subprocess may run before it's killed and treated as a (retryable) timeout. Configurable since a very large repository on a slow link may need longer than the generous 10-minute default. */\nfunction gitProcessTimeoutMs(): number {\n const raw = process.env.THALLY_MIGRATE_CLONE_TIMEOUT_MS\n const parsed = raw ? Number(raw) : NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CLONE_TIMEOUT_MS\n}\n\n/**\n * Run one git subprocess without a shell, with an overall timeout (a\n * stalled clone/fetch otherwise hangs forever — there is no `timeout`\n * binary to rely on) and per-process env overrides (never touching global\n * git/npm config, per this package's own rule).\n */\nfunction runGit(args: Array<string>, options: { cwd?: string; env?: Record<string, string>; label: string }): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = spawn('git', args, {\n stdio: ['ignore', 'ignore', 'pipe'],\n ...(options.cwd ? { cwd: options.cwd } : {}),\n env: { ...process.env, ...options.env },\n })\n let stderr = ''\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n child.kill('SIGKILL')\n }, gitProcessTimeoutMs())\n child.stderr.setEncoding('utf8')\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 16_000) stderr += chunk\n })\n child.on('error', (error) => {\n clearTimeout(timer)\n reject(error)\n })\n child.on('close', (code) => {\n clearTimeout(timer)\n if (code === 0) resolve()\n else if (timedOut) reject(new Error(`${options.label} timed out after ${gitProcessTimeoutMs()}ms and was killed.`))\n else reject(new Error(`${options.label}: ${stderr.trim() || `git exited ${code}`}`))\n })\n })\n}\n\n/**\n * Neutralize the `filter.lfs.*` smudge/clean/process filter driver for one\n * git process only — never the user's global git config — so a repository\n * tracked with Git LFS still clones when the host has no `git-lfs` binary.\n * `GIT_LFS_SKIP_SMUDGE=1` alone isn't enough: if this host ever had\n * `git lfs install` run and then had the `git-lfs` binary removed (as here),\n * `filter.lfs.smudge`/`.process` are still registered in the *global* git\n * config pointing at a command that no longer exists, and\n * `GIT_LFS_SKIP_SMUDGE` is only ever read by that (missing) binary — git\n * itself still fails outright trying to invoke it. `GIT_CONFIG_COUNT`/\n * `GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n` env pairs are the one config\n * source with higher precedence than the user's global config, so they can\n * override it per-process: `smudge`/`clean` become `cat` (pass the LFS\n * pointer text straight through — real content was never fetched anyway)\n * and `process` is cleared so git falls back to them; `filter.lfs.required\n * = false` keeps a filter hiccup on one path (an oversized fixture, say)\n * from failing the whole checkout. The result is the repository's own\n * files, with an LFS-tracked asset left as its pointer text — the\n * asset-copying step below warns when a copied file turns out to be one.\n */\nconst LFS_FILTER_OVERRIDE_ENV: Record<string, string> = {\n GIT_CONFIG_COUNT: '4',\n GIT_CONFIG_KEY_0: 'filter.lfs.smudge',\n GIT_CONFIG_VALUE_0: 'cat',\n GIT_CONFIG_KEY_1: 'filter.lfs.clean',\n GIT_CONFIG_VALUE_1: 'cat',\n GIT_CONFIG_KEY_2: 'filter.lfs.process',\n GIT_CONFIG_VALUE_2: '',\n GIT_CONFIG_KEY_3: 'filter.lfs.required',\n GIT_CONFIG_VALUE_3: 'false',\n}\n\nfunction cloneOnce(source: GitHubRepositorySource, targetDir: string): Promise<void> {\n // Submodules are deliberately not recursed here: `--recurse-submodules`\n // fails the *entire* clone if any one submodule can't be fetched (a\n // private or since-deleted submodule shouldn't take the whole migration\n // down). `initSubmodules`, run after a successful plain clone, is the\n // equivalent of `--recurse-submodules --shallow-submodules` (`--depth 1`\n // per submodule) but fault-tolerant per submodule.\n const args = ['clone', '--depth', '1', '--single-branch']\n if (source.branch !== 'HEAD') args.push('--branch', source.branch)\n args.push('--', source.cloneUrl, targetDir)\n return runGit(args, {\n label: `Failed to clone ${source.owner}/${source.repo}`,\n env: LFS_FILTER_OVERRIDE_ENV,\n })\n}\n\n/** Every submodule path declared in a cloned repository's `.gitmodules`, in file order. */\nexport function gitmodulePaths(targetDir: string): Array<string> {\n const gitmodulesPath = resolvePath(targetDir, '.gitmodules')\n if (!existsSync(gitmodulesPath) || !lstatSync(gitmodulesPath).isFile()) return []\n let content: string\n try {\n content = readFileSync(gitmodulesPath, 'utf8')\n } catch {\n return []\n }\n return [...content.matchAll(/^\\s*path\\s*=\\s*(.+?)\\s*$/gm)].map((match) => match[1]).filter(Boolean)\n}\n\n/**\n * Every submodule `url` in a cloned repository's `.gitmodules`, in the same\n * file order as `gitmodulePaths` (each `[submodule \"...\"]` block declares\n * `path` and `url` once, so index `i` here corresponds to index `i` there).\n */\nfunction gitmoduleUrls(targetDir: string): Array<string> {\n const gitmodulesPath = resolvePath(targetDir, '.gitmodules')\n if (!existsSync(gitmodulesPath) || !lstatSync(gitmodulesPath).isFile()) return []\n let content: string\n try {\n content = readFileSync(gitmodulesPath, 'utf8')\n } catch {\n return []\n }\n return [...content.matchAll(/^\\s*url\\s*=\\s*(.+?)\\s*$/gm)].map((match) => match[1]).filter(Boolean)\n}\n\n/**\n * `--recurse-submodules` on the main clone (above) fails the *entire* clone\n * if any one submodule can't be fetched, which is worse than not having\n * that submodule's content at all. So the main clone omits it and this\n * best-effort pass follows, per submodule path, so one broken/private\n * submodule doesn't take down the whole migration — it's just missing,\n * and named in a warning instead of silently absent.\n */\nasync function initSubmodules(targetDir: string, warnings: Array<MigrationWarning>): Promise<void> {\n const paths = gitmodulePaths(targetDir)\n if (paths.length === 0) return\n const urls = gitmoduleUrls(targetDir)\n const failed: Array<string> = []\n for (const [index, path] of paths.entries()) {\n // A path or url beginning with `-` would be read as a git option\n // rather than a pathspec/URL once it reaches argv (even after `--`,\n // git's own pathspec parser treats a leading `-` as a flag), and\n // `.gitmodules` is attacker-controlled content from the cloned repo.\n if (path.startsWith('-') || (urls[index]?.startsWith('-') ?? false)) {\n failed.push(path)\n continue\n }\n try {\n await runGit([\n '-c', 'protocol.file.allow=never',\n '-c', 'protocol.ext.allow=never',\n 'submodule', 'update', '--init', '--depth', '1', '--', path,\n ], {\n cwd: targetDir,\n env: LFS_FILTER_OVERRIDE_ENV,\n label: `Failed to initialize submodule ${path}`,\n })\n } catch {\n failed.push(path)\n }\n }\n if (failed.length > 0) {\n warnings.push({\n code: 'fetch-failed',\n message: `${failed.length} git submodule${failed.length === 1 ? '' : 's'} could not be fetched and ${failed.length === 1 ? 'is' : 'are'} missing from the migrated content: ${failed.join(', ')}.`,\n })\n }\n}\n\n/**\n * Clone a repository without a shell; callers own and remove `targetDir`. A\n * large repository on a flaky connection can drop mid-clone (`RPC failed`,\n * `Recv failure`, a `curl 56`, …) — retry a network-class failure a couple\n * of times with backoff instead of surfacing a hard failure on the first\n * blip. A partial checkout from the failed attempt is removed first, or\n * `git clone` refuses to reuse the (now non-empty) target directory. A\n * stalled clone/submodule-init is killed by `runGit`'s own timeout, which\n * surfaces as a retryable error. `warnings`, if given, collects a\n * submodule-fetch-failure warning (this function otherwise returns exactly\n * as before, so existing callers are unaffected).\n */\nexport async function cloneGitHubRepository(\n source: GitHubRepositorySource,\n targetDir: string,\n warnings?: Array<MigrationWarning>,\n): Promise<void> {\n for (let attempt = 1; attempt <= CLONE_RETRY_ATTEMPTS; attempt++) {\n try {\n await cloneOnce(source, targetDir)\n await initSubmodules(targetDir, warnings ?? [])\n return\n } catch (error) {\n const retryable = error instanceof Error && RETRYABLE_CLONE_ERROR.test(error.message)\n if (!retryable || attempt === CLONE_RETRY_ATTEMPTS) throw error\n rmSync(targetDir, { recursive: true, force: true })\n await delay(CLONE_RETRY_DELAY_MS * attempt)\n }\n }\n}\n\n/** Detect a supported repository docs platform from unambiguous config files. */\nexport function detectRepositoryPlatform(repositoryDir: string, docsDir?: string): MigrationPlatform {\n if (findMintlifyProjectRoot(repositoryDir, docsDir)) return 'mintlify'\n if (findFernProjectRoot(repositoryDir, docsDir)) return 'fern'\n const selectedRoot = docsDir === undefined ? repositoryDir : resolveWithin(repositoryDir, docsDir || '.')\n const docsJson = resolveWithin(selectedRoot, 'docs.json')\n if (existsSync(docsJson)) {\n try {\n const config = JSON.parse(readFileSync(docsJson, 'utf8')) as Record<string, unknown>\n if (Array.isArray(config.tabs)) return 'thally'\n } catch {\n // A malformed source config is reported later; platform detection falls through.\n }\n }\n if (['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'docusaurus'\n if (findDocusaurusProjectRoot(repositoryDir)) return 'docusaurus'\n if (existsSync(resolveWithin(repositoryDir, 'SUMMARY.md'))) return 'gitbook'\n if (existsSync(resolveWithin(repositoryDir, '.vitepress'))) return 'vitepress'\n if (['astro.config.mjs', 'astro.config.ts']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'starlight'\n if (['pages/_meta.json', '_meta.json']\n .some((name) => existsSync(resolveWithin(repositoryDir, name)))) return 'nextra'\n return 'unknown'\n}\n\nfunction containsMarkdown(directory: string, depth = 0): boolean {\n if (depth > 4) return false\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (isIgnoredDirectory(entry.name) || entry.isSymbolicLink()) continue\n const path = resolveWithin(directory, entry.name)\n if (entry.isFile() && ['.md', '.mdx'].includes(extname(entry.name).toLowerCase())) return true\n if (entry.isDirectory() && containsMarkdown(path, depth + 1)) return true\n }\n return false\n}\n\n/** Pick the first conventional content root containing Markdown. */\nexport function detectRepositoryDocsDir(repositoryDir: string): string {\n for (const candidate of ['docs', 'documentation', 'content', 'pages', 'src/content', 'src/pages', 'guide', 'guides', '']) {\n const path = resolveWithin(repositoryDir, candidate)\n if (existsSync(path) && lstatSync(path).isDirectory() && containsMarkdown(path)) return candidate\n }\n return ''\n}\n\ninterface ScannedFile {\n absolutePath: string\n relativePath: string\n}\n\n/**\n * Scan `root` for its files, following a symbolic link only when its\n * resolved real path stays inside `confinementRoot` (default `root`) — this\n * is how a submodule mounted as a symlink (Oasis's `docs/core ->\n * ../external/oasis-core/docs`, `docs/adrs -> ../external/adrs`) actually\n * gets its content walked, since a plain `git clone` (even with submodules\n * initialized) leaves those as real symlinks on disk that a naive walk\n * would otherwise always skip. `confinementRoot` is normally the whole\n * repository checkout, not just the docs root, because a submodule commonly\n * links out to a sibling directory outside it. `visitedRealPaths` guards\n * against a cycle (a symlink pointing at an ancestor, or two symlinks\n * pointing at each other).\n */\n/**\n * A generous ceiling on how many *directory entries* `scanFiles` will walk\n * when a `rank` function is supplied (see below) — far above\n * `MAX_SOURCE_FILES` so a repository the size of crewAI's (~28k files) is\n * walked in full, but still bounded so a pathologically huge tree can't\n * make discovery itself slow. Walking is cheap (no file content is read\n * here); only the final `MAX_SOURCE_FILES` selection is expensive to get\n * wrong.\n */\nconst MAX_RANKED_WALK_FILES = MAX_SOURCE_FILES * 20\n\n/**\n * Scan `root` for its files. When `rank` is given, the walk isn't cut off at\n * `MAX_SOURCE_FILES` — it continues (bounded by `MAX_RANKED_WALK_FILES`) so\n * every file's priority can be considered before any are dropped; the\n * caller is responsible for sorting by `rank` and trimming to\n * `MAX_SOURCE_FILES` afterward (see `selectFilesWithinBudget`). Without\n * `rank`, the walk stops as soon as `MAX_SOURCE_FILES` files are found, same\n * as before.\n */\nfunction scanFiles(root: string, confinementRoot: string = root, warnings?: Array<MigrationWarning>, rank?: (relativePath: string) => number): Array<ScannedFile> {\n const files: Array<ScannedFile> = []\n const walkCap = rank ? MAX_RANKED_WALK_FILES : MAX_SOURCE_FILES\n let confinementReal: string\n try {\n confinementReal = realpathSync(confinementRoot)\n } catch {\n confinementReal = confinementRoot\n }\n // Tracks every directory's real path, symlinked or not: a symlink into an\n // ancestor (or two symlinks pointing at each other) must not recurse\n // forever, and this also cheaply dedupes reaching the same real directory\n // through two different symlinks.\n const visitedRealPaths = new Set<string>()\n // `directory` is the real, physical path a symlink was already resolved\n // to (used for readdirSync/realpathSync); `logicalDirectory` is the path\n // as seen through the symlink from `root` (used only for `relativePath`,\n // so a page inside a symlinked submodule gets a sensible id like\n // `core/overview` instead of a `../../..`-laden physical path).\n function visit(directory: string, logicalDirectory: string = directory): void {\n if (files.length >= walkCap) return\n let directoryReal: string\n try {\n directoryReal = realpathSync(directory)\n } catch {\n return\n }\n if (visitedRealPaths.has(directoryReal)) return\n visitedRealPaths.add(directoryReal)\n let entries: Array<Dirent>\n try {\n entries = readdirSync(directory, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (files.length >= walkCap) return\n if (isIgnoredContentDirectory(entry.name)) {\n // Still skipped (`.git`, `node_modules`, ...) — but never silently:\n // warn if it turns out to hold real pages, since that's exactly the\n // shape of bug this content root is supposed to be free of.\n if (warnings && entry.isDirectory() && !entry.isSymbolicLink()\n && containsMarkdown(resolveWithin(directory, entry.name))) {\n warnings.push({\n code: 'unsupported-config',\n message: `The \"${entry.name}\" directory was skipped during migration but contains Markdown/MDX files; if any are real pages, move them out or pass --docs-dir to include them.`,\n source: relative(root, resolveWithin(directory, entry.name)).replace(/\\\\/g, '/'),\n })\n }\n continue\n }\n const path = resolveWithin(directory, entry.name)\n const logicalPath = resolveWithin(logicalDirectory, entry.name)\n if (entry.isSymbolicLink()) {\n let real: string\n try {\n real = realpathSync(path)\n } catch {\n continue // A broken symlink (e.g. an uninitialized submodule) has nothing to walk.\n }\n const withinConfinement = real === confinementReal || real.startsWith(`${confinementReal}${sep}`)\n if (!withinConfinement) continue\n let target: ReturnType<typeof statSync>\n try {\n target = statSync(real)\n } catch {\n continue\n }\n if (target.isDirectory()) visit(real, logicalPath)\n else if (target.isFile()) files.push({ absolutePath: real, relativePath: relative(root, logicalPath).replace(/\\\\/g, '/') })\n continue\n }\n if (entry.isDirectory()) visit(path, logicalPath)\n else if (entry.isFile()) files.push({ absolutePath: path, relativePath: relative(root, logicalPath).replace(/\\\\/g, '/') })\n }\n }\n visit(root)\n if (rank && files.length >= walkCap) {\n warnings?.push({\n code: 'limit-reached',\n message: `Stopped scanning after ${walkCap} files, so the rest of the repository was not looked at. Run the migration on a smaller part of the repository with --docs-dir.`,\n })\n }\n return files\n}\n\n/**\n * Applies the `MAX_SOURCE_FILES` budget to one homogeneous group (either\n * documentation pages or assets — see `selectFilesWithinBudget`), keeping\n * the highest-priority files and emitting one warning naming how many were\n * dropped and — for Mintlify — which versions they belonged to.\n */\nfunction selectGroupWithinBudget(\n scanned: Array<ScannedFile>,\n rank: (relativePath: string) => number,\n warnings: Array<MigrationWarning> | undefined,\n allVersionPrefixes: ReadonlySet<string>,\n label: 'file' | 'asset',\n): Array<ScannedFile> {\n if (scanned.length <= MAX_SOURCE_FILES) return scanned\n // Ties (unreferenced files sharing a ceiling) break by path, not by\n // directory-listing order, so the same repository always keeps the same files.\n const ranked = scanned\n .map((file) => ({ file, priority: rank(file.relativePath) }))\n .sort((left, right) => left.priority - right.priority\n || (left.file.relativePath < right.file.relativePath ? -1 : left.file.relativePath > right.file.relativePath ? 1 : 0))\n const dropped = ranked.slice(MAX_SOURCE_FILES).map(({ file }) => file)\n if (warnings) {\n const droppedPages = label === 'file' ? dropped.filter((file) => isDocumentationExtension(file.relativePath)) : dropped\n const noun = label === 'file' ? 'page' : 'image or media file'\n const droppedVersions = new Set<string>()\n for (const file of dropped) {\n const firstSegment = file.relativePath.split('/', 1)[0]\n if (allVersionPrefixes.has(firstSegment)) droppedVersions.add(firstSegment)\n }\n const examples = droppedPages.slice(0, 3).map((file) => file.relativePath)\n const rest = droppedPages.length - examples.length\n warnings.push({\n code: 'limit-reached',\n message: `This repository has more than ${MAX_SOURCE_FILES} ${label === 'file' ? 'files' : 'assets'}, so only the first ${MAX_SOURCE_FILES} (in navigation order, default version first) were migrated. `\n + `${droppedPages.length} ${noun}(s) were left out`\n + (examples.length > 0 ? `: ${examples.join(', ')}${rest > 0 ? `, and ${rest} more` : ''}` : '')\n + (droppedVersions.size > 0 ? ` (versions: ${[...droppedVersions].slice(0, 5).join(', ')}${droppedVersions.size > 5 ? `, and ${droppedVersions.size - 5} more` : ''})` : '')\n + (label === 'file'\n ? '. To include them, run the migration on a smaller part of the repository with --docs-dir.'\n : '. Copy them into public/ manually if your pages use them.'),\n })\n }\n return ranked.slice(0, MAX_SOURCE_FILES).map(({ file }) => file)\n}\n\n/**\n * When a `scanFiles` walk (run with a `rank` function) found more than\n * `MAX_SOURCE_FILES` files, keep the highest-priority files and drop the\n * rest. `rank` comes from `referenceOrder` (navigation traversal order:\n * default version before non-default, newest non-default before older, per\n * `projectMintlifyNavigation`'s version sort), so referenced pages always\n * win over unreferenced ones, and within referenced pages the default\n * version's own pages always win over other versions'.\n *\n * Assets get their own `MAX_SOURCE_FILES` budget, separate from pages: a\n * repository with more than `MAX_SOURCE_FILES` navigation-referenced pages\n * (e.g. crewAI's ~40 Mintlify versions) would otherwise fill the entire\n * shared budget with pages before a single image is ever considered,\n * since `rank` only orders *pages* (assets always sort last, at\n * `Number.MAX_SAFE_INTEGER` — see `discoveryRank` in `migrateRepository`)\n * — starving every asset even though the asset budget\n * (`MAX_ASSET_BYTES`/`MAX_TOTAL_ASSET_BYTES`) was never reached.\n */\nfunction selectFilesWithinBudget(\n scanned: Array<ScannedFile>,\n rank: (relativePath: string) => number,\n warnings: Array<MigrationWarning> | undefined,\n allVersionPrefixes: ReadonlySet<string>,\n): Array<ScannedFile> {\n const isAsset = (file: ScannedFile): boolean => ASSET_EXTENSIONS.has(extname(file.relativePath).toLowerCase())\n const assetFiles = scanned.filter(isAsset)\n const otherFiles = scanned.filter((file) => !isAsset(file))\n return [\n ...selectGroupWithinBudget(otherFiles, rank, warnings, allVersionPrefixes, 'file'),\n ...selectGroupWithinBudget(assetFiles, rank, warnings, allVersionPrefixes, 'asset'),\n ]\n}\n\n/**\n * Mintlify excludes paths from the docs site with a gitignore-style\n * `.mintignore` at the project root (see Mintlify's docs). Honoring it keeps\n * internal tooling directories like `agent-context/` out of the migration\n * even though they aren't dotfile directories.\n */\nfunction readMintignoreMatcher(mintlifyRoot: string): IgnoreMatcher | null {\n const path = resolveWithin(mintlifyRoot, MINTIGNORE_FILENAME)\n if (!existsSync(path) || !lstatSync(path).isFile()) return null\n return createIgnoreMatcher().add(readFileSync(path, 'utf8'))\n}\n\n/**\n * Compile-check a page body with the same MDX compiler the scaffold's\n * runtime build uses (`@mdx-js/mdx`). A single malformed page must never\n * abort `scripts/build-runtime-sources.mts` for the whole project, so\n * migration excludes it up front instead and reports why.\n */\nfunction invalidMdxReason(body: string): string | null {\n try {\n compileSync(body, { outputFormat: 'program' })\n return null\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i\n\n/** Extract Mintlify's `colors.{primary,light,dark}` theme hexes, if valid. */\nfunction mintlifyThemeColors(value: unknown): { primary?: string; light?: string; dark?: string } | undefined {\n if (!value || typeof value !== 'object') return undefined\n const source = value as Record<string, unknown>\n const colors: { primary?: string; light?: string; dark?: string } = {}\n for (const key of ['primary', 'light', 'dark'] as const) {\n if (typeof source[key] === 'string' && HEX_COLOR.test(source[key])) colors[key] = source[key]\n }\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\n/**\n * Extract Fern's `colors.accent-primary` (a hex string, or `{light, dark}`),\n * if valid. Fern's `light`/`dark` are normal (each names the mode it\n * paints), unlike Mintlify's inverted schema that `site.colors` otherwise\n * follows, so they're swapped onto Mintlify's `{light, dark}` keys here to\n * give downstream consumers (`updateSiteConfig`) one consistent contract.\n */\nfunction fernThemeColors(value: unknown): { primary?: string; light?: string; dark?: string } | undefined {\n if (!value || typeof value !== 'object') return undefined\n const accent = (value as Record<string, unknown>)['accent-primary']\n if (typeof accent === 'string') return HEX_COLOR.test(accent) ? { primary: accent } : undefined\n if (!accent || typeof accent !== 'object') return undefined\n const source = accent as Record<string, unknown>\n const lightMode = typeof source.light === 'string' && HEX_COLOR.test(source.light) ? source.light : undefined\n const darkMode = typeof source.dark === 'string' && HEX_COLOR.test(source.dark) ? source.dark : undefined\n const colors: { light?: string; dark?: string } = {}\n if (darkMode) colors.light = darkMode\n if (lightMode) colors.dark = lightMode\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\nfunction normalizedReferenceKey(value: string): string {\n return value.split(/[?#]/, 1)[0]\n .replace(/^\\/+/, '')\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:mdx?|rst|txt)$/i, '')\n .replace(/\\/(?:index|readme)$/i, '')\n .replace(/^(?:index|readme)$/i, '') || 'introduction'\n}\n\nfunction exactReferenceKey(value: string): string {\n return value.split(/[?#]/, 1)[0]\n .replace(/^\\/+/, '')\n .replace(/\\\\/g, '/')\n .replace(/\\.(?:mdx?|rst|txt)$/i, '')\n}\n\nfunction findOpenApi(files: Array<ScannedFile>): ScannedFile | null {\n return files.find((file) => OPENAPI_FILENAMES.has(basename(file.relativePath).toLowerCase())\n && classifyApiSpec(file.absolutePath) === 'openapi') ?? null\n}\n\n/** A familiar filename is insufficient: Fern repositories also keep AsyncAPI there. */\nfunction classifyApiSpec(path: string): 'openapi' | 'asyncapi' | 'unknown' {\n const buffer = Buffer.alloc(64_000)\n let bytesRead = 0\n try {\n const descriptor = openSync(path, 'r')\n try {\n bytesRead = readSync(descriptor, buffer, 0, buffer.length, 0)\n } finally {\n closeSync(descriptor)\n }\n } catch {\n return 'unknown'\n }\n const text = buffer.toString('utf8', 0, bytesRead)\n const topLevel = text.match(/^(?:openapi|swagger|asyncapi)\\s*:/m)?.[0]\n ?? text.match(/^\\s*\\{\\s*\"(?:openapi|swagger|asyncapi)\"\\s*:/m)?.[0]\n if (!topLevel) return 'unknown'\n return /asyncapi/i.test(topLevel) ? 'asyncapi' : 'openapi'\n}\n\n/** An OpenAPI/AsyncAPI spec resolved and ready to copy into `public/`, optionally bound to one tab. */\ninterface ResolvedApiSpec {\n filename: string\n content: Buffer\n tabLabel?: string\n /** Repository-relative path the spec was read from, used only to disambiguate a basename collision across tabs. */\n sourcePath: string\n /** Mintlify's object-form `{ source, directory }` scoping directory, if any — the prefix its auto-generated operation pages live under. */\n directory?: string\n}\n\nfunction mintlifyTopLevelApiReferences(config: Record<string, unknown> | null): Array<MintlifyApiSpecReference> {\n const api = config?.api && typeof config.api === 'object' && !Array.isArray(config.api)\n ? config.api as Record<string, unknown>\n : null\n if (!api) return []\n const references: Array<MintlifyApiSpecReference> = []\n for (const kind of ['openapi', 'asyncapi'] as const) {\n const value = api[kind]\n const values = typeof value === 'string'\n ? [value]\n : Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n for (const entry of values) references.push({ value: entry, kind })\n }\n return references\n}\n\n/**\n * Resolve every OpenAPI/AsyncAPI reference in a Mintlify config — the\n * top-level `api.openapi`/`api.asyncapi` plus every per-tab/group/anchor\n * `openapi`/`asyncapi` field in `navigation` — into copyable spec bytes\n * bound to the tab that referenced them. AsyncAPI has no Thally renderer,\n * so it only ever produces a warning naming the spec. A remote `https://`\n * reference is skipped with an actionable warning until the downloader can\n * validate the connected address on every request, including redirects.\n * Missing local files also produce warnings rather than disappearing.\n */\nfunction resolveMintlifyApiSpecs(\n mintlifyConfig: Record<string, unknown> | null,\n files: Array<ScannedFile>,\n warnings: Array<MigrationWarning>,\n remoteSpecs: Array<{ url: string; tabLabel?: string }>,\n): Array<ResolvedApiSpec> {\n if (!mintlifyConfig) return []\n const references = [\n ...mintlifyTopLevelApiReferences(mintlifyConfig),\n ...mintlifyNavigationApiReferences(mintlifyConfig),\n ]\n const seen = new Set<string>()\n const specs: Array<ResolvedApiSpec> = []\n for (const reference of references) {\n const dedupeKey = `${reference.kind}:${reference.value}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n const tabSuffix = reference.tabLabel ? ` (tab \"${reference.tabLabel}\")` : ''\n if (reference.kind === 'asyncapi') {\n warnings.push({\n code: 'unsupported-config',\n message: `AsyncAPI is not supported by Thally's API reference; the spec \"${reference.value}\"${tabSuffix} was not migrated.`,\n })\n continue\n }\n if (/^https:\\/\\//i.test(reference.value)) {\n remoteSpecs.push({ url: reference.value, ...(reference.tabLabel ? { tabLabel: reference.tabLabel } : {}) })\n warnings.push({\n code: 'unsupported-config',\n message: `The remote OpenAPI spec \"${reference.value}\"${tabSuffix} requires a network download before this import is complete.`,\n source: reference.value,\n })\n continue\n }\n if (/^http:\\/\\//i.test(reference.value)) {\n warnings.push({ code: 'unsupported-config', message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} uses insecure HTTP and was not imported.`, source: reference.value })\n continue\n }\n const key = reference.value.split(/[?#]/, 1)[0].replace(/^\\/+/, '').replace(/\\\\/g, '/')\n const match = files.find((file) => file.relativePath === key)\n if (!match) {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} could not be found in the repository and was not migrated.`,\n })\n continue\n }\n if (reference.directory) {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec \"${reference.value}\"${tabSuffix} was limited to pages under \"${reference.directory}\" in the source, but Thally's API reference always covers a whole tab, so it was migrated as the tab's full API reference. Update any links to \"${reference.directory}/...\" pages manually.`,\n })\n }\n specs.push({\n filename: basename(match.relativePath),\n content: readFileSync(match.absolutePath),\n tabLabel: reference.tabLabel,\n sourcePath: match.relativePath,\n directory: reference.directory,\n })\n }\n // Two specs bound to *different* tabs can share a basename (e.g.\n // \"qstash/openapi.yaml\" and \"workflow/openapi.yaml\" both resolve to\n // \"openapi.yaml\") — without disambiguation the second spec's asset\n // write collides with the first's, silently discarding its content\n // even though both tabs believe they have a working spec bound. Specs\n // that land on the *same* tab are left alone: only one of them ever\n // gets bound (see injectOpenApiSpecs's \"already has an OpenAPI spec\"\n // warning), so renaming there would produce an asset nothing points to.\n const filenameOwners = new Map<string, string>()\n for (const spec of specs) {\n const groupKey = spec.tabLabel ?? '\\0default'\n const owner = filenameOwners.get(spec.filename)\n if (owner !== undefined && owner !== groupKey) {\n let disambiguated = spec.sourcePath.replace(/\\//g, '-')\n while (filenameOwners.has(disambiguated) && filenameOwners.get(disambiguated) !== groupKey) {\n disambiguated = `${groupKey.replace(/\\W+/g, '-')}-${disambiguated}`\n }\n spec.filename = disambiguated\n }\n filenameOwners.set(spec.filename, groupKey)\n }\n return specs\n}\n\nconst OPENAPI_HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']\n\n/** NestJS's conventional CRUD controller method names, mapped to the REST-conventional slug Fern renders them under (confirmed against a live site). */\nconst FERN_CRUD_METHOD_NAMES: Record<string, string> = {\n findall: 'list',\n findone: 'get',\n remove: 'delete',\n}\n\n/** Kebab-case a label the way Mintlify slugs its auto-generated OpenAPI operation pages (tag folder, operation leaf). */\nfunction mintlifyOperationSlugSegment(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')\n}\n\n/**\n * Thally's own API operation route segment: path segments (braces stripped)\n * plus the HTTP method — never the summary. Mirrors `buildSlugSegments` in\n * src/lib/openapi/normalize.ts; duplicated rather than imported because\n * packages/migrate cannot depend on the Next.js app. Ceiling: webhook\n * operations (`x-webhooks`) aren't covered — normalize.ts prefixes those\n * with \"webhooks\", update this alongside it if that ever matters here.\n */\nexport function thallyOperationSlugSegments(path: string, method: string): Array<string> {\n const cleaned = path\n .split('/')\n .filter(Boolean)\n .map((segment) => segment.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9-]/g, '-').replace(/-+/g, '-').toLowerCase())\n if (!cleaned.length) cleaned.push('root')\n cleaned.push(method.toLowerCase())\n return cleaned\n}\n\n/** Mirrors `slugifyId` in src/data/docs.ts, which turns a tab label into its API spec id. */\nfunction slugifyApiSpecId(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9/]+/g, '-').replace(/(^-|-$)+/g, '').replace(/\\//g, '-') || value.toLowerCase()\n}\n\ninterface OpenApiOperationForLinking {\n method: string\n path: string\n tag?: string\n summary?: string\n operationId?: string\n}\n\n/** Read just enough of an OpenAPI document to match Mintlify's auto-generated operation pages. Malformed input yields no operations rather than throwing. */\nfunction parseOpenApiOperationsForLinking(content: Buffer): Array<OpenApiOperationForLinking> {\n let document: unknown\n try {\n document = parseYaml(content.toString('utf8'))\n } catch {\n return []\n }\n const paths = document && typeof document === 'object' ? (document as Record<string, unknown>).paths : null\n if (!paths || typeof paths !== 'object') return []\n const operations: Array<OpenApiOperationForLinking> = []\n for (const [path, pathItem] of Object.entries(paths as Record<string, unknown>)) {\n if (!pathItem || typeof pathItem !== 'object') continue\n for (const method of OPENAPI_HTTP_METHODS) {\n const operation = (pathItem as Record<string, unknown>)[method]\n if (!operation || typeof operation !== 'object') continue\n const op = operation as Record<string, unknown>\n const tags = Array.isArray(op.tags) ? op.tags.filter((tag): tag is string => typeof tag === 'string') : []\n operations.push({\n method,\n path,\n tag: tags[0],\n summary: typeof op.summary === 'string' ? op.summary : undefined,\n operationId: typeof op.operationId === 'string' ? op.operationId : undefined,\n })\n }\n }\n return operations\n}\n\n/**\n * Map Mintlify's auto-generated operation page path (e.g.\n * \"qstash/api-reference/messages/publish-a-message\", from the `directory`\n * an object-form `openapi: { source, directory }` reference scoped its\n * pages under) to Thally's actual operation route\n * (`/api/<specId>/<method+path slug>`), so in-content links to those\n * Mintlify-only pages can be rewritten instead of staying broken.\n *\n * `specId` mirrors buildApiReferenceConfig in src/config/api-reference.ts:\n * the first non-hidden tab with a bound spec is `'default'`, every other\n * one is keyed by its own tab id. Ceiling: matches by tag + (summary,\n * operationId, or \"method path\"), the same fields Mintlify's generator\n * itself falls back through — an operation whose tag Mintlify computed\n * differently still won't resolve, and stays a broken link as before.\n */\n/** A spec bound to a tab, plus the source-platform's own route prefix its auto-generated operation pages live under (Mintlify's `directory`, Fern's section route). */\ninterface ApiOperationLinkSource {\n filename: string\n content: Buffer\n /** Prefix path segment(s) the source platform served its auto-generated operation pages under (no leading/trailing slash); absent or empty means \"no known auto-generated prefix for this spec\" and it's skipped. */\n prefix?: string\n}\n\ninterface ApiOperationLinkMaps {\n /** Exact source-platform operation-page path (lowercased) -> Thally operation route. */\n operationLinks: Map<string, string>\n /**\n * Source-platform API-section route prefix (lowercased, no leading/trailing\n * slash) -> that spec's Thally landing route (`/api` for the first spec,\n * `/api/<specId>` for the rest). Used both for a bare tab-landing link\n * (the prefix on its own) and as the fallback for an operation link under\n * this prefix that didn't match any known operation.\n */\n prefixLandings: Map<string, string>\n}\n\nfunction apiOperationLinkMap(\n sources: Array<ApiOperationLinkSource>,\n docsConfig: MigrationDocsConfig,\n): ApiOperationLinkMaps {\n const map = new Map<string, string>()\n const prefixLandings = new Map<string, string>()\n const apiTabs = docsConfig.tabs.filter((tab) => !tab.hidden && tab.api)\n apiTabs.forEach((tab, index) => {\n const source = sources.find((entry) => tab.api?.source === `/${entry.filename}`)\n if (!source || !source.prefix) return\n const specId = index === 0 ? 'default' : slugifyApiSpecId(tab.tab)\n const prefix = source.prefix.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n if (prefix) prefixLandings.set(prefix, specId === 'default' ? '/api' : `/api/${specId}`)\n for (const operation of parseOpenApiOperationsForLinking(source.content)) {\n const thallyHref = `/api/${specId}/${thallyOperationSlugSegments(operation.path, operation.method).join('/')}`\n // Leaf candidates, tried in order of how likely a source generator is\n // to have used them: Mintlify slugs from the summary; Fern instead\n // prefers an SDK-style method name — confirmed against a live Fern\n // site, where `operationId: \"ToolController_create\"` (summary\n // \"Create Tool\") rendered its page at \".../tools/create\", the\n // operationId's segment after its last \"_\"/\".\", not the summary.\n const leafCandidates = new Set<string>()\n if (operation.operationId) {\n const parts = operation.operationId.split(/[_.]/).filter(Boolean)\n const lastPart = parts.at(-1) ?? operation.operationId\n // A NestJS-style controller method name (findOne/findAll/remove) is\n // common enough in real OpenAPI generators that Fern renders it\n // under its REST-conventional name instead — also confirmed live:\n // \"CallController_findOne\" rendered at \".../calls/get\", not\n // \".../calls/find-one\".\n const conventional = FERN_CRUD_METHOD_NAMES[lastPart.toLowerCase()]\n if (conventional) leafCandidates.add(conventional)\n leafCandidates.add(mintlifyOperationSlugSegment(lastPart))\n }\n if (operation.summary) leafCandidates.add(mintlifyOperationSlugSegment(operation.summary))\n if (operation.operationId) leafCandidates.add(mintlifyOperationSlugSegment(operation.operationId))\n leafCandidates.add(mintlifyOperationSlugSegment(`${operation.method} ${operation.path}`))\n // Two prefix conventions get registered for every leaf candidate:\n // Mintlify nests auto-generated pages under a tag folder\n // (\"<prefix>/<tag>/<leaf>\"); Fern's default layout serves them flat\n // under the section route (\"<prefix>/<leaf>\") instead. Registering\n // every combination costs nothing (an operation matches at most one\n // of them in practice) and avoids guessing which convention and\n // which leaf a given source actually used.\n const tagSegment = mintlifyOperationSlugSegment(operation.tag ?? 'default')\n for (const leaf of leafCandidates) {\n if (!leaf) continue\n const tagged = `${source.prefix}/${tagSegment}/${leaf}`.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n const flat = `${source.prefix}/${leaf}`.replace(/^\\/+|\\/+$/g, '').toLowerCase()\n if (!map.has(tagged)) map.set(tagged, thallyHref)\n if (!map.has(flat)) map.set(flat, thallyHref)\n }\n }\n })\n return { operationLinks: map, prefixLandings }\n}\n\n/** Rewrite API operation links in every page body, with one capped warning for links that matched no operation. */\nfunction rewriteApiLinksInPages(\n pages: Array<MigrationPage>,\n operationLinks: Map<string, string>,\n prefixLandings: Map<string, string>,\n warnings: Array<MigrationWarning>,\n): void {\n if (operationLinks.size === 0 && prefixLandings.size === 0) return\n const unmatched = new Set<string>()\n for (const page of pages) {\n page.body = rewriteApiOperationLinks(page.body, operationLinks, prefixLandings, unmatched)\n }\n if (unmatched.size === 0) return\n const sorted = [...unmatched].sort()\n warnings.push({\n code: 'unsupported-config',\n message: `${sorted.length} link(s) to API endpoints matched no endpoint in the OpenAPI spec, so they now point to the API section's overview page instead: `\n + `${sorted.slice(0, 10).join(', ')}${sorted.length > 10 ? `, and ${sorted.length - 10} more` : ''}. Update those links if you want them to reach a specific endpoint.`,\n })\n}\n\n/**\n * Rewrite in-content links matching a source platform's auto-generated\n * OpenAPI operation pages to Thally's actual `/api/...` routes. A link\n * that is exactly a known API-section prefix (a bare tab-landing link, e.g.\n * \"/api-reference\") is rewritten to that spec's Thally landing route. A\n * link under a known prefix that doesn't match any specific operation\n * (renamed/removed operation, or a match this rewrite's heuristics missed)\n * falls back to the same landing route rather than staying broken, and its\n * original target is recorded into `unmatched` so the caller can emit one\n * aggregated warning instead of one per link. Links outside every known\n * prefix are left untouched — still broken, but no worse than before this\n * rewrite existed.\n */\nfunction rewriteApiOperationLinks(\n body: string,\n linkMap: Map<string, string>,\n prefixLandings: Map<string, string>,\n unmatched: Set<string>,\n): string {\n if (linkMap.size === 0 && prefixLandings.size === 0) return body\n // Longest prefix first, so a more specific API section (e.g.\n // \"api-reference/webhooks\") is preferred over a shorter one that happens\n // to also match (\"api-reference\").\n const orderedPrefixes = [...prefixLandings.entries()].sort((a, b) => b[0].length - a[0].length)\n let codeFence: string | null = null\n return body.split('\\n').map((line) => {\n const fence = line.match(/^\\s*(`{3,}|~{3,})/)\n if (fence) {\n if (!codeFence) codeFence = fence[1][0]\n else if (fence[1][0] === codeFence) codeFence = null\n return line\n }\n if (codeFence) return line\n const rewriteTarget = (target: string): string => {\n const suffixIndex = target.search(/[?#]/)\n const path = (suffixIndex >= 0 ? target.slice(0, suffixIndex) : target).replace(/^\\/+/, '').toLowerCase()\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n const mapped = linkMap.get(path)\n if (mapped) return `${mapped}${suffix}`\n for (const [prefix, landing] of orderedPrefixes) {\n if (path === prefix) return `${landing}${suffix}`\n if (path.startsWith(`${prefix}/`)) {\n unmatched.add(target)\n return `${landing}${suffix}`\n }\n }\n return target\n }\n return line\n .replace(/(\\]\\()\\/([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(`/${target}`)}`)\n .replace(/(\\bhref=\")\\/([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(`/${target}`)}${suffix}`)\n }).join('\\n')\n}\n\nconst MAX_FERN_GENERATORS_BYTES = 2_000_000\n\nfunction fernGeneratorsOpenApiPaths(config: Record<string, unknown>): Array<string> {\n const api = config.api\n if (typeof api === 'string') return [api]\n if (!api || typeof api !== 'object' || Array.isArray(api)) return []\n const specs = (api as Record<string, unknown>).specs\n if (!Array.isArray(specs)) return []\n return specs.flatMap((spec) => {\n if (typeof spec === 'string') return [spec]\n if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return []\n const openapi = (spec as Record<string, unknown>).openapi\n return typeof openapi === 'string' ? [openapi] : []\n })\n}\n\n/**\n * Fern's `generators.yml` can also point an `api.specs[]` entry at an\n * AsyncAPI or OpenRPC document instead of OpenAPI. Thally's API reference\n * only renders OpenAPI, so these are named here purely to produce a\n * specific warning (`fernGeneratorsOpenApiPaths` above never returns them,\n * so without this they'd otherwise look like a missing spec).\n */\nfunction fernGeneratorsUnsupportedSpecPaths(config: Record<string, unknown>): Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> {\n const api = config.api\n if (!api || typeof api !== 'object' || Array.isArray(api)) return []\n const specs = (api as Record<string, unknown>).specs\n if (!Array.isArray(specs)) return []\n return specs.flatMap((spec): Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> => {\n if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return []\n const record = spec as Record<string, unknown>\n if (typeof record.asyncapi === 'string') return [{ kind: 'asyncapi', path: record.asyncapi }]\n if (typeof record.openrpc === 'string') return [{ kind: 'openrpc', path: record.openrpc }]\n return []\n })\n}\n\nfunction readFernGeneratorsConfig(path: string): Record<string, unknown> | null {\n if (!existsSync(path) || !lstatSync(path).isFile() || lstatSync(path).size > MAX_FERN_GENERATORS_BYTES) return null\n const parsed = parseYaml(readFileSync(path, 'utf8'))\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null\n}\n\n/**\n * Resolve the OpenAPI spec Fern's `generators.yml` configures for an API:\n * modern `api.specs[].openapi`, or the legacy top-level `api:` string.\n * Multi-API repos keep a `generators.yml` per API under `fern/apis/<name>/`;\n * single-API repos keep one at the Fern project root.\n *\n * The root `generators.yml` belongs to a *different* API only in a multi-API\n * repo, which Fern lays out under `fern/apis/`. So the root config is skipped\n * only when an explicit `api-name` is set AND a `fern/apis/` directory\n * exists; a single-API repo whose docs.yml still names its API keeps its tab.\n */\nfunction fernOpenApiCandidateDirs(fernRoot: string, apiName: string | undefined, apiNameExplicit: boolean): Array<string> {\n const candidateDirs: Array<string> = []\n if (apiName) {\n try {\n candidateDirs.push(resolveWithin(fernRoot, `apis/${apiName}`))\n } catch {\n // Not a safe relative path (e.g. a display label, not a folder name).\n }\n }\n const apisDir = resolvePath(fernRoot, 'apis')\n const multiApi = existsSync(apisDir) && lstatSync(apisDir).isDirectory()\n if (!apiNameExplicit || !multiApi) candidateDirs.push(fernRoot)\n return candidateDirs\n}\n\n/** `findFernConfiguredOpenApi`'s result, plus any AsyncAPI/OpenRPC specs seen along the way (Thally has no renderer for either). */\ninterface FernOpenApiResolution {\n spec: ScannedFile | null\n unsupported: Array<{ kind: 'asyncapi' | 'openrpc'; path: string }>\n}\n\nfunction findFernConfiguredOpenApi(\n fernRoot: string,\n repositoryDir: string,\n apiName: string | undefined,\n apiNameExplicit: boolean,\n warnings: Array<MigrationWarning>,\n): FernOpenApiResolution {\n const candidateDirs = fernOpenApiCandidateDirs(fernRoot, apiName, apiNameExplicit)\n const unsupported: Array<{ kind: 'asyncapi' | 'openrpc'; path: string }> = []\n for (const dir of candidateDirs) {\n let config: Record<string, unknown> | null = null\n let generatorsPath: string\n try {\n generatorsPath = resolveWithin(dir, 'generators.yml')\n config = readFernGeneratorsConfig(generatorsPath)\n } catch {\n continue\n }\n if (!config) continue\n for (const specPath of fernGeneratorsOpenApiPaths(config)) {\n if (/^(?:https?:)?\\/\\//i.test(specPath)) continue\n // `openapi:` in generators.yml is conventionally relative to that\n // file's own directory (a multi-API repo's `fern/apis/<name>/`), not\n // to the Fern root, so it commonly points outside `dir` (e.g. Cohere's\n // `../../../cohere-openapi.yaml`). The security boundary is still the\n // whole repository checkout, never anything above it.\n try {\n const absolute = resolveWithinRoot(dir, specPath, repositoryDir)\n if (!existsSync(absolute) || !lstatSync(absolute).isFile()) continue\n const kind = classifyApiSpec(absolute)\n if (kind === 'asyncapi') {\n unsupported.push({ kind: 'asyncapi', path: specPath })\n continue\n }\n if (kind !== 'openapi') continue\n return { spec: { absolutePath: absolute, relativePath: relative(repositoryDir, absolute).replace(/\\\\/g, '/') }, unsupported }\n } catch {\n warnings.push({\n code: 'unsupported-config',\n message: `The OpenAPI spec path \"${specPath}\" in ${relative(repositoryDir, generatorsPath).replace(/\\\\/g, '/')} is outside the repository and was skipped.`,\n })\n }\n }\n unsupported.push(...fernGeneratorsUnsupportedSpecPaths(config))\n }\n return { spec: null, unsupported }\n}\n\n/** Whether a Fern Definition (as opposed to a plain OpenAPI/AsyncAPI spec) backs this API. */\nfunction fernDefinitionExists(fernRoot: string, apiName: string | undefined): boolean {\n const candidateDirs: Array<string> = []\n if (apiName) {\n try {\n candidateDirs.push(resolveWithin(fernRoot, `apis/${apiName}/definition`))\n } catch {\n // Not a safe relative path; skip.\n }\n }\n try {\n candidateDirs.push(resolveWithin(fernRoot, 'definition'))\n } catch {\n // Unreachable: 'definition' is always a safe relative segment.\n }\n return candidateDirs.some((dir) => existsSync(dir) && lstatSync(dir).isDirectory())\n}\n\nfunction withoutFrontmatter(value: string): string {\n return value.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/, '').trim()\n}\n\nfunction staticSnippetProperties(attributes: string): Map<string, string> {\n const properties = new Map<string, string>()\n const matcher = /\\b([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{\\s*\"([^\"]*)\"\\s*\\}|\\{\\s*'([^']*)'\\s*\\})/g\n for (const match of attributes.matchAll(matcher)) {\n properties.set(match[1], match[2] ?? match[3] ?? match[4] ?? match[5] ?? '')\n }\n return properties\n}\n\nfunction interpolateSnippet(snippet: string, attributes: string, children?: string): string {\n const properties = staticSnippetProperties(attributes)\n if (children !== undefined) properties.set('children', children.trim())\n if (properties.size === 0) return snippet\n const isJsxSnippet = /<[A-Za-z][A-Za-z0-9]*/.test(snippet)\n let fence = ''\n return snippet.split('\\n').map((line) => {\n const marker = line.match(/^\\s*(`{3,}|~{3,})/)?.[1]\n if (marker) {\n if (!fence) fence = marker[0]\n else if (marker[0] === fence) fence = ''\n return line\n }\n if (fence) return line\n return line.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (original, name: string) => {\n const value = properties.get(name)\n // Preserve MDX expression syntax: a literal replacement inside JSX\n // would turn `<a href={url}>` into invalid `href=https://...`.\n if (value === undefined) return original\n if (name === 'children') return value\n return isJsxSnippet ? `{${JSON.stringify(value)}}` : value\n })\n }).join('\\n')\n}\n\n/** Extract JSX from a statically declared snippet component before inlining it. */\nfunction snippetComponentBody(source: string, componentName: string): string {\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== componentName) continue\n const initializer = declaration.initializer\n if (!initializer || !ts.isArrowFunction(initializer)) continue\n const returned = ts.isBlock(initializer.body)\n ? initializer.body.statements.find(ts.isReturnStatement)?.expression\n : initializer.body\n if (!returned) continue\n let expression: ts.Expression = returned\n while (ts.isParenthesizedExpression(expression)) expression = expression.expression\n if (ts.isJsxElement(expression) || ts.isJsxSelfClosingElement(expression) || ts.isJsxFragment(expression)) {\n return expression.getText(parsed)\n }\n }\n }\n return source\n}\n\n/** Keep a stateful snippet intact so its hooks and local values move with its JSX. */\nfunction statefulSnippetDeclaration(source: string, componentName: string): string | null {\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n // A snippet may declare helpers next to the component (a sibling component\n // it renders); the whole file travels so those stay declared on the page,\n // where the component migrator moves what the component needs. Anything\n // that is not plain ESM is prose, which cannot be preserved as a declaration.\n const isEsm = (statement: ts.Statement): boolean => ts.isImportDeclaration(statement)\n || (ts.isVariableStatement(statement) || ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement))\n && !!ts.getModifiers(statement as ts.HasModifiers)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)\n if (parsed.statements.length === 0 || !parsed.statements.every(isEsm)) return null\n const statement = parsed.statements.find((candidate) => ts.isVariableStatement(candidate)\n && candidate.declarationList.declarations.length === 1\n && ts.isIdentifier(candidate.declarationList.declarations[0].name)\n && candidate.declarationList.declarations[0].name.text === componentName)\n if (!statement || !ts.isVariableStatement(statement)) return null\n const declaration = statement.declarationList.declarations[0]\n if (!declaration.initializer || !ts.isArrowFunction(declaration.initializer)\n || !ts.isBlock(declaration.initializer.body)) return null\n const body = declaration.initializer.body.statements\n // A component with setup statements before its return cannot be flattened\n // to its returned JSX: that strands hooks, computed values, and handlers.\n if (body.length < 2 || !body.some(ts.isReturnStatement)) return null\n return source.trim()\n}\n\n/** Read only primitive named exports; source MDX is parsed, never executed. */\nfunction staticNamedSnippetValues(source: string): Map<string, string> {\n const values = new Map<string, string>()\n const parsed = ts.createSourceFile('snippet.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue\n const expression = declaration.initializer\n if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) {\n values.set(declaration.name.text, JSON.stringify(expression.text))\n } else if (ts.isNumericLiteral(expression)) {\n values.set(declaration.name.text, expression.text)\n } else if (expression.kind === ts.SyntaxKind.TrueKeyword || expression.kind === ts.SyntaxKind.FalseKeyword) {\n values.set(declaration.name.text, expression.kind === ts.SyntaxKind.TrueKeyword ? 'true' : 'false')\n }\n }\n }\n return values\n}\n\n/** MDX imports from nested Markdown partials must live at page scope. */\nfunction hoistMdxImports(source: string): string {\n const imports = new Set<string>()\n const withoutImports = replaceOutsideCode(source, (body) => body.replace(\n /^[ \\t]*import\\s+(?:\\{[^}\\n]+\\}|[A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])[^'\"\\n]+\\1[ \\t]*;?/gm,\n (statement: string) => {\n imports.add(statement.trim().replace(/;?$/, ';'))\n return ''\n },\n ))\n if (imports.size === 0) return source\n const frontmatter = withoutImports.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/)\n const prefix = frontmatter?.[0] ?? ''\n return `${prefix}${[...imports].join('\\n')}\\n\\n${withoutImports.slice(prefix.length).replace(/^(?:\\r?\\n)*/, '')}`\n}\n\n/** Fern can publish a repository beneath a domain path such as `/skills`. */\nfunction fernSourceBasePath(config: Record<string, unknown>): string {\n const instance = Array.isArray(config.instances) ? config.instances[0] : null\n if (!instance || typeof instance !== 'object' || Array.isArray(instance)) return ''\n const value = instance as Record<string, unknown>\n const address = typeof value['custom-domain'] === 'string' ? value['custom-domain'] : value.url\n if (typeof address !== 'string') return ''\n try {\n const path = new URL(/^https?:\\/\\//i.test(address) ? address : `https://${address}`).pathname.replace(/\\/+$/, '')\n return path === '/' ? '' : path\n } catch {\n return ''\n }\n}\n\n/** The imported Fern version's URL prefix is omitted from Thally's routes. */\nfunction fernDefaultVersionPath(config: Record<string, unknown>): string {\n if (!Array.isArray(config.versions)) return ''\n const versions = config.versions.filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object' && !Array.isArray(entry))\n const chosen = versions.find((version) => version.default === true) ?? versions[0]\n return typeof chosen?.slug === 'string' && /^[A-Za-z0-9_-]+$/.test(chosen.slug) ? `/${chosen.slug}` : ''\n}\n\n/** Preserve the published Fern host for references outside the imported pages. */\nfunction fernSourceSiteUrl(config: Record<string, unknown>): string | undefined {\n const instance = Array.isArray(config.instances) ? config.instances[0] : null\n if (!instance || typeof instance !== 'object' || Array.isArray(instance)) return undefined\n const value = instance as Record<string, unknown>\n const address = typeof value['custom-domain'] === 'string' ? value['custom-domain'] : value.url\n if (typeof address !== 'string') return undefined\n try {\n const url = new URL(/^https?:\\/\\//i.test(address) ? address : `https://${address}`)\n return `${url.origin}${fernSourceBasePath(config)}${fernDefaultVersionPath(config)}`\n } catch {\n return undefined\n }\n}\n\n/** Keep unresolved root-relative links usable on the source site, with an explicit warning. */\nfunction externalizeMissingFernLinks(body: string, pageIds: ReadonlySet<string>, sourceSiteUrl: string, externalized: Set<string>): string {\n const rewrite = (target: string): string => {\n const path = target.split(/[?#]/, 1)[0].replace(/^\\//, '').replace(/\\/$/, '')\n // Only unresolved page routes belong on the source site. Fern pages may\n // reference copied public assets with root-relative Markdown links; an\n // image or download is not a missing docs page.\n if (!path || pageIds.has(path) || ASSET_EXTENSIONS.has(extname(path).toLowerCase())) return target\n try {\n const base = new URL(`${sourceSiteUrl}/`)\n const sourceLinkUrl = new URL(target.slice(1), base)\n if (sourceLinkUrl.origin !== base.origin) return target\n const sourceLink = sourceLinkUrl.toString()\n externalized.add(target)\n return sourceLink\n } catch {\n return target\n }\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()\\/(?!\\/)([^\\s)]+)(\\))/g, (_match, before: string, target: string, after: string) => `${before}${rewrite(`/${target}`)}${after}`)\n .replace(/(\\b(?:href|to)=(['\"]))\\/(?!\\/)([^'\"\\n]+)\\2/g, (_match, before: string, quote: string, target: string) => `${before}${rewrite(`/${target}`)}${quote}`))\n}\n\n/** Rewrite only root-relative Markdown/JSX links, never URLs or code examples. */\nfunction stripFernBasePathFromLinks(body: string, basePath: string): string {\n if (!basePath) return body\n const escaped = basePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return replaceOutsideCode(body, (text) => text\n .replace(new RegExp(`(\\\\]\\\\()${escaped}(?=\\\\/|[)#?])`, 'g'), (match, prefix: string, offset: number, source: string) => (\n prefix + (source[offset + match.length] === '/' ? '' : '/')\n ))\n .replace(new RegExp(`(\\\\b(?:href|to)=[\"'])${escaped}(?=\\\\/|[\"'#?])`, 'g'), (match, prefix: string, offset: number, source: string) => (\n prefix + (source[offset + match.length] === '/' ? '' : '/')\n )))\n}\n\n/** Remove a published Mintlify mount path only when its destination is an imported page. */\nfunction rewriteMintlifyMountedLinks(body: string, pageIds: ReadonlySet<string>): string {\n const rewrite = (target: string): string => {\n const suffixAt = target.search(/[?#]/)\n const pathname = suffixAt < 0 ? target : target.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : target.slice(suffixAt)\n if (!pathname.startsWith('/') || pathname.startsWith('//') || pathname.includes('\\\\')) return target\n const segments = pathname.slice(1).split('/')\n if (segments.some((segment) => !segment || segment === '.' || segment === '..')) return target\n if (pageIds.has(segments.join('/'))) return target\n // A source site may serve its docs below /docs or another mount. Limit\n // removal to a leading path prefix and prove the remaining route exists;\n // this leaves real /docs pages and non-page assets untouched.\n for (let count = 1; count < segments.length && count <= 3; count++) {\n const candidate = segments.slice(count).join('/')\n if (pageIds.has(candidate)) return `/${candidate}${suffix}`\n }\n return target\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()(\\/[^\\s)]+)(\\))/g, (_match, before: string, target: string, after: string) => `${before}${rewrite(target)}${after}`)\n .replace(/(\\b(?:href|to)=(['\"]))(\\/[^'\"\\n]+)\\2/g, (_match, before: string, quote: string, target: string) => `${before}${rewrite(target)}${quote}`))\n}\n\n/** Preserve source fragments that resolve to a unique heading or table row. */\nfunction preserveLinkedAnchors(pages: Array<MigrationPage>): void {\n const pageById = new Map(pages.map((page) => [page.id, page]))\n const requested = new Map<string, Set<string>>()\n const crossPageRequests = new Set<string>()\n const addTarget = (target: string, currentId: string): void => {\n const hash = target.indexOf('#')\n if (hash < 0) return\n let fragment: string\n try { fragment = decodeURIComponent(target.slice(hash + 1)) } catch { return }\n // Only HTML-attribute-safe fragments can become explicit IDs. Encoded\n // fragments are common in exported docs, including names with `$`.\n if (!/^[\\p{L}\\p{N}_.:$-]{1,120}$/u.test(fragment)) return\n const path = target.slice(0, hash).split('?')[0]\n const id = target.startsWith('#') ? currentId : path.startsWith('/') && !path.startsWith('//')\n ? path.replace(/^\\//, '').replace(/\\/$/, '') || 'introduction' : ''\n if (!pageById.has(id)) return\n if (!requested.has(id)) requested.set(id, new Set())\n requested.get(id)!.add(fragment)\n if (id !== currentId) crossPageRequests.add(`${id}#${fragment}`)\n }\n for (const page of pages) {\n replaceOutsideCode(page.body, (text) => {\n for (const match of text.matchAll(/\\]\\(([^)\\s]+)\\)/g)) addTarget(match[1], page.id)\n for (const match of text.matchAll(/\\b(?:href|to)=(['\"])([^'\"\\n]+)\\1/g)) addTarget(match[2], page.id)\n return text\n })\n }\n const comparable = (value: string): string => value\n .replace(/&(?:lt|gt|amp|quot);/g, ' ')\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, '')\n for (const page of pages) {\n const fragments = requested.get(page.id)\n if (!fragments?.size) continue\n const lines = page.body.split('\\n')\n let fence: string | undefined\n const tableCells: Array<{ index: number; text: string }> = []\n const headings = lines.map((line, index) => {\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = undefined\n return null\n }\n if (fence) return null\n const tableCell = line.match(/^ {0,3}\\|\\s*([^|]+?)\\s*\\|/)\n if (tableCell && !/^[:\\s-]+$/.test(tableCell[1])) tableCells.push({ index, text: tableCell[1] })\n const match = line.match(/^ {0,3}#{1,6}\\s+(.+?)\\s*#*\\s*$/)\n return match ? { index, text: match[1] } : null\n }).filter((entry): entry is { index: number; text: string } => entry !== null)\n const existing = new Set<string>()\n replaceOutsideCode(page.body, (text) => {\n for (const match of text.matchAll(/\\bid=(?:\"([^\"]+)\"|'([^']+)')/g)) existing.add(match[1] ?? match[2])\n return text\n })\n const candidateIndexes = new Map<string, Array<{ index: number; kind: 'heading' | 'table' }>>()\n for (const heading of headings) {\n const key = comparable(heading.text)\n candidateIndexes.set(key, [...(candidateIndexes.get(key) ?? []), { index: heading.index, kind: 'heading' }])\n }\n for (const cell of tableCells) {\n const key = comparable(cell.text)\n candidateIndexes.set(key, [...(candidateIndexes.get(key) ?? []), { index: cell.index, kind: 'table' }])\n }\n for (const heading of headings) existing.add(heading.text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''))\n const headingAliases = new Map<number, Array<string>>()\n const tableAliases = new Map<number, Array<string>>()\n for (const fragment of fragments) {\n if (existing.has(fragment)) continue\n const matches = candidateIndexes.get(comparable(fragment)) ?? []\n let match = matches.length === 1 ? matches[0] : undefined\n if (!match && matches.length > 1 && !crossPageRequests.has(`${page.id}#${fragment}`)) {\n // Repeated option names can occur in several tables. A same-page\n // reference after one of them refers to the nearest preceding option;\n // only add an alias when every real local link agrees on that row.\n const escaped = fragment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const linkPattern = new RegExp(`\\\\]\\\\(#${escaped}\\\\)|\\\\b(?:href|to)=[\"']#${escaped}[\"']`)\n const linkIndexes = lines.flatMap((line, index) => linkPattern.test(line) ? [index] : [])\n const selections = linkIndexes.map((index) => matches.filter((candidate) => candidate.index < index).at(-1))\n if (selections.length && selections.every((candidate) => candidate?.index === selections[0]?.index)) match = selections[0]\n }\n if (!match) continue\n const { index, kind } = match\n const aliases = kind === 'heading' ? headingAliases : tableAliases\n aliases.set(index, [...(aliases.get(index) ?? []), fragment])\n existing.add(fragment)\n }\n if (headingAliases.size || tableAliases.size) page.body = lines.flatMap((line, index) => [\n ...(headingAliases.get(index) ?? []).map((fragment) => `<a id=\"${fragment}\"></a>`),\n tableAliases.has(index)\n ? line.replace(/^( {0,3}\\|\\s*)/, (prefix) => `${prefix}${tableAliases.get(index)!.map((fragment) => `<a id=\"${fragment}\"></a>`).join('')}`)\n : line,\n ]).join('\\n')\n }\n}\n\n/** Prevent an entry's EOF-terminated fence from swallowing the next feed entry. */\nfunction closeOpenCodeFence(body: string): string {\n let open: { marker: string; length: number } | null = null\n for (const line of body.split(/\\r?\\n/)) {\n const match = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)\n if (!match) continue\n const marker = match[1][0]\n if (!open) {\n open = { marker, length: match[1].length }\n } else if (marker === open.marker && match[1].length >= open.length && !match[2].trim()) {\n open = null\n }\n }\n return open ? `${body}\\n\\n${open.marker.repeat(open.length)}` : body\n}\n\n/** Fern changelog fragments prefix each article heading with its date. */\nfunction addDatedHeadingAliases(body: string, date: string): string {\n let open: { marker: string; length: number } | null = null\n const existingIds = new Set([...body.matchAll(/<a\\s+id=[\"']([^\"']+)[\"']/g)].map((match) => match[1]))\n return body.split(/\\r?\\n/).flatMap((line) => {\n const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/)\n if (fence) {\n const marker = fence[1][0]\n if (!open) open = { marker, length: fence[1].length }\n else if (marker === open.marker && fence[1].length >= open.length && !fence[2].trim()) open = null\n return [line]\n }\n if (open) return [line]\n const heading = line.match(/^#{2,6}\\s+(.+?)\\s*#*\\s*$/)\n if (!heading) return [line]\n const slug = heading[1]\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1')\n .replace(/[`*_]/g, '')\n .normalize('NFKD').toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s-]/gu, '')\n .trim().replace(/\\s+/g, '-')\n const id = `${date}-${slug}`\n if (!slug || existingIds.has(id)) return [line]\n existingIds.add(id)\n return [`<a id=\"${id}\" />`, '', line]\n }).join('\\n')\n}\n\nfunction resolveSnippetPath(\n sourcePath: string,\n currentFile: string,\n repositoryRoot: string,\n siteRoot: string,\n): string {\n // Markdown authors sometimes escape a leading underscore in an import\n // path; the repository filename itself is still unescaped.\n sourcePath = sourcePath.replace(/\\\\(?=_)/g, '')\n const repositoryRelative = sourcePath.startsWith('@site/')\n ? relative(repositoryRoot, resolveWithin(siteRoot, sourcePath.slice('@site/'.length))).replace(/\\\\/g, '/')\n : sourcePath.startsWith('/')\n ? relative(repositoryRoot, resolveWithin(siteRoot, sourcePath.replace(/^\\/+/, ''))).replace(/\\\\/g, '/')\n : relative(repositoryRoot, resolvePath(dirname(currentFile), sourcePath)).replace(/\\\\/g, '/')\n const candidate = resolveWithin(repositoryRoot, repositoryRelative)\n resolveWithin(repositoryRoot, relative(repositoryRoot, candidate))\n return candidate\n}\n\nfunction globalSnippetAliases(\n files: Array<ScannedFile>,\n repositoryRoot: string,\n siteRoot: string,\n): Map<string, string> {\n const aliases = new Map<string, string>()\n for (const file of files) {\n const segments = file.relativePath.split('/')\n if (!segments.some((segment) => SNIPPET_DIRECTORIES.has(segment.toLowerCase()))) continue\n const basenameWithoutExtension = basename(file.relativePath).replace(/\\.mdx?$/i, '')\n const conventionalAlias = basenameWithoutExtension\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n if (conventionalAlias) aliases.set(conventionalAlias, file.absolutePath)\n }\n for (const file of files) {\n if (!['.md', '.mdx'].includes(extname(file.relativePath).toLowerCase())) continue\n const raw = readFileSync(file.absolutePath, 'utf8')\n for (const match of raw.matchAll(SNIPPET_IMPORT_PATTERN)) {\n try {\n const componentName = match[1] ?? match[2]\n const candidate = resolveSnippetPath(match[3], file.absolutePath, repositoryRoot, siteRoot)\n if (existsSync(candidate) && lstatSync(candidate).isFile()) {\n aliases.set(componentName, candidate)\n }\n } catch {\n // The page-local inliner emits the actionable warning when it reaches\n // an unsafe or missing import. Global discovery is best-effort only.\n }\n }\n }\n return aliases\n}\n\nfunction repositoryAssetHref(\n value: string,\n currentFile: string,\n siteRoot: string,\n onReferenced?: (normalizedPath: string) => void,\n): string | null {\n const isBracketed = value.startsWith('<') && value.endsWith('>')\n const raw = isBracketed ? value.slice(1, -1) : value\n if (!raw || raw.startsWith('#') || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(raw)) return null\n const suffixIndex = raw.search(/[?#]/)\n const pathname = suffixIndex >= 0 ? raw.slice(0, suffixIndex) : raw\n const suffix = suffixIndex >= 0 ? raw.slice(suffixIndex) : ''\n let decodedPath: string\n try {\n decodedPath = decodeURIComponent(pathname)\n } catch {\n return null\n }\n if (!ASSET_EXTENSIONS.has(extname(decodedPath).toLowerCase())) return null\n try {\n const candidate = decodedPath.startsWith('/')\n ? resolveWithin(siteRoot, decodedPath.replace(/^\\/+/, ''))\n : resolveWithinRoot(dirname(currentFile), decodedPath, siteRoot)\n // Resolve every path component before accepting an asset. A repository\n // could contain a symlinked directory whose lexical path stays under\n // the docs root while its file contents live elsewhere on the host.\n const realRoot = realpathSync(siteRoot)\n const realCandidate = realpathSync(candidate)\n const realRelative = relative(realRoot, realCandidate)\n if (realRelative === '..' || realRelative.startsWith(`..${sep}`) || isAbsolute(realRelative)) return null\n // Mintlify's deploy root is the directory containing docs.json. Do not\n // copy or expose a relative reference that escapes that project boundary.\n const siteRelative = relative(siteRoot, candidate).replace(/\\\\/g, '/')\n resolveWithin(siteRoot, siteRelative)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) return null\n const normalized = normalizeAssetPath(siteRelative)\n if (!normalized) return null\n onReferenced?.(normalized)\n const rewritten = `/${normalized}${suffix}`\n // Markdown destinations containing parentheses must stay angle-bracketed;\n // removing the wrapper makes CommonMark terminate the URL too early.\n return isBracketed ? `<${rewritten}>` : rewritten\n } catch {\n return null\n }\n}\n\n/**\n * Rewrite links to a page whose Fern frontmatter `slug` replaced its docs.yml\n * hierarchy. Other pages still spell the link the \"natural\" nested way, so\n * this runs across every page's body, not just the renamed page's own.\n */\nfunction rewriteFernIdRenameLinks(body: string, renames: Map<string, string>): string {\n return replaceOutsideCode(body, (text) => {\n const rewriteTarget = (target: string): string => {\n const suffixIndex = target.search(/[?#]/)\n const path = (suffixIndex >= 0 ? target.slice(0, suffixIndex) : target).replace(/^\\/+/, '')\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n const renamed = renames.get(path)\n return renamed ? `/${renamed}${suffix}` : target\n }\n return text\n .replace(/(\\]\\()\\/([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(`/${target}`)}`)\n .replace(/(\\bhref=\")\\/([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(`/${target}`)}${suffix}`)\n })\n}\n\nfunction rewriteRepositoryAssetLinks(\n body: string,\n currentFile: string,\n siteRoot: string,\n onReferenced?: (normalizedPath: string) => void,\n): string {\n return body\n .replace(/(!?\\[[^\\]]*\\]\\()(<[^>]+>|[^)\\s]+)([^)]*\\))/g, (\n original,\n opening: string,\n destination: string,\n closing: string,\n ) => {\n const rewritten = repositoryAssetHref(destination, currentFile, siteRoot, onReferenced)\n return rewritten ? `${opening}${rewritten}${closing}` : original\n })\n .replace(/\\b(src|img|image|href)=(['\"])([^'\"]+)\\2/g, (\n original,\n property: string,\n quote: string,\n destination: string,\n ) => {\n const rewritten = repositoryAssetHref(destination, currentFile, siteRoot, onReferenced)\n return rewritten ? `${property}=${quote}${rewritten}${quote}` : original\n })\n}\n\nconst LOCAL_EXPORT_DECLARATION = /^\\s*export\\s+(?:const|let|var|function|class|async\\s+function)\\s+([A-Za-z_$][\\w$]*)/\n\n/**\n * Names a page declares itself with a top-level `export const/function/class`.\n * Mintlify treats every file under `/snippets/` as an implicitly available\n * global component keyed by its filename, so a page that happens to declare\n * an inline component with the same name (e.g. both `snippets/counter.mdx`\n * and a page's own `export const Counter = ...`) must keep its local\n * declaration: forcing the unrelated global snippet's source in over a\n * `<Counter />` usage duplicates the export and breaks the compiled module.\n */\nfunction locallyDeclaredNames(raw: string): Set<string> {\n const names = new Set<string>()\n let codeFence: string | null = null\n for (const line of raw.split('\\n')) {\n const codeMatch = line.match(/^\\s*(`{3,}|~{3,})/)\n if (codeMatch) {\n if (!codeFence) codeFence = codeMatch[1][0]\n else if (codeMatch[1][0] === codeFence) codeFence = null\n continue\n }\n if (codeFence) continue\n const declared = line.match(LOCAL_EXPORT_DECLARATION)?.[1]\n if (declared) names.add(declared)\n }\n return names\n}\n\nfunction inlineMdxSnippets(\n raw: string,\n currentFile: string,\n repositoryRoot: string,\n warnings: Array<MigrationWarning>,\n depth = 0,\n siteRoot = repositoryRoot,\n globalAliases: Map<string, string> = new Map(),\n): string {\n if (depth >= 8) return raw\n // Hoisting page imports must see indented JSX code examples as fenced code.\n // Otherwise imports shown in translated <Step> examples become live MDX\n // imports, disappear from the example, and can break the server build.\n raw = normalizeIndentedFences(raw)\n const snippets = new Map<string, string>()\n const preservedDeclarations = new Map<string, string>()\n let withoutImports = replaceOutsideCode(raw, (source) => source.replace(\n SNIPPET_IMPORT_PATTERN,\n (_statement, namedComponent: string | undefined, defaultComponent: string | undefined, sourcePath: string) => {\n const componentName = (namedComponent ?? defaultComponent) as string\n try {\n const candidate = resolveSnippetPath(sourcePath, currentFile, repositoryRoot, siteRoot)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) throw new Error('file not found')\n const nested = inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n const declaration = statefulSnippetDeclaration(nested, componentName)\n if (declaration) preservedDeclarations.set(componentName, declaration)\n else snippets.set(componentName, snippetComponentBody(nested, componentName))\n return ''\n } catch {\n warnings.push({\n code: 'missing-page',\n message: `Imported snippet ${sourcePath} could not be resolved and was left as a comment.`,\n source: relative(repositoryRoot, currentFile).replace(/\\\\/g, '/'),\n })\n snippets.set(componentName, `{/* Missing imported snippet: ${sourcePath} */}`)\n return ''\n }\n },\n ))\n withoutImports = replaceOutsideCode(withoutImports, (source) => source.replace(\n SNIPPET_VALUE_IMPORT_PATTERN,\n (statement: string, names: string, sourcePath: string) => {\n const bindings = names.split(',').map((name) => name.trim()).filter(Boolean).map((name) => {\n const parsed = name.match(/^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/)\n return parsed ? { exported: parsed[1], local: parsed[2] ?? parsed[1] } : null\n })\n if (bindings.length === 0 || bindings.some((binding) => !binding)) return statement\n try {\n const candidate = resolveSnippetPath(sourcePath, currentFile, repositoryRoot, siteRoot)\n if (!existsSync(candidate) || !lstatSync(candidate).isFile()) return statement\n const snippetSource = readFileSync(candidate, 'utf8')\n const values = staticNamedSnippetValues(snippetSource)\n const declarations: Array<string> = []\n const components: Array<[string, string]> = []\n for (const binding of bindings) {\n const value = values.get(binding!.exported)\n if (value !== undefined) {\n declarations.push(`export const ${binding!.local} = ${value};`)\n continue\n }\n if (!/^[A-Z]/.test(binding!.exported)) return statement\n const body = snippetComponentBody(snippetSource, binding!.exported)\n if (body === snippetSource) return statement\n components.push([binding!.local, body])\n }\n for (const [name, body] of components) snippets.set(name, body)\n return declarations.join('\\n')\n } catch {\n return statement\n }\n },\n ))\n // Mintlify resolves snippet imports across its MDX compilation graph. Some\n // real sites consequently reuse an alias on a page that does not repeat the\n // import declaration. Recover those aliases deterministically from imports\n // elsewhere in the same docs project.\n const localNames = locallyDeclaredNames(withoutImports)\n for (const [componentName, candidate] of globalAliases) {\n if (snippets.has(componentName) || localNames.has(componentName)\n || !new RegExp(`<${componentName}(?:\\\\s|/?>)`).test(withoutImports)) continue\n const nested = inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n const declaration = statefulSnippetDeclaration(nested, componentName)\n if (declaration) preservedDeclarations.set(componentName, declaration)\n else snippets.set(componentName, snippetComponentBody(nested, componentName))\n }\n let result = withoutImports\n for (const [componentName, snippet] of snippets) {\n result = result\n .replace(new RegExp(`<${componentName}((?:\\\\s[^>]*)?)\\\\s*/>`, 'g'), (_tag, attributes: string) => {\n return interpolateSnippet(snippet, attributes)\n })\n .replace(new RegExp(`<${componentName}((?:\\\\s[^>]*)?)>([\\\\s\\\\S]*?)<\\\\/${componentName}>`, 'g'), (_tag, attributes: string, children: string) => {\n return interpolateSnippet(snippet, attributes, children)\n })\n }\n result = result.replace(SNIPPET_TAG_PATTERN, (_tag, doubleQuoted: string | undefined, singleQuoted: string | undefined) => {\n const filePath = (doubleQuoted ?? singleQuoted)!\n try {\n // Mintlify's documented form is relative to `snippets/`; sites also write\n // the full `/snippets/x.mdx` (or a page-relative) path.\n const candidate = [\n () => resolveWithin(siteRoot, `snippets/${filePath}`),\n () => resolveSnippetPath(filePath, currentFile, repositoryRoot, siteRoot),\n ].map((resolveCandidate) => {\n try { return resolveCandidate() } catch { return undefined }\n }).find((path) => path !== undefined && existsSync(path) && lstatSync(path).isFile())\n if (!candidate) throw new Error('file not found')\n return inlineMdxSnippets(\n withoutFrontmatter(readFileSync(candidate, 'utf8')),\n candidate,\n repositoryRoot,\n warnings,\n depth + 1,\n siteRoot,\n globalAliases,\n )\n } catch {\n warnings.push({\n code: 'missing-page',\n message: `Snippet file=\"${filePath}\" could not be resolved and was left as a comment.`,\n source: relative(repositoryRoot, currentFile).replace(/\\\\/g, '/'),\n })\n return `{/* Missing snippet: ${filePath} */}`\n }\n })\n if (preservedDeclarations.size > 0) {\n const frontmatter = result.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/)\n const prefix = frontmatter?.[0] ?? ''\n result = `${prefix}${[...new Set(preservedDeclarations.values())].join('\\n\\n')}\\n\\n${result.slice(prefix.length)}`\n }\n return depth === 0 ? hoistMdxImports(result) : result\n}\n\n/**\n * Bind one or more resolved specs into their tabs. A spec with no\n * `tabLabel` (the common single-spec case) falls back to an existing\n * \"*api*\"-labelled tab, or gets a new \"API Reference\" tab of its own — the\n * original single-spec behavior. A spec with a `tabLabel` only ever binds\n * to that exact tab (creating it if the source tab had no other content\n * and so was dropped from `config.tabs` earlier), never the loose\n * substring fallback, so two specs from two different tabs can never both\n * land on the same tab by accident.\n */\nfunction injectOpenApiSpecs(\n config: MigrationDocsConfig,\n specs: Array<{ filename: string; tabLabel?: string }>,\n warnings?: Array<MigrationWarning>,\n): MigrationDocsConfig {\n let tabs = config.tabs.map((tab) => ({ ...tab }))\n for (const spec of specs) {\n const apiTab = spec.tabLabel\n ? tabs.find((tab) => tab.tab === spec.tabLabel)\n : tabs.find((tab) => tab.tab.toLowerCase().includes('api'))\n if (apiTab) {\n // Thally binds one API spec per tab; a second spec that resolves to\n // the same tab would otherwise silently replace the first one's\n // binding with no trace of it ever having existed.\n if (apiTab.api && warnings) {\n warnings.push({\n code: 'unsupported-config',\n message: `Tab \"${apiTab.tab}\" already uses another OpenAPI spec, and Thally supports one API spec per tab, so \"/${spec.filename}\" was not added. Put it in its own tab to include it.`,\n })\n continue\n }\n apiTab.api = {\n source: `/${spec.filename}`,\n // An API-only tab needs generated endpoint navigation; an authored\n // page tab keeps its own groups alongside the bound spec.\n ...((apiTab.groups?.length || apiTab.pages?.length) ? { navigation: false } : {}),\n }\n } else {\n tabs = [...tabs, { tab: spec.tabLabel ?? 'API Reference', api: { source: `/${spec.filename}` } }]\n }\n }\n return { ...config, tabs }\n}\n\n/** Identify component ownership independently of checkout paths and URL syntax. */\nfunction componentSourceIdentity(sourceUrl: string, repositoryDir: string, siteRoot: string): string {\n const url = new URL(sourceUrl)\n // A GitHub tree URL and the repository root identify the same source. Branch\n // changes should update its components, while separate monorepo sites must\n // retain independent namespaces even if their snippet filenames coincide.\n // Credentials, queries and fragments are not source identity and never feed\n // generated names; only the canonical origin/path and docs root participate.\n const repository = url.hostname.toLowerCase() === 'github.com'\n ? `https://github.com/${url.pathname.split('/').filter(Boolean).slice(0, 2).join('/').replace(/\\.git$/i, '').toLowerCase()}`\n : `${url.origin}${trimTrailingSlashes(url.pathname)}`\n return JSON.stringify([repository, relative(repositoryDir, siteRoot).replace(/\\\\/g, '/')])\n}\n\n/** Import an already-available repository directory into a canonical bundle. */\nexport function migrateRepository(options: RepositoryMigrationOptions): MigrationBundle {\n const repositoryDir = options.repositoryDir\n const platform = options.platform ?? detectRepositoryPlatform(repositoryDir, options.docsDir)\n const warnings: Array<MigrationWarning> = []\n const mintlifyProjectRoot = platform === 'mintlify'\n ? findMintlifyProjectRoot(repositoryDir, options.docsDir, warnings)\n : null\n const docusaurusProjectRoot = platform === 'docusaurus'\n ? findDocusaurusProjectRoot(repositoryDir, options.docsDir, warnings)\n : null\n const fernProjectRoot = platform === 'fern'\n ? findFernProjectRoot(repositoryDir, options.docsDir)\n : null\n const configuredDocsDir = (() => {\n if (options.docsDir !== undefined) {\n const selected = resolveWithin(repositoryDir, options.docsDir || '.')\n if (platform === 'docusaurus' && hasDocusaurusConfig(selected)) {\n const projectRelative = relative(repositoryDir, selected).replace(/\\\\/g, '/')\n return [projectRelative, primaryDocusaurusDocsDirectory(selected)].filter(Boolean).join('/')\n }\n return options.docsDir\n }\n if (docusaurusProjectRoot) {\n const projectRelative = relative(repositoryDir, docusaurusProjectRoot).replace(/\\\\/g, '/')\n return [projectRelative, primaryDocusaurusDocsDirectory(docusaurusProjectRoot)].filter(Boolean).join('/')\n }\n if (platform === 'mintlify' && mintlifyProjectRoot) {\n return relative(repositoryDir, mintlifyProjectRoot).replace(/\\\\/g, '/')\n }\n if (platform === 'fern' && fernProjectRoot) {\n return relative(repositoryDir, fernProjectRoot).replace(/\\\\/g, '/')\n }\n return platform === 'mintlify' ? '' : detectRepositoryDocsDir(repositoryDir)\n })()\n // A Docusaurus or Fern MDX page can import its own local components\n // (relative, or `@site/...` for Docusaurus) and bare npm packages the same\n // way a Mintlify page can; the same bounded component graph and\n // import-stripping logic applies to any source, rooted at whichever\n // project actually owns the pages. `@site/...` is Docusaurus' own alias\n // for its project root specifically (not the whole repository) and must\n // keep resolving there. A plain relative import (`../../components/X`),\n // though, is written relative to the *page*, which can live outside that\n // root in a monorepo where docs/ is a sibling of website/ (e.g. Redux) or\n // of a Fern project directory rather than nested under it — the\n // repository, not the narrower platform root, is the real confinement\n // boundary for those.\n const componentRoot = mintlifyProjectRoot ?? docusaurusProjectRoot ?? fernProjectRoot ?? repositoryDir\n const componentMigrator = platform === 'mintlify' || platform === 'docusaurus' || platform === 'fern'\n ? createComponentMigrator(componentRoot, repositoryDir, warnings, componentSourceIdentity(options.sourceUrl, repositoryDir, componentRoot))\n : undefined\n let docsConfig: MigrationDocsConfig = { tabs: [] }\n // Literal leading path segments (e.g. \"v1.15.22\") that identify a\n // Mintlify `versions` container's default version — see\n // `mintlifyDefaultVersionPrefixes`.\n let defaultVersionPrefixes: ReadonlySet<string> = new Set()\n // Every version identifier declared in the config (default and\n // non-default) — used only to name which versions' pages were dropped if\n // discovery exceeds MAX_SOURCE_FILES; see `selectFilesWithinBudget`.\n let allVersionPrefixes: ReadonlySet<string> = new Set()\n const referenceMap = new Map<string, { navigationId: string; locale?: string }>()\n const exactReferenceMap = new Map<string, { navigationId: string; locale?: string }>()\n const referenceOrder = new Map<string, number>()\n let docusaurusSidebars: DocusaurusSidebars | null = null\n let mintlifyConfig: Record<string, unknown> | null = null\n let fernRawConfig: Record<string, unknown> | null = null\n let fernBasePath = ''\n let fernVersionPath = ''\n let fernApiSections: Array<FernApiSection> = []\n // sourcePaths of Fern descriptors that resolve outside fern/ (from a\n // `versions:` file living in a sibling directory) — resolved directly,\n // below, since the ordinary fern/-rooted scan can't reach them.\n const fernExternalSourcePaths = new Set<string>()\n let fernChangelogIndexes: Array<{ route: string; entries: Array<string> }> = []\n const fernReferencedPaths = new Set<string>()\n const fernSourceLinkAliases = new Map<string, string>()\n const fernNavTitles = new Map<string, string>()\n const fernHiddenIds = new Set<string>()\n\n if (platform === 'mintlify') {\n try {\n const config = readMintlifyConfig(mintlifyProjectRoot ?? repositoryDir)\n if (config) {\n mintlifyConfig = config\n defaultVersionPrefixes = mintlifyDefaultVersionPrefixes(config)\n allVersionPrefixes = mintlifyAllVersionPrefixes(config)\n const projected = projectMintlifyNavigation(config)\n docsConfig = projected.docsConfig\n warnings.push(...projected.warnings)\n for (const [index, reference] of projected.pageReferences.entries()) {\n const key = normalizedReferenceKey(reference.ref)\n // Shared source pages may appear in several language menus. The\n // projector visits the default language first; retain that primary\n // file so other locales can use the runtime's content fallback.\n if (!referenceMap.has(key)) referenceMap.set(key, reference)\n const exactKey = exactReferenceKey(reference.ref)\n if (!exactReferenceMap.has(exactKey)) exactReferenceMap.set(exactKey, reference)\n if (!referenceOrder.has(key)) referenceOrder.set(key, index)\n }\n }\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Mintlify config could not be read: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n\n if (platform === 'fern' && fernProjectRoot) {\n try {\n const fernConfig = readFernConfig(fernProjectRoot)\n if (fernConfig) {\n fernRawConfig = fernConfig.config\n fernBasePath = fernSourceBasePath(fernConfig.config)\n fernVersionPath = fernDefaultVersionPath(fernConfig.config)\n const projected = projectFernNavigation({ config: fernConfig.config, fernRoot: fernProjectRoot, repositoryRoot: repositoryDir })\n docsConfig = projected.docsConfig\n warnings.push(...projected.warnings)\n fernApiSections = projected.apiSections\n fernChangelogIndexes = projected.changelogIndexes\n for (const [index, descriptor] of projected.descriptors.entries()) {\n fernReferencedPaths.add(descriptor.sourcePath)\n if (descriptor.navTitle && !fernNavTitles.has(descriptor.navigationId)) {\n fernNavTitles.set(descriptor.navigationId, descriptor.navTitle)\n }\n if (descriptor.hidden) fernHiddenIds.add(descriptor.navigationId)\n // Fern pages often link by their source directory while a section\n // title changes the published route (for example tts-vendors to\n // tts-vendor-settings). Resolve only unambiguous, tab-prefixed\n // source paths rather than guessing at arbitrary root links.\n const sourceTail = descriptor.sourcePath.match(/(?:^|\\/)pages\\/(.+)\\.mdx?$/i)?.[1]?.replace(/\\/index$/i, '')\n if (sourceTail) {\n const routeSegments = descriptor.navigationId.split('/')\n const sourceSegments = sourceTail.split('/')\n if (routeSegments.length === sourceSegments.length + 1) {\n const alias = `${routeSegments[0]}/${sourceTail}`\n if (alias !== descriptor.navigationId && !fernSourceLinkAliases.has(alias)) fernSourceLinkAliases.set(alias, descriptor.navigationId)\n }\n }\n const key = normalizedReferenceKey(descriptor.sourcePath)\n if (!referenceMap.has(key)) referenceMap.set(key, { navigationId: descriptor.navigationId })\n const exactKey = exactReferenceKey(descriptor.sourcePath)\n if (!exactReferenceMap.has(exactKey)) exactReferenceMap.set(exactKey, { navigationId: descriptor.navigationId })\n if (!referenceOrder.has(key)) referenceOrder.set(key, index)\n if (descriptor.sourcePath.startsWith('../')) fernExternalSourcePaths.add(descriptor.sourcePath)\n }\n }\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Fern config could not be read: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n\n if (platform === 'docusaurus') {\n try {\n docusaurusSidebars = options.docusaurusSkipSidebar || !docusaurusProjectRoot\n ? null\n : readDocusaurusSidebars(docusaurusProjectRoot, options.docusaurusSidebarPath)\n } catch (error) {\n warnings.push({\n code: 'unsupported-config',\n message: `Docusaurus sidebar could not be read safely: ${error instanceof Error ? error.message : String(error)} Generated navigation will be used.`,\n })\n }\n }\n\n const contentRoot = resolveWithin(repositoryDir, configuredDocsDir)\n if (!existsSync(contentRoot) || !lstatSync(contentRoot).isDirectory()) {\n throw new Error(`Documentation directory does not exist: ${configuredDocsDir || '.'}`)\n }\n const mintignoreMatcher = platform === 'mintlify' && mintlifyProjectRoot\n ? readMintignoreMatcher(mintlifyProjectRoot)\n : null\n // Referenced files (found in the navigation config) are ranked ahead of\n // unreferenced ones, in navigation traversal order — which already puts a\n // Mintlify default version's pages before non-default versions' (and\n // newer non-default versions before older ones); see\n // `selectFilesWithinBudget`. Only meaningful when a nav was actually\n // parsed (Mintlify/Fern); Docusaurus has no pre-scan reference set.\n //\n // An *unreferenced* page (a real file Mintlify still serves by its own\n // file-based routing even though no sidebar entry points at it, e.g.\n // crewAI's `tools/web-scraping/firecrawlsearchtool.mdx`) used to get the\n // exact same flat lowest priority regardless of which version it belonged\n // to. Ranking it just after a single *global* floor (every referenced\n // page, from every version) isn't enough to fix that: a repository whose\n // total *referenced*-page count alone already exceeds the budget (e.g.\n // crewAI's ~40 versions x ~180 pages each) would still starve every\n // orphan, including the default version's own, since literally every\n // referenced page from every version would still outrank it. Instead,\n // each orphan is ranked right after the *last* referenced page found\n // under its own version+locale block — traversal is contiguous per\n // (language, version) pair (a whole version's pages, referenced and its\n // own orphans together, are visited before the next version starts, and\n // a whole language's versions before the next language's) — so grouping\n // by version alone (dropping the locale segment) would still pool an\n // English orphan's ceiling together with, say, Arabic's or Korean's much\n // later-traversed pages under the same version identifier. Keying by the\n // first two path segments (version, then locale) — rather than requiring\n // an exact match against `allVersionPrefixes` (the `version:` label\n // declared in config) — also keeps this working even when a version's\n // declared label and its actual directory prefix disagree in spelling or\n // case (e.g. crewAI's own `\"version\": \"Edge\"` label for its lowercase\n // `edge/` directory): what matters for contiguity is purely the directory\n // structure real pages were discovered under, not the label text. A\n // version's orphans land immediately behind that same version+locale's\n // own referenced pages, never behind another locale's or version's.\n const lastReferencedIndexByVersionLocale = new Map<string, number>()\n for (const [key, index] of referenceOrder) {\n const blockKey = key.split('/').slice(0, 2).join('/')\n const current = lastReferencedIndexByVersionLocale.get(blockKey)\n if (current === undefined || index > current) lastReferencedIndexByVersionLocale.set(blockKey, index)\n }\n const discoveryRank = referenceOrder.size > 0\n ? (relativePath: string): number => {\n const referencedIndex = referenceOrder.get(normalizedReferenceKey(relativePath))\n if (referencedIndex !== undefined) return referencedIndex\n const blockKey = relativePath.split('/').slice(0, 2).join('/')\n const versionCeiling = lastReferencedIndexByVersionLocale.get(blockKey)\n return versionCeiling !== undefined ? versionCeiling + 1 : Number.MAX_SAFE_INTEGER\n }\n : undefined\n const scannedFiles = scanFiles(contentRoot, repositoryDir, warnings, discoveryRank)\n const mintignoreFilteredFiles = mintignoreMatcher\n ? scannedFiles.filter((file) => !mintignoreMatcher.ignores(file.relativePath))\n : scannedFiles\n const discoveryBudgetApplied = discoveryRank !== undefined && mintignoreFilteredFiles.length > MAX_SOURCE_FILES\n const files = discoveryRank\n ? selectFilesWithinBudget(mintignoreFilteredFiles, discoveryRank, warnings, allVersionPrefixes)\n : mintignoreFilteredFiles\n // A Fern `versions:` file may live outside fern/ (a sibling `docs/`\n // directory) and its own pages resolve relative to it, so their\n // sourcePath (e.g. `../docs/pages/x.mdx`) falls outside the fern/-rooted\n // scan above. Resolve exactly those referenced files directly, rather\n // than rescanning the whole repository (which would also shift every\n // asset's firstSegment and break the fern/-relative asset-bucket\n // detection below).\n if (platform === 'fern' && fernProjectRoot) {\n const discovered = new Set(files.map((file) => file.relativePath))\n for (const sourcePath of fernExternalSourcePaths) {\n if (discovered.has(sourcePath)) continue\n try {\n const absolutePath = resolveWithinRoot(fernProjectRoot, sourcePath, repositoryDir)\n if (existsSync(absolutePath) && lstatSync(absolutePath).isFile()) {\n files.push({ absolutePath, relativePath: sourcePath })\n discovered.add(sourcePath)\n } else {\n warnings.push({ code: 'missing-page', message: 'A Fern navigation path could not be read within this repository.', source: sourcePath })\n }\n } catch {\n warnings.push({ code: 'missing-page', message: 'A Fern navigation path could not be read within this repository.', source: sourcePath })\n }\n }\n }\n const pages: Array<MigrationPage> = []\n const assets: Array<MigrationAsset> = []\n const remoteApiSpecs: Array<{ url: string; tabLabel?: string }> = []\n // Which pages reference which asset (by its normalized copy-destination\n // path), so the final asset-copy pass can prioritize referenced assets\n // over unreferenced ones when the budget is tight, and name the\n // referencing pages in the warning if one still gets dropped.\n const referencedAssetPaths = new Map<string, Set<string>>()\n const addAssetReference = (assetPath: string, referencingPage: string): void => {\n const referrers = referencedAssetPaths.get(assetPath)\n if (referrers) referrers.add(referencingPage)\n else referencedAssetPaths.set(assetPath, new Set([referencingPage]))\n }\n const docusaurusDescriptors: Array<DocusaurusPageDescriptor> = []\n const docusaurusDocCardRoutes = new Set<string>()\n const seenPageIds = new Set<string>()\n /** docs.yml-derived navigationId -> final id, when a page's frontmatter `slug` overrides it. */\n const fernIdRenames = new Map<string, string>()\n let skipped = 0\n let discovered = files.length\n\n const localeConfig = docsConfig.i18n\n const defaultPageIds = new Set([...referenceMap.values()]\n .filter((reference) => !reference.locale || reference.locale === localeConfig?.defaultLocale)\n .map((reference) => reference.navigationId))\n const routeAliases: NonNullable<MigrationDocsConfig['redirects']> = []\n const pageFiles = [...files].sort((left, right) => {\n const leftOrder = referenceOrder.get(normalizedReferenceKey(left.relativePath)) ?? Number.MAX_SAFE_INTEGER\n const rightOrder = referenceOrder.get(normalizedReferenceKey(right.relativePath)) ?? Number.MAX_SAFE_INTEGER\n return leftOrder - rightOrder || left.relativePath.localeCompare(right.relativePath)\n })\n const snippetAliases = platform === 'mintlify' && mintlifyProjectRoot\n ? globalSnippetAliases(files, repositoryDir, mintlifyProjectRoot)\n : new Map<string, string>()\n for (const file of pageFiles) {\n if (!isDocumentationExtension(file.relativePath)) continue\n // Unlike Mintlify/Docusaurus, Fern only ever serves pages reachable from\n // docs.yml (or a versions file); everything else is invisible on the\n // live site, so importing it as an \"orphan\" page would fabricate content\n // (and can crash a build on stray files that were never meant to render).\n if (platform === 'fern'\n && !exactReferenceMap.has(exactReferenceKey(file.relativePath))\n && !referenceMap.has(normalizedReferenceKey(file.relativePath))) {\n skipped++\n continue\n }\n const sourceSegments = file.relativePath.split('/')\n if (sourceSegments.some((segment) => SNIPPET_DIRECTORIES.has(segment.toLowerCase()))\n || (platform === 'docusaurus' && basename(file.relativePath).startsWith('_'))) {\n skipped++\n continue\n }\n const rootFilename = !file.relativePath.includes('/') ? basename(file.relativePath).toLowerCase() : ''\n if (REPOSITORY_ONLY_DOCUMENTS.has(rootFilename) && !exactReferenceMap.has(exactReferenceKey(file.relativePath))) {\n skipped++\n continue\n }\n if (!['.md', '.mdx'].includes(extname(file.relativePath).toLowerCase())) {\n skipped++\n warnings.push({ code: 'skipped-file', message: 'Only Markdown and MDX are imported without an explicit converter.', source: file.relativePath })\n continue\n }\n const size = lstatSync(file.absolutePath).size\n if (size > MAX_PAGE_BYTES) {\n skipped++\n warnings.push({ code: 'skipped-file', message: 'Page exceeded the 2 MB repository import limit.', source: file.relativePath })\n continue\n }\n const key = normalizedReferenceKey(file.relativePath)\n const referenced = exactReferenceMap.get(exactReferenceKey(file.relativePath)) ?? referenceMap.get(key)\n let locale = referenced?.locale\n let navigationId = referenced?.navigationId ?? pageIdFromReference(file.relativePath, platform === 'mintlify')\n if (!referenced && localeConfig) {\n for (const entry of localeConfig.locales) {\n const localized = mintlifyLocalizedReference(file.relativePath, entry.code, defaultPageIds)\n if (localized === file.relativePath) continue\n locale = entry.code\n navigationId = pageIdFromReference(localized, platform === 'mintlify')\n break\n }\n }\n if (!navigationId) {\n skipped++\n warnings.push({ code: 'invalid-page', message: 'Page path could not be normalized safely.', source: file.relativePath })\n continue\n }\n const isDefaultLocale = !locale || locale === localeConfig?.defaultLocale\n const id = isDefaultLocale ? navigationId : `${locale}/${navigationId}`\n let raw = inlineMdxSnippets(\n readFileSync(file.absolutePath, 'utf8'),\n file.absolutePath,\n repositoryDir,\n warnings,\n 0,\n mintlifyProjectRoot ?? docusaurusProjectRoot ?? fernProjectRoot ?? repositoryDir,\n snippetAliases,\n )\n if (platform === 'fern' || platform === 'mintlify' || platform === 'docusaurus') {\n // A heading's `{#custom-id}` anchor (`## Title {#custom-id}`) crashes\n // `@mdx-js/mdx`'s parser outright, so it must be converted to a\n // preceding `<a id=\"custom-id\"></a>` (see `normalizeExplicitHeadingIds`)\n // before ANY MDX parse of this page is attempted — including\n // `componentMigrator.transform` below, whose own early parse would\n // otherwise choke on it and skip the page's import analysis entirely.\n raw = normalizeExplicitHeadingIds(raw)\n }\n if (componentMigrator) {\n const warningsBeforeTransform = warnings.length\n raw = componentMigrator.transform(raw, file.absolutePath)\n // `transform` excludes a page itself (pushing a 'skipped-file' warning\n // for it) when it references an unsupported npm import outside JSX —\n // keeping that import would fail `next build` for the whole site. Skip\n // building this page too; `pruneMissingNavigationPages` below drops it\n // from navigation since it never joins `pages`.\n // `warning.source` is relative to `componentRoot`, which can differ\n // from `repositoryDir` (a nested Mintlify/Docusaurus project root);\n // compare absolute paths rather than the two relative forms directly.\n if (warnings.slice(warningsBeforeTransform).some((warning) => warning.code === 'skipped-file' && warning.source !== undefined\n && resolvePath(componentRoot, warning.source) === file.absolutePath)) {\n skipped++\n continue\n }\n }\n // A bare `{word}` in prose (e.g. Infisical's STYLE_GUIDE.md `{x}`) is\n // literal text on Mintlify and Docusaurus too, not just Fern — MDX\n // always evaluates `{...}` as a JS expression, so any platform's source\n // can hit the same `ReferenceError` at render. `escapeFernLiteralBraces`\n // is platform-agnostic (it only reads the page's own AST/ESM scope), so\n // run it for every platform Thally migrates from.\n if (platform === 'fern' || platform === 'mintlify' || platform === 'docusaurus') {\n // Math must be protected before the AST-based brace escaper runs:\n // `$$\\begin{align*}...\\end{align*}$$` crashes that parser outright\n // (see `protectMathBlocks`), which is what excluded these pages\n // before this ran. The heading-custom-id case that used to be\n // handled at this same point is now converted earlier, above, before\n // `componentMigrator.transform` gets a chance to choke on it too.\n const protectedMath = protectMathBlocks(raw)\n if (protectedMath.converted) {\n warnings.push({\n code: 'unsupported-config',\n message: \"Math (KaTeX '$$...$$') has no renderer in Thally yet; it was kept as a fenced code block instead of being dropped.\",\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n } else if (protectedMath.guardTriggered) {\n warnings.push({\n code: 'unsupported-config',\n message: 'A suspected math span looked like it needed converting, but doing so broke the page; the page was kept as originally authored instead.',\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n }\n raw = escapeFernLiteralBraces(protectedMath.body)\n }\n const hasDocusaurusDocCardList = platform === 'docusaurus' && /<DocCardList\\b[^>]*\\/>/.test(raw)\n if (hasDocusaurusDocCardList) {\n // A plain HTML placeholder survives the generic MDX normalizer while\n // retaining the card list's exact position relative to surrounding prose.\n raw = raw.replace(/<DocCardList\\b[^>]*\\/>/g, '<div data-thally-doc-card-list=\"\" />')\n }\n let docusaurusDescriptor: Omit<DocusaurusPageDescriptor, 'title'> | undefined\n const page = parseMarkdownPage({\n id,\n navigationId,\n ...(locale ? { locale } : {}),\n raw,\n platform,\n source: `${options.sourceUrl}#${relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/')}`,\n ...(platform === 'docusaurus' ? {\n resolveIdentity: (frontmatter, fallback) => {\n const resolved = resolveDocusaurusPageIdentity(file.relativePath, frontmatter, fallback)\n const routePrefix = options.docusaurusRoutePrefix === undefined\n ? undefined\n : trimEdgeSlashes(options.docusaurusRoutePrefix)\n if (!routePrefix) {\n docusaurusDescriptor = resolved.descriptor\n return resolved.identity\n }\n const prefixedNavigationId = resolved.identity.navigationId === 'introduction'\n ? routePrefix\n : `${routePrefix}/${resolved.identity.navigationId}`\n const prefixedStorageId = resolved.identity.id === 'introduction'\n ? routePrefix\n : `${routePrefix}/${resolved.identity.id}`\n docusaurusDescriptor = {\n ...resolved.descriptor,\n navigationId: prefixedNavigationId,\n }\n return {\n ...resolved.identity,\n id: prefixedStorageId,\n navigationId: prefixedNavigationId,\n }\n },\n } : {}),\n // A Fern page's own frontmatter `slug` replaces its whole section/folder\n // hierarchy (never just its own segment) and wins over a docs.yml slug.\n ...(platform === 'fern' ? {\n resolveIdentity: (frontmatter, fallback) => {\n const slug = typeof frontmatter.slug === 'string' ? frontmatter.slug.trim() : ''\n if (!slug) return fallback\n const overridden = pageIdFromReference(slug, true)\n if (!overridden) return fallback\n fernIdRenames.set(fallback.navigationId, overridden)\n return { ...fallback, id: overridden, navigationId: overridden }\n },\n } : {}),\n })\n if (!page) {\n skipped++\n continue\n }\n if (page.frontmatterError) {\n warnings.push({\n code: 'unsupported-config',\n message: `The page's frontmatter is not valid YAML (${page.frontmatterError}); the page was kept and as much of its metadata as could be read was used.`,\n source: relative(repositoryDir, file.absolutePath).replace(/\\\\/g, '/'),\n })\n }\n if (platform === 'fern' && !page.navTitle) {\n const navTitle = fernNavTitles.get(navigationId)\n if (navTitle && navTitle !== page.title) page.navTitle = navTitle\n }\n if (platform === 'fern' && fernHiddenIds.has(navigationId)) page.hidden = true\n if (platform === 'mintlify' && mintlifyProjectRoot) {\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, mintlifyProjectRoot, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n }\n if (platform === 'fern' && fernProjectRoot) {\n // Fern can keep docs in a sibling `docs/` directory beside `fern/`.\n // The checkout, not the config directory, is the safe asset boundary.\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, fernProjectRoot, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, repositoryDir, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\n page.body = stripFernBasePathFromLinks(page.body, fernBasePath)\n page.body = stripFernBasePathFromLinks(page.body, fernVersionPath)\n }\n if (platform === 'mintlify' || platform === 'docusaurus' || platform === 'fern') {\n // `<Link href=\"...\">` (common Mintlify/Docusaurus prose, e.g. mem0's\n // docs) has no Thally builtin; map it to a plain anchor before the\n // generic unknown-component fallback runs, so a real navigable link\n // survives instead of becoming a `<div>`. Runs on the fully normalized\n // body (after `parseMarkdownPage`'s `normalizeMdx`), so a tag that a\n // platform-specific rename still resolves (Docusaurus `TabItem` ->\n // `Tab`, Mintlify `Warn` -> `Warning`, ...) is never mistaken for\n // unknown. Fern-native components with no Thally equivalent\n // (`Markdown`, `Button`, `Download`, ...) fall into the same generic\n // path below — there is no separate Fern-specific detector, so each\n // unknown tag gets exactly one warning.\n page.body = replaceLinkWithAnchor(page.body)\n // Anything still capitalized and unresolved at this point (not a\n // Thally builtin, not declared/imported by the page, not already\n // handled by componentMigrator's copy/removal above) would otherwise\n // throw \"Expected component X to be defined\" at render. Warn once per\n // component name and neutralize it: keep a paired tag's children,\n // drop a self-closing one outright.\n page.body = replaceUnknownComponents(page.body, (name) => {\n warnings.push({\n code: 'unsupported-config',\n message: `Component <${name}> has no equivalent in Thally and wasn't found on this page; it was replaced with a plain <div> (or removed, if self-closing) so the page still builds. Add a matching component or edit the page.`,\n source: file.relativePath,\n })\n })\n }\n const mdxError = invalidMdxReason(page.body)\n if (mdxError) {\n skipped++\n warnings.push({\n code: 'skipped-file',\n message: `Page was excluded because it does not compile as MDX: ${mdxError}`,\n source: file.relativePath,\n })\n continue\n }\n // `hasAnyFunctionValuedProp` only proves a function value (a reference to\n // a page-declared function, or a function written inline) is passed as\n // *some* JSX prop; it does not know which tag receives it. A prop\n // landing on a component this migration actually extracted as\n // 'use client' (`Migrated<hash>`/`Inline<n>`) or on a Thally runtime\n // built-in already backed by a 'use client' module (`Accordion`, `Panel`,\n // `Tabs`, ... — see `CLIENT_BUILTIN_COMPONENT_TAGS` in components.ts) is\n // confirmed to cross the server/client boundary and throw at render — a\n // prop on any other tag (an unregistered/removed component) is not\n // confirmed either way, so exclusion (a last resort) is reserved for the\n // confirmed case; the unconfirmed case is warned instead, so it is never\n // silently dropped or silently shipped broken.\n const declaredNames = functionDeclaredNames(page.body)\n if (hasAnyFunctionValuedProp(page.body, declaredNames)) {\n if (propsTargetExtractedClientComponent(page.body, declaredNames)) {\n skipped++\n warnings.push({\n code: 'skipped-file',\n message: \"This page passes a function to an interactive component, which can't be rendered on the server. \"\n + 'Move the function into the component or edit the page manually.',\n source: file.relativePath,\n })\n continue\n }\n warnings.push({\n code: 'unsupported-config',\n message: \"This page might pass a function to an interactive component, which can't be rendered on the \"\n + 'server; review it manually if the built page fails to render.',\n source: file.relativePath,\n })\n }\n if (declarationsReferenceBrowserGlobal(page.body)) {\n warnings.push({\n code: 'unsupported-config',\n message: \"This page defines a component that uses `document`/`window`, which isn't available when pages \"\n + 'are rendered on the server. Move that code into a client component or edit the page manually.',\n source: file.relativePath,\n })\n }\n if (seenPageIds.has(page.id)) {\n skipped++\n warnings.push({ code: 'collision', message: `Multiple source files map to ${page.id}; the first file was kept.`, source: file.relativePath })\n continue\n }\n seenPageIds.add(page.id)\n pages.push(page)\n // MDX normalization removes DocCardList because Thally has no matching\n // component. Remember its authored route so the resolved sidebar can\n // supply the cards once every page and category has been discovered.\n if (hasDocusaurusDocCardList) {\n docusaurusDocCardRoutes.add(page.navigationId)\n }\n if (platform === 'mintlify') {\n const sourcePath = exactReferenceKey(file.relativePath)\n // Only literal portable paths become Next redirects: source filenames\n // must never introduce route patterns such as `:param` or wildcards.\n if (sourcePath !== page.id && /^[A-Za-z0-9_./-]+$/.test(sourcePath)) {\n routeAliases.push({ source: `/${sourcePath}`, destination: `/${page.id}`, permanent: false })\n }\n // The default version's own pages are also linked without the\n // version segment (the live Mintlify site 307s such a link to the\n // versioned page) — add the matching alias so those in-repo links\n // resolve instead of dead-ending. See `mintlifyDefaultVersionPrefixes`.\n const versionPrefix = [...defaultVersionPrefixes].find((prefix) => sourcePath === prefix || sourcePath.startsWith(`${prefix}/`))\n if (versionPrefix) {\n const unversioned = sourcePath.slice(versionPrefix.length).replace(/^\\/+/, '')\n if (unversioned && unversioned !== sourcePath && unversioned !== page.id\n && /^[A-Za-z0-9_./-]+$/.test(unversioned)\n && !routeAliases.some((redirect) => redirect.source === `/${unversioned}`)) {\n routeAliases.push({ source: `/${unversioned}`, destination: `/${page.id}`, permanent: false })\n }\n }\n }\n if (docusaurusDescriptor) {\n docusaurusDescriptors.push({ ...docusaurusDescriptor, title: page.title })\n }\n }\n\n const discoveredReferenceKeys = new Set(files.map((file) => normalizedReferenceKey(file.relativePath)))\n for (const [key] of referenceMap) {\n if (!discoveredReferenceKeys.has(key)) {\n warnings.push({ code: 'missing-page', message: 'A navigation entry did not resolve to a source page.', source: key })\n }\n }\n\n const docusaurusAssetRoot = docusaurusProjectRoot ?? repositoryDir\n const fernBrandAssetPaths = new Map<string, string>()\n const fernReferencedAssets: Array<ScannedFile> = []\n if (platform === 'fern' && fernProjectRoot) {\n const seen = new Set<string>()\n const addFernAsset = (candidate: string, source?: string): void => {\n try {\n const absolutePath = source\n ? resolveWithinRoot(fernProjectRoot, source.replace(/^\\/+/, ''), repositoryDir)\n : resolveWithin(repositoryDir, candidate)\n if (!existsSync(absolutePath) || !lstatSync(absolutePath).isFile()) return\n const realRoot = realpathSync(repositoryDir)\n const realPath = realpathSync(absolutePath)\n const confined = relative(realRoot, realPath)\n if (confined === '..' || confined.startsWith(`..${sep}`) || isAbsolute(confined)) return\n const withinFern = relative(fernProjectRoot, absolutePath)\n const assetRelative = withinFern !== '..' && !withinFern.startsWith(`..${sep}`) && !isAbsolute(withinFern)\n ? withinFern\n : relative(repositoryDir, absolutePath)\n const assetPath = normalizeAssetPath(assetRelative.replace(/\\\\/g, '/'))\n if (!assetPath || !ASSET_EXTENSIONS.has(extname(assetPath).toLowerCase())) return\n if (source) {\n fernBrandAssetPaths.set(source, assetPath)\n addAssetReference(assetPath, 'fern/docs.yml')\n }\n if (seen.has(absolutePath)) return\n seen.add(absolutePath)\n fernReferencedAssets.push({ absolutePath, relativePath: assetPath })\n } catch {\n // The existing missing-asset warning names any unresolved brand path.\n }\n }\n for (const path of referencedAssetPaths.keys()) addFernAsset(path)\n for (const value of [fernRawConfig?.logo, fernRawConfig?.favicon]) {\n if (typeof value === 'string') addFernAsset('', value)\n else if (value && typeof value === 'object' && !Array.isArray(value)) {\n const variants = value as Record<string, unknown>\n for (const candidate of [variants.light, variants.dark, variants.src, variants.srcDark]) {\n if (typeof candidate === 'string') addFernAsset('', candidate)\n }\n }\n }\n }\n const repositoryAssets = platform === 'docusaurus' && configuredDocsDir && !options.docusaurusSkipAssets\n ? ['static', 'public'].flatMap((directory) => {\n const root = resolveWithin(docusaurusAssetRoot, directory)\n if (!existsSync(root) || !lstatSync(root).isDirectory()) return []\n return scanFiles(root, repositoryDir).map((file) => ({\n ...file,\n relativePath: `${directory}/${file.relativePath}`,\n }))\n })\n : []\n interface AssetCandidate { file: ScannedFile; assetPath: string; size: number }\n const assetCandidates: Array<AssetCandidate> = []\n for (const file of [...files, ...repositoryAssets, ...fernReferencedAssets]) {\n const firstSegment = file.relativePath.split('/', 1)[0].toLowerCase()\n if (!ASSET_EXTENSIONS.has(extname(file.relativePath).toLowerCase())) continue\n if (platform !== 'mintlify' && !ASSET_DIRECTORIES.has(firstSegment)\n && !(platform === 'fern' && referencedAssetPaths.has(file.relativePath))) continue\n const isDocusaurusStatic = platform === 'docusaurus' && firstSegment === 'static'\n const assetPath = normalizeAssetPath(firstSegment === 'public'\n ? file.relativePath.slice('public/'.length)\n : isDocusaurusStatic\n ? file.relativePath.slice('static/'.length)\n : file.relativePath)\n if (!assetPath) continue\n assetCandidates.push({ file, assetPath, size: lstatSync(file.absolutePath).size })\n }\n // Copy assets that pages actually reference before unreferenced ones, so a\n // tight budget drops decorative/unused files first instead of screenshots\n // a page links to (each group keeps its original scan order).\n const isReferenced = (candidate: AssetCandidate): boolean => referencedAssetPaths.has(candidate.assetPath)\n const orderedAssetCandidates = [\n ...assetCandidates.filter((candidate) => isReferenced(candidate)),\n ...assetCandidates.filter((candidate) => !isReferenced(candidate)),\n ]\n let totalAssetBytes = 0\n for (const { file, assetPath, size } of orderedAssetCandidates) {\n if (size > MAX_ASSET_BYTES || totalAssetBytes + size > MAX_TOTAL_ASSET_BYTES) {\n const referencingPages = referencedAssetPaths.get(assetPath)\n warnings.push({\n code: 'limit-reached',\n message: 'This file was not copied because it is larger than 25 MB or the copied files would exceed 500 MB in total. Add it to public/ manually'\n + (referencingPages\n ? `; it is used by ${[...referencingPages].slice(0, 3).join(', ')}${referencingPages.size > 3 ? `, and ${referencingPages.size - 3} more` : ''}.`\n : '.'),\n source: file.relativePath,\n })\n continue\n }\n const content = readFileSync(file.absolutePath)\n if (isGitLfsPointer(content)) {\n warnings.push({\n code: 'unsupported-config',\n message: 'This asset is a Git LFS pointer, not its real content (Git LFS was skipped during clone because the host has no git-lfs binary). Install git-lfs and re-run the migration, or add the real file to public/ manually.',\n source: file.relativePath,\n })\n continue\n }\n assets.push({ path: assetPath, content })\n totalAssetBytes += size\n }\n\n // `selectFilesWithinBudget` already emitted a detailed warning (dropped\n // count + versions) when it ran; this generic fallback only covers the\n // case it couldn't run (no `discoveryRank`, e.g. Docusaurus) or the rare\n // case where later additions (Fern's external sourcePaths, above) pushed\n // the count back over budget after the event.\n if (!discoveryBudgetApplied && files.length >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Stopped scanning after ${MAX_SOURCE_FILES} files, so the rest of the repository was not looked at. Run the migration on a smaller part of the repository with --docs-dir.` })\n }\n if (platform === 'docusaurus') {\n const projected = projectDocusaurusNavigation({\n sidebars: docusaurusSidebars,\n descriptors: docusaurusDescriptors,\n contentRoot,\n sourceUrl: options.sourceUrl,\n routePrefix: options.docusaurusRoutePrefix,\n })\n docsConfig = projected.docsConfig\n expandDocusaurusDocCardLists(pages, docsConfig, docusaurusDocCardRoutes)\n warnings.push(...projected.warnings)\n for (const page of projected.generatedPages) {\n if (seenPageIds.has(page.id)) continue\n seenPageIds.add(page.id)\n pages.push(page)\n }\n const descriptorByNavigationId = new Map(\n docusaurusDescriptors.map((descriptor) => [descriptor.navigationId, descriptor]),\n )\n const sourceOrigin = docusaurusProjectRoot ? readDocusaurusSiteOrigin(docusaurusProjectRoot) : undefined\n const externalizedLinks = new Set<string>()\n for (const page of pages) {\n const descriptor = descriptorByNavigationId.get(page.navigationId)\n if (descriptor) page.body = rewriteDocusaurusLinks(page.body, descriptor, docusaurusDescriptors, {\n sourceOrigin,\n onExternalLink: (target) => externalizedLinks.add(target),\n assetPaths: new Set(assets.map((asset) => asset.path)),\n })\n }\n if (externalizedLinks.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalizedLinks.size} link(s) outside the imported Docusaurus docs still point to ${sourceOrigin}; migrate those sections separately if this site must be fully independent.`,\n })\n if (docusaurusProjectRoot && !options.docusaurusSkipRedirects) {\n const redirects = readDocusaurusRedirects(docusaurusProjectRoot, warnings)\n if (redirects.length > 0) docsConfig = { ...docsConfig, redirects: [...(docsConfig.redirects ?? []), ...redirects] }\n }\n }\n if (platform === 'fern' && fernIdRenames.size > 0) {\n const renamedRoute = (route: string): string => {\n const renamed = fernIdRenames.get(route.replace(/^\\//, ''))\n return renamed ? `/${renamed}` : route\n }\n const renamePages = (nodes: Array<string | MigrationNavigationGroup>): Array<string | MigrationNavigationGroup> =>\n nodes.map((node) => typeof node === 'string'\n ? fernIdRenames.get(node) ?? node\n : { ...node, pages: renamePages(node.pages) })\n for (const page of pages) {\n page.body = rewriteFernIdRenameLinks(page.body, fernIdRenames)\n }\n docsConfig = {\n ...docsConfig,\n tabs: docsConfig.tabs.map((tab) => ({\n ...tab,\n ...(tab.pages ? { pages: renamePages(tab.pages) } : {}),\n ...(tab.groups ? { groups: renamePages(tab.groups) as Array<MigrationNavigationGroup> } : {}),\n })),\n ...(docsConfig.redirects ? {\n redirects: docsConfig.redirects.map((redirect) => ({\n ...redirect,\n source: renamedRoute(redirect.source),\n destination: renamedRoute(redirect.destination),\n })),\n } : {}),\n }\n }\n if (platform === 'fern' && fernSourceLinkAliases.size > 0) {\n const imported = new Set(pages.map((page) => page.id))\n const aliases = new Map([...fernSourceLinkAliases]\n .map(([source, target]) => [source, fernIdRenames.get(target) ?? target] as const)\n .filter(([, target]) => imported.has(target)))\n for (const page of pages) page.body = rewriteFernIdRenameLinks(page.body, aliases)\n }\n if (docsConfig.tabs.length === 0) docsConfig = buildNavigationFromPages(pages)\n if (platform === 'fern' && fernProjectRoot) {\n // A repo-wide scan for *any* `openapi.yml`/`.json` file cannot tell one\n // API's spec from another's, so once an explicit `api-name` names a\n // specific API, that naive scan is never consulted as a fallback (the\n // root `generators.yml` rule is in `fernOpenApiCandidateDirs`). A docs.yml\n // with no `api:` node at all falls back to the naive scan, bound to\n // whatever tab `injectOpenApiSpecs` picks for an unbound spec.\n const sections: Array<{ name?: string; nameExplicit: boolean; tabLabel?: string; routeSegments?: Array<string> }> = fernApiSections.length > 0\n ? fernApiSections\n : [{ nameExplicit: false }]\n const resolvedSpecs: Array<{ filename: string; tabLabel?: string; content: Buffer; routeSegments: Array<string> }> = []\n // Two different multi-API specs commonly share a basename (Paradex's\n // prod_rest and testnet_rest both resolve to their own\n // apis/<name>/openapi/openapi.json) — track which absolute file a\n // filename already names so a second, genuinely different spec gets a\n // distinguishing prefix instead of silently reusing the first spec's\n // copied asset for both tabs.\n const specFilenameSources = new Map<string, string>()\n for (const section of sections) {\n const resolution = findFernConfiguredOpenApi(fernProjectRoot, repositoryDir, section.name, section.nameExplicit, warnings)\n const spec = resolution.spec ?? (!section.nameExplicit ? findOpenApi(files) : null)\n if (spec) {\n let filename = basename(spec.relativePath)\n const existingSource = specFilenameSources.get(filename)\n if (existingSource && existingSource !== spec.absolutePath) {\n const prefix = section.name ? `${section.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')}-` : `${specFilenameSources.size + 1}-`\n filename = `${prefix}${filename}`\n }\n specFilenameSources.set(filename, spec.absolutePath)\n const specContent = readFileSync(spec.absolutePath)\n if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: specContent })\n }\n resolvedSpecs.push({ filename, tabLabel: section.tabLabel, content: specContent, routeSegments: section.routeSegments ?? [] })\n continue\n }\n if (resolution.unsupported.length > 0) {\n const sectionLabel = section.name ? ` for the \"${section.name}\" API` : ''\n for (const entry of resolution.unsupported) {\n warnings.push({\n code: 'unsupported-config',\n message: `${entry.kind === 'asyncapi' ? 'AsyncAPI' : 'OpenRPC'} is not supported by Thally's API reference; the spec \"${entry.path}\"${sectionLabel} was not migrated.`,\n })\n }\n continue\n }\n if (section.name === undefined) continue\n if (fernDefinitionExists(fernProjectRoot, section.name)) {\n warnings.push({\n code: 'unsupported-config',\n message: `This API${section.name ? ` (\"${section.name}\")` : ''} is defined with a Fern Definition, not an OpenAPI/AsyncAPI document; generating a spec from a Fern Definition is not supported. Export an OpenAPI document and reference it from generators.yml, or add it manually.`,\n })\n continue\n }\n // Neither an OpenAPI/AsyncAPI spec nor a Fern Definition could be found\n // for this `api:` node — the API tab was silently dropped from the nav.\n // Name the node so the user knows which one to fix.\n const checked = fernOpenApiCandidateDirs(fernProjectRoot, section.name, section.nameExplicit)\n .map((dir) => relative(repositoryDir, resolvePath(dir, 'generators.yml')).replace(/\\\\/g, '/'))\n if (!section.nameExplicit) checked.push('any openapi or swagger file in the repository')\n warnings.push({\n code: 'unsupported-config',\n message: checked.length\n ? `No OpenAPI/AsyncAPI spec could be found for the \"${section.name}\" API. Checked: ${checked.join(', ')}. Point generators.yml at a spec file that exists.`\n : `No OpenAPI/AsyncAPI spec could be found for the \"${section.name}\" API, because its api-name is not a valid folder name. Add the spec manually.`,\n })\n }\n if (resolvedSpecs.length > 0) {\n docsConfig = injectOpenApiSpecs(docsConfig, resolvedSpecs, warnings)\n // Fern serves each api: section's auto-generated operation pages\n // under that section's own route (e.g. \"api-reference/messages/...\")\n // — the same shape Mintlify's `directory` scoping produces, so the\n // same rewrite applies, keyed by the section's route instead.\n const { operationLinks, prefixLandings } = apiOperationLinkMap(\n resolvedSpecs.map((spec) => ({ filename: spec.filename, content: spec.content, prefix: spec.routeSegments.join('/') })),\n docsConfig,\n )\n rewriteApiLinksInPages(pages, operationLinks, prefixLandings, warnings)\n }\n } else if (platform === 'mintlify') {\n const resolvedSpecs = resolveMintlifyApiSpecs(mintlifyConfig, files, warnings, remoteApiSpecs)\n for (const spec of resolvedSpecs) {\n if (!assets.some((asset) => asset.path === spec.filename)) {\n assets.push({ path: spec.filename, content: spec.content })\n }\n }\n if (resolvedSpecs.length > 0) {\n docsConfig = injectOpenApiSpecs(docsConfig, resolvedSpecs, warnings)\n const { operationLinks, prefixLandings } = apiOperationLinkMap(\n resolvedSpecs.map((spec) => ({ filename: spec.filename, content: spec.content, prefix: spec.directory })),\n docsConfig,\n )\n rewriteApiLinksInPages(pages, operationLinks, prefixLandings, warnings)\n } else {\n // No docs.json-configured spec at all: fall back to a naive repo scan,\n // matching every other platform's baseline behavior.\n const fallback = findOpenApi(files)\n if (fallback) {\n const filename = basename(fallback.relativePath)\n if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: readFileSync(fallback.absolutePath) })\n }\n docsConfig = injectOpenApiSpecs(docsConfig, [{ filename }])\n }\n }\n }\n if (platform === 'mintlify') {\n const sources = new Set((docsConfig.redirects ?? []).map((redirect) => redirect.source))\n const aliases = routeAliases.filter((redirect) => !sources.has(redirect.source))\n if (aliases.length > 0) docsConfig = { ...docsConfig, redirects: [...(docsConfig.redirects ?? []), ...aliases] }\n docsConfig = addMintlifyHomepageRedirects(addMintlifyDirectoryRedirects(docsConfig, pages), pages)\n // `index.mdx` pages often publish at their parent route while source\n // prose still links to `/docs/<locale>/section/index`. Route aliases are\n // known only after the page loop, so include them in this final rewrite.\n const reachablePaths = new Set([\n ...pages.map((page) => page.id),\n ...(docsConfig.redirects ?? []).map((redirect) => redirect.source.replace(/^\\//, '')),\n ])\n for (const page of pages) page.body = rewriteMintlifyMountedLinks(page.body, reachablePaths)\n }\n\n if (platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipPlugins) {\n const additionalRoots: Array<DocusaurusArchiveRoot> = [\n ...additionalDocusaurusPluginRoots(repositoryDir, docusaurusProjectRoot, warnings).map((plugin) => ({\n ...plugin,\n label: plugin.routePrefix.split(/[-_/]/).filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' '),\n })),\n ...docusaurusArchiveRoots(docusaurusProjectRoot, repositoryDir, warnings),\n ]\n for (const plugin of additionalRoots) {\n if (discovered >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Stopped importing Docusaurus docs plugins after ${MAX_SOURCE_FILES} files; the remaining plugin docs were not migrated.` })\n break\n }\n if (plugin.docsDir === configuredDocsDir) continue\n const pluginBundle = migrateRepository({\n ...options,\n docsDir: plugin.docsDir,\n platform: 'docusaurus',\n docusaurusRoutePrefix: plugin.routePrefix,\n docusaurusSkipPlugins: true,\n docusaurusSkipSidebar: !plugin.sidebarPath,\n docusaurusSidebarPath: plugin.sidebarPath,\n docusaurusSkipAssets: true,\n docusaurusSkipRedirects: true,\n })\n for (const page of pluginBundle.pages) {\n if (seenPageIds.has(page.id)) {\n skipped++\n warnings.push({ code: 'collision', message: `Docusaurus docs roots both map to ${page.id}; the first page was kept.`, source: page.source })\n continue\n }\n seenPageIds.add(page.id)\n pages.push(page)\n }\n const assetPaths = new Set(assets.map((asset) => asset.path))\n for (const asset of pluginBundle.assets) {\n if (assetPaths.has(asset.path)) continue\n assetPaths.add(asset.path)\n assets.push(asset)\n }\n const pluginLabel = plugin.label\n docsConfig.tabs.push(...pluginBundle.docsConfig.tabs.map((tab, index) => ({\n ...tab,\n tab: index === 0 ? pluginLabel : `${pluginLabel}: ${tab.tab}`,\n })))\n warnings.push(...pluginBundle.warnings)\n discovered += pluginBundle.stats.discovered\n skipped += pluginBundle.stats.skipped\n }\n }\n\n if (platform === 'docusaurus') {\n // Localized and archived docs are imported as separate roots, often with\n // asset copying disabled. Once all roots are merged, resolve their mounted\n // `/docs/...` references against the assets actually copied by the parent.\n const copiedAssets = new Set(assets.map((asset) => asset.path))\n for (const page of pages) {\n page.body = rewriteDocusaurusLinks(page.body, {\n sourcePath: page.source ?? page.navigationId,\n docId: page.navigationId,\n navigationId: page.navigationId,\n title: page.title,\n }, [], { assetPaths: copiedAssets })\n }\n const importedRoutes = new Set(pages.map((page) => page.navigationId))\n docsConfig.tabs = docsConfig.tabs.map((tab) => {\n if (tab.href) return tab\n const root = tab.tab.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-')\n if (!root || !importedRoutes.has(root)) return tab\n // Auto-generated Docusaurus sidebars can sort an `index.mdx` landing\n // page after alphabetic siblings. Keep the actual tab root as the\n // collection destination, and put it first when it is a direct child.\n return {\n ...tab,\n href: `/${root}`,\n ...(tab.pages ? { pages: tab.pages.map((node) => {\n if (typeof node === 'string') return node\n const index = node.pages.indexOf(root)\n return index > 0\n ? { ...node, pages: [root, ...node.pages.filter((page) => page !== root)] }\n : node\n }) } : {}),\n ...(tab.groups ? { groups: tab.groups.map((group) => {\n const index = group.pages.indexOf(root)\n return index > 0\n ? { ...group, pages: [root, ...group.pages.filter((page) => page !== root)] }\n : group\n }) } : {}),\n }\n })\n }\n\n // Pages skipped above (invalid MDX, a client-boundary function prop, an id\n // collision) never entered `pages`, but the nav was projected from the raw\n // source config and may still reference their ids. Drop those dangling\n // references so `thally check` never reports a nav entry with no MDX file.\n if (platform === 'fern') {\n const byId = new Map(pages.map((page) => [page.navigationId, page]))\n for (const changelog of fernChangelogIndexes) {\n let index = byId.get(changelog.route)\n const entries = changelog.entries\n .map((id) => byId.get(fernIdRenames.get(id) ?? id))\n .filter((page): page is MigrationPage => Boolean(page))\n .slice(0, 10)\n if (entries.length === 0) continue\n if (!index) {\n // A changelog directory may have no overview file at all. Fern still\n // publishes a feed at the tab route, so materialize that route before\n // pruning navigation entries which lack an imported source file.\n index = {\n id: changelog.route,\n navigationId: changelog.route,\n title: 'Release Notes',\n description: 'Latest release notes and product updates.',\n descriptionPlacement: 'body',\n keywords: [],\n body: '',\n source: entries[0].source,\n }\n pages.push(index)\n byId.set(index.navigationId, index)\n docsConfig.redirects = docsConfig.redirects?.filter((redirect) => redirect.source !== `/${changelog.route}`)\n }\n if (index.body.trim()) continue\n // Fern renders changelog directories as a dated feed at the bare tab\n // route. Its `overview.mdx` is often intentionally blank: leaving that\n // page blank strands the release notes even though every entry imports.\n // The feed contains the full articles, including code examples and\n // images. Entry bodies have already gone through normal MDX migration\n // and link/asset rewriting. Pages with module declarations need an\n // excerpt because imports cannot safely be concatenated into one MDX\n // document without renaming all their bindings.\n index.description ||= 'Latest release notes and product updates.'\n index.body = entries.map((entry) => {\n const date = entry.source.match(/\\d{4}-\\d{2}-\\d{2}/)?.[0]\n const escapeText = (value: string): string => value.replace(/([\\\\{}<>\\[\\]*_`])/g, '\\\\$1')\n // The runtime wraps headings in their own permalink anchor. A link\n // inside the heading would create nested anchors and break hydration.\n const body = /^(?:import|export)\\s.+(?:from\\s|\\{)/m.test(entry.body)\n ? escapeText(entry.description)\n : closeOpenCodeFence(date ? addDatedHeadingAliases(entry.body.trim(), date) : entry.body.trim()) || escapeText(entry.description)\n const dateAnchor = date ? `<a id=\"${date}T00:00:00.000Z\" />\\n\\n` : ''\n return `${dateAnchor}## ${escapeText(entry.title)}\\n\\n${date ? `**${date}** · ` : ''}[Read release note](/${entry.id})\\n\\n${body}`\n }).join('\\n\\n---\\n\\n')\n }\n }\n docsConfig = pruneMissingNavigationPages(docsConfig, new Set(pages.map((page) => page.navigationId)))\n if (platform === 'docusaurus') addDocusaurusTranslatedHeadingAliases(pages)\n if (platform === 'fern' && fernProjectRoot) {\n const sourcePath = (page: MigrationPage): string | null => {\n const fragment = page.source.split('#', 2)[1]\n if (!fragment) return null\n try {\n return relative(fernProjectRoot, resolveWithin(repositoryDir, decodeURIComponent(fragment))).replace(/\\\\/g, '/')\n } catch {\n return null\n }\n }\n const routes = new Map<string, string>()\n for (const page of pages) {\n const source = sourcePath(page)\n if (source) routes.set(source, page.id)\n }\n for (const page of pages) {\n const source = sourcePath(page)\n if (source) page.body = rewriteFernRelativePageLinks(page.body, source, routes)\n }\n }\n preserveLinkedAnchors(pages)\n if (platform === 'fern' && fernRawConfig) {\n const sourceSiteUrl = fernSourceSiteUrl(fernRawConfig)\n if (sourceSiteUrl) {\n const externalized = new Set<string>()\n const pageIds = new Set(pages.map((page) => page.id))\n for (const page of pages) page.body = externalizeMissingFernLinks(page.body, pageIds, sourceSiteUrl, externalized)\n if (externalized.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalized.size} unresolved Fern link(s) still point to ${sourceSiteUrl}; import those sections separately for a fully independent site.`,\n })\n }\n }\n if (docsConfig.redirects) {\n docsConfig = {\n ...docsConfig,\n redirects: docsConfig.redirects.filter((redirect) => {\n // A redirect back to the same literal route loops before the page can\n // render. Treat a trailing slash as the same route, while retaining\n // destinations with a query or fragment because they carry intent.\n const literalRoute = (route: string): string | null =>\n route.startsWith('/') && !/[?:*#()[\\]{}]/.test(route)\n ? route.replace(/\\/+$/, '') || '/'\n : null\n const sourceRoute = literalRoute(redirect.source)\n if (sourceRoute && sourceRoute === literalRoute(redirect.destination)) {\n warnings.push({\n code: 'unsupported-config',\n message: `Self-redirect from ${redirect.source} to ${redirect.destination} was omitted.`,\n })\n return false\n }\n // Next's route-pattern parser treats these as operators. Source\n // paths such as Mintlify's literal `/client/c++` must not make the\n // entire generated project fail to build.\n if (!/[+?()[\\]{}]/.test(redirect.source)) return true\n warnings.push({\n code: 'unsupported-config',\n message: `Redirect from ${redirect.source} contains route-pattern syntax Next.js cannot express literally and was omitted.`,\n })\n return false\n }),\n }\n }\n\n if (pages.length === 0) {\n const reasons = warnings.map((warning) => warning.message)\n throw new Error(reasons.length\n ? `No importable Markdown or MDX pages were found in the repository. Warnings encountered during migration:\\n${reasons.map((reason) => `- ${reason}`).join('\\n')}`\n : 'No importable Markdown or MDX pages were found in the repository.')\n }\n // Redirects and branding are global site config, extracted once at the\n // top-level Docusaurus call — `docusaurusSkipRedirects` already marks the\n // recursive per-plugin-instance sub-calls (community/mcp/agent-cli), which\n // would otherwise redundantly re-read (and re-warn about) the same config.\n const isTopLevelDocusaurus = platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipRedirects\n const docusaurusSettings = isTopLevelDocusaurus\n ? readDocusaurusSiteSettings(docusaurusProjectRoot!)\n : undefined\n if (docusaurusSettings) {\n const importedRoutes = new Set(pages.map((page) => page.navigationId))\n const sourceOrigin = readDocusaurusSiteOrigin(docusaurusProjectRoot!)\n const externalized = new Set<string>()\n const projectLink = (raw: string, sourceLiteral = false): string | undefined => {\n if (/^https?:\\/\\//i.test(raw)) return raw\n if (/^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(raw) || raw.includes('\\\\')) return undefined\n const suffixAt = raw.search(/[?#]/)\n const path = suffixAt < 0 ? raw : raw.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : raw.slice(suffixAt)\n const route = path.replace(/^\\.?\\//, '').replace(/\\/+$/, '')\n if (route === '..' || route.startsWith('../') || route.includes('/../')) return undefined\n const docsBase = docusaurusSettings.docsRouteBasePath.replace(/^\\/+|\\/+$/g, '')\n // Literal site links are routes in Docusaurus' URL space. A docs page\n // called \"blog\" must not capture the site's separate /blog section\n // when docs are mounted below /docs.\n const isOutsideDocs = sourceLiteral && docsBase\n && route !== docsBase && !route.startsWith(`${docsBase}/`)\n if (isOutsideDocs && sourceOrigin) {\n externalized.add(raw)\n return new URL(raw, `${sourceOrigin}/`).toString()\n }\n const strippedDocsRoute = docsBase && route.startsWith(`${docsBase}/`)\n ? route.slice(docsBase.length + 1) : route\n const candidates = [route, strippedDocsRoute, ...(route === docsBase ? ['introduction'] : [])]\n const imported = candidates.find((candidate) => importedRoutes.has(candidate))\n if (imported) return `/${imported}${suffix}`\n if (sourceOrigin) {\n externalized.add(raw)\n return new URL(raw, `${sourceOrigin}/`).toString()\n }\n return path.startsWith('/') ? `${path}${suffix}` : `/${route}${suffix}`\n }\n const firstNavigationPage = (nodes: Array<string | MigrationNavigationGroup>): string | undefined => {\n for (const node of nodes) {\n if (typeof node === 'string') return node\n const nested = firstNavigationPage(node.pages)\n if (nested) return nested\n }\n return undefined\n }\n const navbarLinks = docusaurusSettings.navbarLinks.flatMap((link) => {\n const docRoute = link.docId && !link.docsPluginId && docusaurusDescriptors.find((page) =>\n page.docId === link.docId)?.navigationId\n const sidebar = link.sidebarId && docsConfig.tabs.find((tab) =>\n tab.tab.toLowerCase() === link.sidebarId!.toLowerCase())\n const sidebarRoute = sidebar && firstNavigationPage(sidebar.pages ?? sidebar.groups ?? [])\n const pluginRoot = link.docsPluginId && importedRoutes.has(link.docsPluginId)\n ? link.docsPluginId : undefined\n const rawHref = link.href ?? (docRoute ? `/${docRoute}` : undefined)\n ?? (pluginRoot ? `/${pluginRoot}` : undefined)\n ?? (sidebarRoute ? `/${sidebarRoute}` : undefined)\n ?? (link.docsPluginId ? `/${link.docsPluginId}` : undefined)\n const href = rawHref && projectLink(rawHref, Boolean(link.href))\n return href ? [{ label: link.label, href }] : []\n })\n const footerLinks = docusaurusSettings.footerLinks?.flatMap((column) => {\n const items = column.items.flatMap((item) => {\n const href = projectLink(item.href, true)\n return href ? [{ label: item.label, href }] : []\n })\n return items.length > 0 ? [{ heading: column.heading, items }] : []\n })\n docsConfig = {\n ...docsConfig,\n ...(navbarLinks.length > 0 ? { navbar: { ...docsConfig.navbar, links: navbarLinks } } : {}),\n ...(footerLinks?.length || docusaurusSettings.copyright ? {\n footer: {\n ...docsConfig.footer,\n ...(footerLinks?.length ? { links: footerLinks } : {}),\n ...(docusaurusSettings.copyright ? { copyright: docusaurusSettings.copyright } : {}),\n },\n } : {}),\n }\n if (externalized.size > 0) warnings.push({\n code: 'unsupported-config',\n message: `${externalized.size} site navigation/footer link(s) point outside the imported docs and were kept on ${sourceOrigin}.`,\n })\n }\n // Dense version menus should fit in one header row. A dozen archived\n // Docusaurus releases otherwise turn the collection tabs into a tall wall\n // above every document.\n if (!docsConfig.navigation?.display && docsConfig.tabs.filter((tab) => !tab.hidden).length > 6) {\n docsConfig = { ...docsConfig, navigation: { display: 'dropdown' } }\n }\n const themeColors = mintlifyConfig\n ? mintlifyThemeColors(mintlifyConfig.colors)\n : fernRawConfig\n ? fernThemeColors(fernRawConfig.colors)\n : isTopLevelDocusaurus ? readDocusaurusThemeColor(docusaurusProjectRoot!) : undefined\n // Brand assets are copied as ordinary public files. Wire only assets that\n // were actually imported; a missing source file must not create a broken\n // header image or favicon. Admin uploads still override these fallbacks.\n const assetPaths = new Set(assets.map((asset) => asset.path))\n const publicBrandPath = (value: unknown): string | undefined => {\n if (typeof value !== 'string' || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(value)) return undefined\n const normalized = fernBrandAssetPaths.get(value) ?? normalizeAssetPath(value)\n return normalized && assetPaths.has(normalized) ? `/${normalized}` : undefined\n }\n const brandVariants = (value: unknown): { light?: string; dark?: string; showTitle?: boolean } => {\n if (typeof value === 'string') return { light: value }\n if (!value || typeof value !== 'object') return {}\n const source = value as Record<string, unknown>\n const light = source.light ?? source.src\n const dark = source.dark ?? source.srcDark\n return {\n ...(typeof light === 'string' ? { light } : {}),\n ...(typeof dark === 'string' ? { dark } : {}),\n ...(typeof source.showTitle === 'boolean' ? { showTitle: source.showTitle } : {}),\n }\n }\n const sourceLogo = mintlifyConfig?.logo ?? fernRawConfig?.logo ?? docusaurusSettings?.logo\n const sourceFavicon = mintlifyConfig?.favicon ?? fernRawConfig?.favicon ?? docusaurusSettings?.favicon\n const logo = brandVariants(sourceLogo)\n const favicon = brandVariants(sourceFavicon)\n const logoLight = publicBrandPath(logo.light)\n const logoDark = publicBrandPath(logo.dark)\n const faviconLight = publicBrandPath(favicon.light)\n const faviconDark = publicBrandPath(favicon.dark)\n if (logoLight) docsConfig = {\n ...docsConfig,\n navbar: {\n ...docsConfig.navbar,\n logo: {\n light: logoLight,\n ...(logoDark ? { dark: logoDark } : {}),\n showTitle: mintlifyConfig || fernRawConfig ? false : logo.showTitle !== false,\n ...(typeof (fernRawConfig?.logo as Record<string, unknown> | undefined)?.['right-text'] === 'string'\n ? { rightText: String((fernRawConfig!.logo as Record<string, unknown>)['right-text']).trim().slice(0, 40) }\n : {}),\n },\n },\n }\n if (platform === 'docusaurus' && docusaurusSettings?.navbarTitle && !logoLight) {\n // Docusaurus commonly uses a text-only navbar. Its commented-out logo\n // template must not become Thally's unrelated starter leaf mark.\n docsConfig = { ...docsConfig, navbar: { ...docsConfig.navbar, logo: null } }\n }\n if (mintlifyConfig) {\n const appearance = mintlifyConfig.appearance && typeof mintlifyConfig.appearance === 'object'\n ? mintlifyConfig.appearance as Record<string, unknown> : null\n const defaultMode = appearance?.default\n if (defaultMode === 'light' || defaultMode === 'dark' || defaultMode === 'system') {\n docsConfig = { ...docsConfig, appearance: { ...docsConfig.appearance, default: defaultMode } }\n }\n const background = mintlifyConfig.background && typeof mintlifyConfig.background === 'object'\n ? mintlifyConfig.background as Record<string, unknown> : null\n if (background) {\n const decoration = background.decoration\n const image = publicBrandPath(background.image)\n const imageDark = publicBrandPath(background.imageDark)\n docsConfig = {\n ...docsConfig,\n background: {\n ...docsConfig.background,\n ...(decoration === 'none' || decoration === 'grid' || decoration === 'gradient' ? { decoration } : {}),\n ...(image ? { image } : {}),\n ...(imageDark ? { imageDark } : {}),\n },\n }\n }\n }\n if (platform === 'docusaurus') {\n docsConfig = { ...docsConfig, appearance: { ...docsConfig.appearance, default: docusaurusSettings?.defaultColorMode ?? 'light' } }\n }\n if (faviconLight) docsConfig = {\n ...docsConfig,\n favicon: { light: faviconLight, ...(faviconDark ? { dark: faviconDark } : {}) },\n }\n const missingBrand = [\n ...[logo.light, logo.dark].filter((value): value is string => typeof value === 'string' && !publicBrandPath(value)),\n ...[favicon.light, favicon.dark].filter((value): value is string => typeof value === 'string' && !publicBrandPath(value)),\n ]\n if (missingBrand.length > 0) warnings.push({\n code: 'unsupported-config',\n message: `Brand asset(s) were referenced but not imported: ${[...new Set(missingBrand)].join(', ')}. Add these files under public/ or update docs.json.`,\n })\n if (fernRawConfig?.logo && !logoLight && !logo.light) warnings.push({\n code: 'unsupported-config',\n message: 'Fern supplied a logo through its global theme without a local asset; add a logo path to docs.json after import.',\n })\n return {\n sourceUrl: options.sourceUrl,\n sourceKind: 'repository',\n platform,\n pages,\n assets,\n ...(remoteApiSpecs.length > 0 ? { remoteApiSpecs } : {}),\n ...(componentMigrator ? { componentFiles: componentMigrator.files() } : {}),\n docsConfig,\n ...(mintlifyConfig ? {\n site: {\n ...(typeof mintlifyConfig.name === 'string' ? { name: mintlifyConfig.name } : {}),\n ...(typeof mintlifyConfig.description === 'string' ? { description: mintlifyConfig.description } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : fernRawConfig && (typeof fernRawConfig.title === 'string' || themeColors) ? {\n site: {\n ...(typeof fernRawConfig.title === 'string' ? { name: fernRawConfig.title } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : docusaurusSettings && (docusaurusSettings.name || docusaurusSettings.description || themeColors) ? {\n site: {\n ...(docusaurusSettings.navbarTitle || docusaurusSettings.name ? { name: docusaurusSettings.navbarTitle ?? docusaurusSettings.name } : {}),\n ...(docusaurusSettings.description ? { description: docusaurusSettings.description } : {}),\n ...(themeColors ? { colors: themeColors } : {}),\n },\n } : themeColors ? {\n site: { colors: themeColors },\n } : {}),\n warnings,\n stats: { discovered, imported: pages.length, skipped },\n }\n}\n","/**\n * Move repository-owned MDX components into the customer component registry.\n * Source is parsed, never evaluated. Every dependency must remain inside the\n * documentation root and traverse only ordinary files (including its parents).\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, lstatSync, readFileSync } from 'node:fs'\nimport { basename, dirname, extname, relative, resolve } from 'node:path'\nimport postcss from 'postcss'\nimport selectorParser from 'postcss-selector-parser'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport ts from 'typescript'\nimport { unified } from 'unified'\n\nimport { parseFrontmatter } from './frontmatter.js'\nimport { functionDeclaredNames, isFunctionInitializer, normalizeHtmlComments, normalizeExplicitHeadingIds } from './mdx.js'\nimport { resolveWithin } from './path.js'\nimport { planInlineExtraction, unboundTags } from './inline-extraction.js'\nimport type { MigrationWarning, RenderedMigrationFile } from './types.js'\n\ninterface MdxNode {\n type: string\n name?: string | null\n value?: string\n attributes?: Array<{\n name?: string\n type: string\n value?: string | { type?: string; value?: string } | null\n position?: { start: { offset?: number }; end: { offset?: number } }\n }>\n children?: Array<MdxNode>\n position?: { start: { offset?: number }; end: { offset?: number } }\n}\n\ninterface Replacement { start: number; end: number; value: string }\ninterface Binding { local: string; imported: string; source: string }\n\n/** Make JSX-indented fences parse as code before MDX import analysis runs. */\nexport function normalizeIndentedFences(content: string): string {\n const lines = content.split('\\n')\n let active: { indent: string; marker: string } | undefined\n let ordinaryFence: string | undefined\n let indentedJsx: { tag: string; indent: string } | undefined\n let listIndent: number | undefined\n return lines.map((line) => {\n const trimmed = line.trimStart()\n // A fenced example inside list-indented JSX must move together with its\n // container. Unindenting only the fence leaves the tag unclosed; keeping\n // everything indented lets textual import passes mistake example imports\n // for live MDX imports.\n if (indentedJsx) {\n const normalized = line.startsWith(indentedJsx.indent) ? line.slice(indentedJsx.indent.length) : line\n if (normalized.trimStart().startsWith(`</${indentedJsx.tag}>`)) indentedJsx = undefined\n return normalized\n }\n if (ordinaryFence) {\n const closing = trimmed.match(/^(`{3,}|~{3,})\\s*$/)?.[1]\n if (closing && closing[0] === ordinaryFence[0] && closing.length >= ordinaryFence.length) ordinaryFence = undefined\n return line\n }\n if (!active) {\n const listItem = line.match(/^([ \\t]*)(?:[-*+]|\\d+[.)])\\s/)\n const indentation = line.length - trimmed.length\n if (listItem) listIndent = listItem[1].length\n else if (trimmed && listIndent !== undefined && indentation <= listIndent) listIndent = undefined\n const jsx = line.match(/^([ \\t]{2,})<([A-Z][\\w.]*)\\b[^>]*>\\s*$/)\n if (jsx && listIndent !== undefined && jsx[1].length > listIndent && !trimmed.endsWith('/>')) {\n indentedJsx = { tag: jsx[2], indent: jsx[1] }\n return line.slice(jsx[1].length)\n }\n const match = line.match(/^([ \\t]{4,})(`{3,}|~{3,})/)\n if (match) {\n active = { indent: match[1], marker: match[2] }\n return line.slice(match[1].length)\n }\n const ordinary = line.match(/^[ \\t]{0,3}(`{3,}|~{3,})/)\n if (ordinary) ordinaryFence = ordinary[1]\n return line\n }\n const normalized = line.startsWith(active.indent) ? line.slice(active.indent.length) : line\n const closing = normalized.trimStart().match(/^(`{3,}|~{3,})\\s*$/)?.[1]\n if (closing && closing[0] === active.marker[0] && closing.length >= active.marker.length) active = undefined\n return normalized\n }).join('\\n')\n}\n\n/** Lift a self-contained data helper out of a copied client module for server MDX expressions. */\nfunction staticServerHelper(path: string, imported: string, local: string): string | null {\n if (imported === 'default') return null\n const parsed = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n const isLiteral = (node: ts.Expression): boolean => {\n if (ts.isParenthesizedExpression(node)) return isLiteral(node.expression)\n if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isNumericLiteral(node)) return true\n if ([ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(node.kind)) return true\n if (ts.isPrefixUnaryExpression(node)) return [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken].includes(node.operator) && ts.isNumericLiteral(node.operand)\n if (ts.isArrayLiteralExpression(node)) return node.elements.every((element) => ts.isExpression(element) && isLiteral(element))\n if (ts.isObjectLiteralExpression(node)) return node.properties.every((property) => ts.isPropertyAssignment(property)\n && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name))\n && isLiteral(property.initializer))\n return false\n }\n for (const statement of parsed.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name) || declaration.name.text !== imported || !declaration.initializer || !ts.isArrowFunction(declaration.initializer)) continue\n const arrow = declaration.initializer\n if (arrow.parameters.length > 0) continue\n const result = ts.isBlock(arrow.body)\n ? arrow.body.statements.length === 1 && ts.isReturnStatement(arrow.body.statements[0]) ? arrow.body.statements[0].expression : undefined\n : arrow.body\n if (result && isLiteral(result)) return `export const ${local} = () => (${result.getText(parsed)});`\n }\n }\n return null\n}\n\n/** A bare `id`/`videoId`-style attribute value is safe to embed in an `iframe src` only when it looks like a real YouTube video id. */\nconst YOUTUBE_VIDEO_ID = /^[\\w-]{1,64}$/\n/** Packages known to take a literal YouTube video id prop (as opposed to a URL, or a non-YouTube player). */\nconst YOUTUBE_ID_PACKAGES = new Set(['react-lite-youtube-embed', 'react-youtube', '@justinribeiro/lite-youtube'])\nconst YOUTUBE_URL = /(?:youtube\\.com\\/(?:watch\\?v=|embed\\/|shorts\\/)|youtu\\.be\\/)([\\w-]{1,64})/i\n\n/**\n * Only a small, known set of YouTube embed packages get a working `<iframe>`\n * replacement; every other removed component (Vimeo, Loom, a bespoke\n * in-house player, or any package this doesn't recognize) falls back to the\n * plain comment stub, since guessing at an unfamiliar player's embed URL\n * shape would silently render the wrong video or nothing at all.\n */\nfunction youtubeEmbedVideoId(node: MdxNode, specifier: string): string | undefined {\n const attribute = (attributeName: string): string | undefined => {\n const raw = node.attributes?.find((entry) => entry.name === attributeName)?.value\n return typeof raw === 'string' ? raw : undefined\n }\n if (YOUTUBE_ID_PACKAGES.has(specifier)) {\n const id = attribute('id') ?? attribute('videoId')\n return id && YOUTUBE_VIDEO_ID.test(id) ? id : undefined\n }\n if (specifier === 'react-player') {\n const url = attribute('url')\n const match = url ? YOUTUBE_URL.exec(url) : null\n return match ? match[1] : undefined\n }\n return undefined\n}\n\nconst parser = unified().use(remarkParse).use(remarkMdx)\nconst CODE_EXTENSIONS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs'])\nconst DATA_EXTENSIONS = new Set(['.json', '.css', '.svg', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.woff', '.woff2'])\n/**\n * Binary asset types a failed component/module import can still be rescued\n * as: copied verbatim to `public/` and bound to its URL string, rather than\n * losing the reference outright. Includes types `DATA_EXTENSIONS` already\n * lets `copyGraph` copy as a JS-module asset (an image can still fail that\n * path for other reasons — budget, a symlink) and types it never would\n * (`.docx`, `.pdf`: not importable as a JS module, but a real static file).\n */\nconst RESCUABLE_ASSET_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.ico', '.docx', '.pdf'])\n\n/**\n * Tiny equivalents for the handful of Docusaurus theme/runtime imports a\n * copied component commonly uses, so the component still copies instead of\n * failing outright with \"external package requires manual installation\" —\n * the same reasoning as `SCAFFOLD_PROVIDED_IMPORTS`, just for names that\n * only exist inside a Docusaurus build. Deliberately small: anything else\n * Docusaurus-specific (`@docusaurus/Translate`, a theme-common hook, ...)\n * still fails copyGraph and is handled by the dead-import-removal fallback\n * (the catch block below) instead of growing this into a Docusaurus shim\n * layer.\n */\nconst DOCUSAURUS_THEME_SHIMS: Record<string, { filename: string; content: string }> = {\n '@theme/CodeBlock': {\n filename: 'docusaurus-code-block.tsx',\n content: [\n \"import type { ReactNode } from 'react'\",\n '',\n 'export default function CodeBlock({ children, className }: { children?: ReactNode; className?: string }) {',\n ' return (',\n ' <pre className={className}>',\n ' <code>{children}</code>',\n ' </pre>',\n ' )',\n '}',\n '',\n ].join('\\n'),\n },\n '@docusaurus/BrowserOnly': {\n filename: 'docusaurus-browser-only.tsx',\n content: [\n \"'use client'\",\n '',\n \"import { useEffect, useState, type ReactNode } from 'react'\",\n '',\n 'export default function BrowserOnly({ children, fallback = null }: { children: () => ReactNode; fallback?: ReactNode }) {',\n ' const [mounted, setMounted] = useState(false)',\n ' useEffect(() => { setMounted(true) }, [])',\n ' return mounted ? <>{children()}</> : <>{fallback}</>',\n '}',\n '',\n ].join('\\n'),\n },\n}\nconst SHARED_IMPORTS = new Set(['react', 'react/jsx-runtime', 'react/jsx-dev-runtime'])\n/**\n * Packages the standalone starter already installs as its own runtime\n * dependencies. An MDX page's import of one of these (or of a subpath such\n * as `next/navigation` or `lucide-react/dynamic`), even outside JSX, is not\n * \"unavailable\": the package is really there, so the page keeps the import\n * and any extracted client module gets a copy of it.\n *\n * `@/…` path aliases are deliberately absent: in a source repository they\n * point at that site's own code, not at Thally's.\n *\n * Drift-guarded by the \"SCAFFOLD_PROVIDED_IMPORTS drift guard\" test in\n * `packages/migrate/src/__tests__/components.test.ts`.\n */\nexport const SCAFFOLD_PROVIDED_IMPORTS: ReadonlySet<string> = new Set(['next', 'react-dom', 'clsx', 'lucide-react', 'tailwind-merge'])\nfunction isScaffoldProvidedImport(specifier: string): boolean {\n // Next aliases react-dom/server so renderToString/renderToStaticMarkup throw\n // at render; treat it like an unavailable package rather than keep the page.\n if (/^react-dom\\/server(?:[./]|$)/.test(specifier)) return false\n return [...SCAFFOLD_PROVIDED_IMPORTS].some((name) => specifier === name || specifier.startsWith(`${name}/`))\n}\n/** How a warning names an import that is not available in the migrated project. */\nfunction unavailableImportLabel(specifier: string): string {\n return specifier.startsWith('@/')\n ? `the path alias '${specifier}' (the source site's own code, which the migration does not copy)`\n : `the npm package '${specifier}'`\n}\nconst REACT_GLOBALS = new Set([\n 'useState', 'useEffect', 'useLayoutEffect', 'useMemo', 'useCallback', 'useRef',\n 'useReducer', 'useContext', 'useId', 'useTransition', 'useDeferredValue',\n 'useImperativeHandle', 'useSyncExternalStore', 'useInsertionEffect',\n 'useOptimistic', 'useActionState', 'use', 'createContext', 'forwardRef', 'memo',\n])\nconst MAX_COMPONENT_FILES = 300\nconst MAX_COMPONENT_BYTES = 20_000_000\nconst MAX_FILE_BYTES = 2_000_000\n\n/**\n * Where each Thally built-in MDX component actually lives, for building the\n * `MintlifyComponents` shim (below). This must import each leaf module\n * directly rather than the app's `mdx-components.tsx` registry: that\n * registry pulls in `src/mdx/custom-components.tsx`, which re-exports every\n * migrated component — including this very generated file — so importing\n * it here would be circular (`ReferenceError: Cannot access 'X' before\n * initialization` at build time). Kept in sync with\n * `src/components/mdx/builtin-components.tsx`'s own imports by hand; a drift\n * here only means `MintlifyComponents.<Name>` is `undefined` for a name\n * added there, not a crash.\n */\nconst MINTLIFY_COMPONENT_MODULES: ReadonlyArray<{ module: string; names: ReadonlyArray<string> }> = [\n { module: '@/components/mdx/note', names: ['Note'] },\n { module: '@/components/mdx/agent-prompt', names: ['AgentPrompt'] },\n { module: '@/components/mdx/code-blocks', names: ['CodeGroup'] },\n { module: '@/components/mdx/rich-content', names: ['Columns', 'Frame', 'Hero'] },\n { module: '@/components/mdx/accordion', names: ['Accordion', 'AccordionGroup'] },\n { module: '@/components/mdx/content-cards', names: ['Card', 'CardGroup', 'Tile', 'TileGroup'] },\n { module: '@/components/mdx/content-icon', names: ['Icon'] },\n { module: '@/components/mdx/content-inline', names: ['Badge', 'Tooltip'] },\n { module: '@/components/mdx/color', names: ['Color'] },\n { module: '@/components/mdx/content-metadata', names: ['Update'] },\n { module: '@/components/mdx/panel', names: ['Panel', 'ContentPanel', 'InlinePanel'] },\n { module: '@/components/mdx/examples', names: ['RequestExample', 'ResponseExample', 'InlineRequestExample', 'InlineResponseExample'] },\n { module: '@/components/mdx/prompt', names: ['Prompt', 'PromptAssistant', 'PromptUser', 'Terminal', 'TerminalInput', 'TerminalOutput'] },\n { module: '@/components/mdx/file-tree', names: ['Tree', 'Folder', 'File'] },\n { module: '@/components/mdx/api-fields', names: ['ResponseField', 'ParamField', 'Expandable'] },\n { module: '@/components/mdx/mermaid', names: ['Mermaid'] },\n { module: '@/components/mdx/view', names: ['Embed', 'LegacyView', 'View'] },\n { module: '@/components/mdx/github-card', names: ['GitHub'] },\n { module: '@/components/mdx/visibility', names: ['Agent', 'Human', 'Visibility'] },\n { module: '@/components/mdx/steps', names: ['Steps', 'Step'] },\n { module: '@/components/mdx/content-tabs', names: ['Tabs', 'Tab'] },\n]\n\n/** Builtins mapped straight through to their same-named import (aliased, see below). */\nconst MINTLIFY_DIRECT_COMPONENTS = [\n 'AccordionGroup', 'Hero', 'Card', 'CardGroup', 'Columns', 'Frame', 'Accordion', 'Tooltip',\n 'Icon', 'Steps', 'Step', 'Tabs', 'Tab', 'Badge', 'Update', 'RequestExample', 'ResponseExample',\n 'Panel', 'ContentPanel', 'InlinePanel', 'InlineRequestExample', 'InlineResponseExample',\n 'Tile', 'TileGroup', 'Prompt', 'PromptUser', 'PromptAssistant', 'Terminal', 'TerminalInput',\n 'TerminalOutput', 'AgentPrompt', 'Color', 'Tree', 'Folder', 'File', 'ResponseField',\n 'ParamField', 'Expandable', 'Mermaid', 'View', 'Embed', 'LegacyView', 'GitHub', 'Visibility',\n 'Human', 'Agent', 'CodeGroup',\n]\n\n/**\n * Mintlify's implicit `MintlifyComponents` global for a copied `.jsx`\n * snippet (`const { Card } = MintlifyComponents;`, no import) — an object\n * of Thally's built-in equivalents. Every import is aliased (`Card as\n * __mintlify_Card`) so none of ~50 bare names land in the snippet's own top\n * level scope and risk colliding with something it already declares; only\n * the single `MintlifyComponents` identifier is introduced unaliased.\n */\nfunction mintlifyComponentsShim(): string {\n const alias = (name: string) => `__mintlify_${name}`\n const imports = MINTLIFY_COMPONENT_MODULES\n .map(({ module, names }) => `import { ${names.map((name) => `${name} as ${alias(name)}`).join(', ')} } from '${module}';`)\n .join('\\n')\n const entries = [\n // The callout family all render through Note, whose `type` mdx-components.tsx\n // sets for each name; Callout and Latex mirror that file's own handling.\n `Info: (props) => <${alias('Note')} type=\"info\" {...props} />`,\n `Warning: (props) => <${alias('Note')} type=\"warning\" {...props} />`,\n `Check: (props) => <${alias('Note')} type=\"check\" {...props} />`,\n `Danger: (props) => <${alias('Note')} type=\"danger\" {...props} />`,\n `Error: (props) => <${alias('Note')} type=\"danger\" {...props} />`,\n `Note: (props) => <${alias('Note')} type=\"note\" {...props} />`,\n `Tip: (props) => <${alias('Note')} type=\"tip\" {...props} />`,\n `Callout: (props) => <${alias('Note')} {...props} />`,\n `Latex: ({ children }) => <code>{children}</code>`,\n ...MINTLIFY_DIRECT_COMPONENTS.map((name) => `${name}: ${alias(name)}`),\n `Github: ${alias('GitHub')}`,\n ]\n return `${imports}\\nconst MintlifyComponents = {\\n ${entries.join(',\\n ')},\\n};`\n}\n\nfunction applyReplacements(source: string, replacements: Array<Replacement>): string {\n return replacements.sort((a, b) => b.start - a.start).reduce(\n (text, edit) => text.slice(0, edit.start) + edit.value + text.slice(edit.end), source,\n )\n}\n\nfunction hash(value: string): string {\n return createHash('sha256').update(value).digest('hex').slice(0, 12)\n}\n\nfunction portableSpecifier(path: string): string {\n // Customer tsconfigs do not opt into allowImportingTsExtensions. Next's\n // bundler resolves these extensionless source imports without that flag.\n return path.replace(/\\.tsx?$/, '')\n}\n\n/**\n * Turbopack's CSS Modules loader requires every selector to contain at\n * least one class or id (\"pure\"): a copied `.module.css` file that targets\n * `:root`, an element, or an attribute at the top level (a common way to\n * key off a `data-theme` attribute, e.g. Docusaurus' `BrowserWindow`) fails\n * the whole build with `Selector \"...\" is not pure`, even though the\n * selector compiled and worked fine in its own Docusaurus build. Wrap only\n * the impure branches of each rule's selector list in `:global(...)`\n * (CSS Modules' own escape hatch) using a real selector parser — a\n * character-scanning approach can't tell a selector's structure (nesting,\n * combinators, pseudo-classes) from its text reliably enough to know where\n * a `:global(...)` wrapper legally starts and ends.\n */\nfunction wrapImpureCssModuleSelectors(css: string): string {\n const root = postcss.parse(css)\n root.walkRules((rule) => {\n rule.selector = selectorParser((selectors) => {\n selectors.each((selector) => {\n let hasClassOrId = false\n selector.walk((node) => {\n if (node.type === 'class' || node.type === 'id') hasClassOrId = true\n })\n if (hasClassOrId) return\n const nodes = selector.nodes.splice(0, selector.nodes.length)\n const container = selectorParser.selector({ value: '' })\n for (const node of nodes) container.append(node)\n const globalPseudo = selectorParser.pseudo({ value: ':global' })\n globalPseudo.append(container)\n selector.append(globalPseudo)\n })\n }).processSync(rule.selector)\n })\n return root.toString()\n}\n\nfunction sourceFile(source: string, filename: string): ts.SourceFile {\n return ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true,\n /\\.[cm]?ts$/.test(filename) ? ts.ScriptKind.TS : ts.ScriptKind.TSX)\n}\n\nfunction walk(node: MdxNode, visitor: (node: MdxNode) => void): void {\n visitor(node)\n for (const child of node.children ?? []) walk(child, visitor)\n}\n\nfunction implicitReactImports(source: ts.SourceFile): string {\n const bindings = new Set<string>()\n const references = new Set<string>()\n function bind(name: ts.BindingName): void {\n if (ts.isIdentifier(name)) bindings.add(name.text)\n else for (const element of name.elements) if (ts.isBindingElement(element)) bind(element.name)\n }\n for (const statement of source.statements) {\n if (ts.isImportDeclaration(statement) && statement.importClause) {\n const clause = statement.importClause\n if (clause.name) bindings.add(clause.name.text)\n if (clause.namedBindings) {\n if (ts.isNamespaceImport(clause.namedBindings)) bindings.add(clause.namedBindings.name.text)\n else for (const element of clause.namedBindings.elements) bindings.add(element.name.text)\n }\n }\n if (ts.isVariableStatement(statement)) for (const declaration of statement.declarationList.declarations) bind(declaration.name)\n if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) bindings.add(statement.name.text)\n }\n function visit(node: ts.Node): void {\n if (ts.isIdentifier(node) && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)\n && !(ts.isPropertyAssignment(node.parent) && node.parent.name === node)) references.add(node.text)\n ts.forEachChild(node, visit)\n }\n visit(source)\n const hooks = [...REACT_GLOBALS].filter((name) => references.has(name) && !bindings.has(name)).sort()\n // Mintlify's own snippet convention exposes its built-in MDX components as\n // an implicit global too (`const { Card } = MintlifyComponents;`, no\n // import).\n const usesMintlifyComponents = references.has('MintlifyComponents') && !bindings.has('MintlifyComponents')\n // Mintlify also makes built-ins available as bare JSX names inside snippet\n // modules. A copied module runs outside Mintlify's MDX scope, so explicitly\n // import every unbound name it uses before the destination build renders it.\n const implicitComponents = MINTLIFY_COMPONENT_MODULES.map(({ module, names }) => {\n const needed = names.filter((name) => references.has(name) && !bindings.has(name))\n return needed.length ? `import { ${needed.join(', ')} } from '${module}';` : ''\n }).filter(Boolean)\n return [\n references.has('React') && !bindings.has('React') ? \"import * as React from 'react';\" : '',\n hooks.length ? `import { ${hooks.join(', ')} } from 'react';` : '',\n ...implicitComponents,\n usesMintlifyComponents ? mintlifyComponentsShim() : '',\n ].filter(Boolean).join('\\n')\n}\n\n/**\n * A component extracted into its own client module (see `createComponentMigrator`'s\n * inline-hook extraction below) loses the page's implicit access to Thally's\n * built-in MDX components: unlike a component that stays inline in the page,\n * this module never receives a `components` prop to read a name such as\n * `CodeBlock` from. Any JSX tag it uses that isn't locally declared or\n * imported is resolved instead from `builtinMdxComponents`, the same\n * built-in registry every MDX page reads from — imported directly rather\n * than through `useMDXComponents`, which in turn imports the customer\n * registry that imports every extracted module, closing an import cycle\n * that throws at runtime once bundled.\n */\nfunction resolveInlineBuiltinReferences(source: string, moduleNames: ReadonlySet<string>): string {\n const unresolved = unboundTags(source, moduleNames)\n if (unresolved.length === 0) return source\n return [\n \"import { builtinMdxComponents } from '@/components/mdx/builtin-components';\",\n `const { ${unresolved.join(', ')} } = builtinMdxComponents;`,\n source,\n ].join('\\n')\n}\n\nfunction imports(statement: ts.ImportDeclaration): Array<Binding> {\n if (!ts.isStringLiteral(statement.moduleSpecifier) || !statement.importClause) return []\n const clause = statement.importClause\n if (clause.isTypeOnly) return []\n const source = statement.moduleSpecifier.text\n const bindings: Array<Binding> = clause.name ? [{ local: clause.name.text, imported: 'default', source }] : []\n if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n if (!element.isTypeOnly) bindings.push({ local: element.name.text, imported: element.propertyName?.text ?? element.name.text, source })\n }\n }\n return bindings\n}\n\n/**\n * Every component this migrator actually renders in a client boundary — a\n * copied import (`register`, always prefixed 'use client' by `copyGraph`) or\n * an inline-extracted interactive block (`Inline<n>`) — is renamed to one of\n * these two shapes in the transformed body. No other JSX tag (a Thally\n * built-in, an unregistered/removed component) ever matches.\n */\nconst EXTRACTED_CLIENT_COMPONENT_TAG = /^(?:Migrated[0-9a-f]+|Inline\\d+)$/\n\n/**\n * Thally's own runtime `src/components/mdx/builtin-components.tsx` registry names\n * whose backing module is a 'use client' file under `src/components/mdx/`.\n * Passing a page-authored function as a prop into any of these also throws\n * \"Functions cannot be passed directly to Client Components\" at render, the\n * same as an extracted component — so they are confirmed exclusion targets\n * too, not just unconfirmed-and-warned.\n *\n * This list is a snapshot, not a live read of the app (a published migrate\n * package cannot import from the app's `src/`). It is drift-guarded by\n * `src/components/mdx/client-registry.test.ts`, which recomputes the same\n * set from `src/components/mdx/*.tsx` and `builtin-components.tsx` and fails CI\n * if this snapshot goes stale.\n *\n * Source file per name (all under `src/components/mdx/`):\n * Accordion, AccordionGroup -> accordion.tsx\n * AgentPrompt -> agent-prompt.tsx\n * ResponseField, ParamField,\n * Expandable -> api-fields.tsx\n * CodeGroup -> code-blocks.tsx\n * Badge, Tooltip -> content-inline.tsx\n * Tabs, Tab -> content-tabs.tsx\n * RequestExample, ResponseExample,\n * InlineRequestExample,\n * InlineResponseExample -> examples.tsx\n * Tree, Folder, File -> file-tree.tsx\n * Mermaid -> mermaid.tsx\n * Panel, ContentPanel,\n * InlinePanel -> panel.tsx\n * Prompt, PromptUser,\n * PromptAssistant, Terminal,\n * TerminalInput, TerminalOutput -> prompt.tsx\n * View, Embed, LegacyView -> view.tsx\n * Color, Color.Item -> color.tsx (server) spreads props into\n * color-item.tsx's 'use client'\n * ColorItemClient — a re-export, not a\n * direct 'use client' file, so it is\n * listed by hand (see the override map\n * in client-registry.test.ts)\n */\nexport const CLIENT_BUILTIN_COMPONENT_TAGS: ReadonlySet<string> = new Set([\n 'Accordion', 'AccordionGroup',\n 'AgentPrompt',\n 'ResponseField', 'ParamField', 'Expandable',\n 'CodeGroup', 'CodeBlock',\n 'Badge', 'Tooltip',\n 'Tabs', 'Tab',\n 'RequestExample', 'ResponseExample', 'InlineRequestExample', 'InlineResponseExample',\n 'Tree', 'FileTree', 'Folder', 'File',\n 'Mermaid',\n 'Panel', 'ContentPanel', 'InlinePanel',\n 'Prompt', 'PromptUser', 'PromptAssistant', 'Terminal', 'TerminalInput', 'TerminalOutput',\n 'View', 'Embed', 'LegacyView',\n 'Color', 'Color.Item',\n])\n\nfunction isConfirmedClientBoundaryTag(name: string): boolean {\n return EXTRACTED_CLIENT_COMPONENT_TAG.test(name) || CLIENT_BUILTIN_COMPONENT_TAGS.has(name)\n}\n\n/**\n * A JSX attribute's raw expression source (`prop={<this>}`), for the two\n * shapes that end up passing a function value: a bare reference to a\n * page-declared function (`declaredNames`), or a function written inline\n * right there (`() => ...`, `function () { ... }`). Only `mdxJsxAttribute`\n * nodes with an expression value carry a source string here; a string\n * literal attribute (`title=\"x\"`) or a spread (`mdxJsxExpressionAttribute`)\n * never does, so this returns `undefined` for those.\n */\nfunction functionValuedAttribute(node: MdxNode, declaredNames: ReadonlySet<string>): string | undefined {\n const isFunctionValue = (value: string) => declaredNames.has(value.trim()) || isFunctionInitializer(value.trim(), 0)\n for (const attribute of node.attributes ?? []) {\n const raw = attribute.value\n const value = raw && typeof raw === 'object' ? raw.value : undefined\n if (typeof value !== 'string') continue\n if (isFunctionValue(value)) return value\n }\n // Function-as-children (`<Accordion>{() => 'x'}</Accordion>`) is passed as\n // the `children` prop, so it crosses the same boundary. Inline children sit\n // inside a paragraph node; look one level into it.\n const children = (node.children ?? []).flatMap((child) => child.type === 'paragraph' ? child.children ?? [] : [child])\n for (const child of children) {\n if (['mdxFlowExpression', 'mdxTextExpression'].includes(child.type) && child.value && isFunctionValue(child.value)) return child.value\n }\n return undefined\n}\n\n/**\n * True when a name in `declaredNames` (typically a page's `export const`/\n * `export function` identifiers) is passed as a bare JSX prop\n * (`prop={Name}`), or a function is written inline as a prop value\n * (`prop={() => ...}`, `prop={function () { ... }}`), into a component\n * confirmed to cross the server/client boundary: one this migrator extracted\n * as a 'use client' module, or a Thally runtime built-in already backed by\n * one (`CLIENT_BUILTIN_COMPONENT_TAGS`). This is the only shape that really\n * throws \"Functions cannot be passed directly to Client Components\" at\n * render — the same check against an unconfirmed tag would over-fire and\n * drop pages that render just fine.\n *\n * JSX written inside a page's own `export const Name = () => <...>` (bound\n * for client extraction itself) is never visited here: `remark-mdx` parses\n * that whole declaration as a single `mdxjsEsm` text node, not as MDX JSX\n * element nodes, so `walk`'s `.children` traversal never reaches it — the\n * same reason fenced/inline code samples (parsed as `code`/`inlineCode` text\n * nodes) never reach it either.\n */\nexport function propsTargetExtractedClientComponent(body: string, declaredNames: ReadonlySet<string>): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n walk(tree, (node) => {\n if (found || !node.name || !isConfirmedClientBoundaryTag(node.name)) return\n if (functionValuedAttribute(node, declaredNames) !== undefined) found = true\n })\n return found\n}\n\n/**\n * Broader, unconfirmed signal: true when *any* JSX tag on the page (not\n * just a confirmed client boundary) receives a function-valued prop, the\n * same shapes `propsTargetExtractedClientComponent` looks for. Callers use\n * this to decide whether the page is worth a \"might throw at render, review\n * manually\" warning even when the receiving tag's own client/server status\n * cannot be confirmed.\n */\nexport function hasAnyFunctionValuedProp(body: string, declaredNames: ReadonlySet<string>): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n walk(tree, (node) => {\n if (found || !node.name) return\n if (functionValuedAttribute(node, declaredNames) !== undefined) found = true\n })\n return found\n}\n\n/**\n * True when a page's own inline `export const`/`export function` declaration\n * (kept in place, not extracted into a 'use client' module — see the\n * `mdxjsEsm` note above) references `document` or `window` as an identifier.\n * Next renders an MDX page as a Server Component by default, where neither\n * global exists; callers use this to warn rather than let the page fail at\n * render. Identifiers are found via the TS AST, so a string, comment, or\n * fenced code sample using the same words never counts.\n */\nexport function declarationsReferenceBrowserGlobal(body: string): boolean {\n const tree = parser.parse(body) as MdxNode\n let found = false\n function inspect(node: ts.Node): void {\n if (ts.isIdentifier(node) && (node.text === 'document' || node.text === 'window')) found = true\n ts.forEachChild(node, inspect)\n }\n for (const node of tree.children ?? []) {\n if (found || node.type !== 'mdxjsEsm' || node.value === undefined) continue\n for (const statement of sourceFile(node.value, 'inline.tsx').statements) {\n if (ts.isVariableStatement(statement) || ts.isFunctionDeclaration(statement)) inspect(statement)\n }\n }\n return found\n}\n\n/** Create one bounded component graph and registry for a repository migration. */\n/**\n * `siteRoot` (a Mintlify/Docusaurus project root, when one was detected —\n * `repositoryDir` otherwise) is what `@site/...`/root-relative (`/...`)\n * specifiers resolve against, matching Docusaurus' own alias semantics; a\n * warning's reported `source` and the generated destination paths stay\n * relative to it too, unchanged from before this parameter split. A plain\n * relative import (`../../components/X`), though, is written relative to\n * the importing *page*, which — in a monorepo where docs/ is a sibling of\n * website/ rather than nested under it (Redux) — can resolve outside\n * `siteRoot` even for a component the repository legitimately owns.\n * `confinementRoot` (always `repositoryDir`) is the actual security\n * boundary for that resolution and for `checkedFile`'s symlink safety walk,\n * so such an import still copies instead of throwing \"path escapes its\n * root\" for a component this migration should have imported.\n */\n\n/**\n * Text-only safety net for a page whose MDX can't be parsed at all (see the\n * catch below `transform`'s own `parser.parse` call): with no AST to drive a\n * real copy/removal, this only guarantees the page still builds by dropping\n * a `@site/...`/relative component import and blanking its JSX usage,\n * narrowly matching the single-binding default/named-as-default shape\n * `SNIPPET_IMPORT_PATTERN` (repository.ts) already uses for the same reason.\n * A bare npm-package import is left alone — that failure mode (\"module not\n * installed\") is unrelated to why this page's MDX didn't parse, and this\n * pass has no way to tell whether it is actually used anywhere.\n */\nfunction neutralizeUnresolvableImportsWithoutAst(content: string, currentFile: string, warn: (message: string, source: string) => void): string {\n const importPattern = /^import\\s+(?:\\{\\s*(?:default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}|([A-Z][A-Za-z0-9_]*))\\s+from\\s+(['\"])((?:@site\\/|\\.\\.?\\/|\\/)[^'\"]+)\\3\\s*;?[ \\t]*$/gm\n const dropped: Array<{ name: string; specifier: string }> = []\n let result = content.replace(importPattern, (_match, namedComponent: string | undefined, defaultComponent: string | undefined, _quote: string, specifier: string) => {\n dropped.push({ name: (namedComponent ?? defaultComponent) as string, specifier })\n return ''\n })\n for (const { name, specifier } of dropped) {\n warn(`Component import ${JSON.stringify(specifier)} could not be resolved because this page has invalid MDX (see the previous warning), so the import and its usage were removed to keep the site building.`, currentFile)\n result = result\n .replace(new RegExp(`<${name}(?:\\\\s[^>]*)?/>`, 'g'), `{/* Removed <${name}>: unresolved during fallback migration */}`)\n .replace(new RegExp(`<${name}(?:\\\\s[^>]*)?>[\\\\s\\\\S]*?<\\\\/${name}>`, 'g'), `{/* Removed <${name}>: unresolved during fallback migration */}`)\n }\n return result\n}\n\nexport function createComponentMigrator(siteRoot: string, confinementRoot: string, warnings: Array<MigrationWarning>, sourceIdentity: string): {\n transform: (raw: string, currentFile: string) => string\n files: () => Array<RenderedMigrationFile>\n} {\n const root = resolve(siteRoot)\n const confined = resolve(confinementRoot)\n // A destination can contain imports from several repositories with identical\n // snippet names. Stable source identity isolates their graphs without tying\n // registry names to a temporary checkout path or changing repeat imports.\n const destinationRoot = `src/mdx/migrated/${hash(sourceIdentity)}`\n const copied = new Map<string, RenderedMigrationFile>()\n const registrations = new Map<string, { path: string; imported: string }>()\n let copiedBytes = 0\n\n function warn(message: string, source: string): void {\n warnings.push({ code: 'unsupported-config', message, source: relative(root, source).replace(/\\\\/g, '/') })\n }\n\n function checkedFile(path: string): string {\n const local = relative(confined, path)\n resolveWithin(confined, local)\n let current = confined\n if (lstatSync(current).isSymbolicLink()) throw new Error('symbolic links are not imported')\n for (const segment of local.split(/[\\\\/]/)) {\n current = resolveWithin(current, segment)\n if (lstatSync(current).isSymbolicLink()) throw new Error('symbolic links are not imported')\n }\n if (!lstatSync(path).isFile()) throw new Error('dependency is not a regular file')\n return path\n }\n\n function expandCandidates(candidate: string): Array<string> {\n const candidates = [candidate]\n if (!extname(candidate)) {\n candidates.push(...['.tsx', '.jsx', '.ts', '.js', '.mjs', '.json'].map((extension) => candidate + extension))\n candidates.push(...['index.tsx', 'index.jsx', 'index.ts', 'index.js'].map((name) => resolve(candidate, name)))\n } else if (extname(candidate) === '.js') {\n candidates.push(candidate.slice(0, -3) + '.ts', candidate.slice(0, -3) + '.tsx')\n }\n return candidates\n }\n\n /**\n * `allowFlattenedMirror` gates the repository-root retry for a *plain\n * relative* specifier (`./x`, `../x`) below. It must stay narrow: a\n * relative import resolves relative to the importing file by standard\n * Node semantics, full stop — rebasing that resolution onto the\n * repository root for every project with a nested docs directory (the\n * ordinary case, not a monorepo) let a missing/broken import like\n * `./bogus` silently resolve to an unrelated same-named file that\n * happens to live at the mirrored repository-root path, instead of\n * being reported as unresolvable. The one real need for a mirror is\n * Playwright's own build (`cp -r nodejs/* .` flattens the `nodejs/`\n * project root's contents, including its shared `images/`, up into the\n * repository root before the site is generated), reached only through\n * the `require('../asset.ext')` idiom below — so only that call site\n * passes `true`. Every ordinary component/`import` resolution passes\n * `false` (the default) and never rebases.\n */\n function resolveDependency(specifier: string, importer: string, allowFlattenedMirror = false): string {\n if (specifier.includes('\\\\') || specifier.includes('\\0') || /[?#]/.test(specifier)) throw new Error('unsupported component dependency path')\n const candidates = specifier.startsWith('/')\n ? expandCandidates(resolveWithin(root, specifier.slice(1)))\n : expandCandidates(resolveWithin(confined, relative(confined, resolve(dirname(importer), specifier))))\n // A root-relative `@site/...`/`/...` specifier is Docusaurus' own alias\n // for its *project* root; when the shared component it names isn't\n // nested under the narrower detected project root, it can still be a\n // real, unambiguous repository-root path (Playwright's shared\n // `src/components` tree is a sibling of the `nodejs/` project, not\n // nested under it) — tried only after the direct, project-rooted path\n // fails. This is safe even outside a flattened-build layout: the\n // specifier itself names an absolute-from-some-root path, so the retry\n // can't be fooled into matching an unrelated file the way a *relative*\n // import's rebase (below) can.\n if (root !== confined && specifier.startsWith('/')) {\n candidates.push(...expandCandidates(resolveWithin(confined, specifier.slice(1))))\n }\n if (root !== confined && !specifier.startsWith('/') && allowFlattenedMirror) {\n try {\n const rebasedImporter = resolveWithin(confined, relative(root, importer))\n candidates.push(...expandCandidates(resolveWithin(confined, relative(confined, resolve(dirname(rebasedImporter), specifier)))))\n } catch {\n // Importer itself is outside the project root; nothing to rebase.\n }\n }\n for (const path of candidates) {\n if (existsSync(path) && lstatSync(path).isFile()) return checkedFile(path)\n }\n throw new Error(`component dependency ${specifier} was not found`)\n }\n\n function outputPath(path: string): string {\n // Must be `confined`, not `root`: a component reached via a relative\n // import from outside `root` (see `resolveDependency`) is still inside\n // `confined`, and a `../`-containing destination path would risk\n // writing outside `destinationRoot`.\n return `${destinationRoot}/source/${relative(confined, path).replace(/\\\\/g, '/')}`\n }\n\n function copyGraph(entry: string): string {\n // Stage the entire graph in memory. A missing leaf must not leave a partly\n // registered component or consume the successful-copy budget.\n const staged = new Map<string, RenderedMigrationFile>()\n let stagedBytes = 0\n /** Stage a small fixed-content shim module (see `DOCUSAURUS_THEME_SHIMS`) once, reused across every component that imports it. */\n function stageShim(filename: string, content: string): string {\n const shimDestination = `${destinationRoot}/shims/${filename}`\n if (!copied.has(shimDestination) && !staged.has(shimDestination)) staged.set(shimDestination, { path: shimDestination, content })\n return shimDestination\n }\n function visit(path: string): void {\n const destination = outputPath(path)\n if (copied.has(destination) || staged.has(destination)) return\n checkedFile(path)\n const size = lstatSync(path).size\n if (size > MAX_FILE_BYTES || copiedBytes + stagedBytes + size > MAX_COMPONENT_BYTES\n || copied.size + staged.size >= MAX_COMPONENT_FILES) throw new Error('component migration budget exceeded')\n const extension = extname(path).toLowerCase()\n if (!CODE_EXTENSIONS.has(extension) && !DATA_EXTENSIONS.has(extension)) throw new Error(`unsupported dependency file type ${extension}`)\n stagedBytes += size\n const content = readFileSync(path)\n staged.set(destination, { path: destination, content })\n if (!CODE_EXTENSIONS.has(extension)) {\n if (extension === '.css' && /@import\\b|url\\s*\\(/i.test(content.toString('utf8'))) throw new Error('CSS resource dependencies require manual migration')\n if (extension === '.css' && path.toLowerCase().endsWith('.module.css')) {\n // A parse failure here (malformed CSS, an SCSS-only construct that\n // isn't valid CSS, ...) is treated the same as any other copy\n // failure: throw, so the dead-import-removal fallback in the\n // caller can neutralize its usage instead of shipping CSS\n // Turbopack would reject anyway.\n let wrapped: string\n try {\n wrapped = wrapImpureCssModuleSelectors(content.toString('utf8'))\n } catch {\n throw new Error('CSS module could not be parsed to check for Turbopack-safe selectors')\n }\n staged.set(destination, { path: destination, content: wrapped })\n }\n return\n }\n const text = content.toString('utf8')\n const syntax = ts.transpileModule(text, { fileName: path, reportDiagnostics: true,\n compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext } })\n if (syntax.diagnostics?.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) throw new Error('component source contains unsupported JavaScript or TypeScript syntax')\n const ast = sourceFile(text, path)\n if (ast.statements.some((statement) => ts.isExpressionStatement(statement)\n && ts.isStringLiteral(statement.expression) && statement.expression.text === 'use server')) throw new Error('server-only component modules require manual migration')\n const edits: Array<Replacement> = []\n function dependency(literal: ts.StringLiteralLike, importDeclaration?: ts.ImportDeclaration): void {\n const specifier = literal.text\n if (SHARED_IMPORTS.has(specifier) || isScaffoldProvidedImport(specifier)) return\n // `@docusaurus/Link` maps onto `next/link` (already scaffold-provided)\n // rather than a shim module: same default export, only its `to` prop\n // is renamed to `href` wherever the copied file itself uses the tag.\n if (specifier === '@docusaurus/Link') {\n edits.push({ start: literal.getStart(ast), end: literal.end, value: '\"next/link\"' })\n const localName = importDeclaration?.importClause?.name?.text\n if (localName) {\n function renameToProp(node: ts.Node): void {\n if (ts.isJsxAttribute(node) && node.name.getText(ast) === 'to'\n && ts.isJsxOpeningLikeElement(node.parent.parent)\n && node.parent.parent.tagName.getText(ast) === localName) {\n edits.push({ start: node.name.getStart(ast), end: node.name.end, value: 'href' })\n }\n ts.forEachChild(node, renameToProp)\n }\n renameToProp(ast)\n }\n return\n }\n const shim = DOCUSAURUS_THEME_SHIMS[specifier]\n if (shim) {\n const shimPath = stageShim(shim.filename, shim.content)\n const nextPath = relative(dirname(destination), shimPath).replace(/\\\\/g, '/')\n edits.push({ start: literal.getStart(ast), end: literal.end, value: JSON.stringify(portableSpecifier(nextPath.startsWith('.') ? nextPath : `./${nextPath}`)) })\n return\n }\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n throw new Error(specifier.startsWith('@/')\n ? `path alias ${specifier} points to source-site code the migration does not copy`\n : `external package ${specifier} requires manual installation and review`)\n }\n const target = resolveDependency(specifier, path)\n visit(target)\n const nextPath = relative(dirname(destination), outputPath(target)).replace(/\\\\/g, '/')\n edits.push({ start: literal.getStart(ast), end: literal.end, value: JSON.stringify(portableSpecifier(nextPath.startsWith('.') ? nextPath : `./${nextPath}`)) })\n }\n function inspect(node: ts.Node): void {\n if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {\n dependency(node.moduleSpecifier, ts.isImportDeclaration(node) ? node : undefined)\n }\n if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword\n || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {\n const argument = node.arguments[0]\n if (node.arguments.length !== 1 || !argument || !ts.isStringLiteralLike(argument)) throw new Error('computed component imports require manual migration')\n dependency(argument)\n }\n ts.forEachChild(node, inspect)\n }\n inspect(ast)\n // Mark copied code as client-owned even when the source platform inferred\n // its client boundary. Browser hooks must never run in MDX's server scope.\n // The source site never ran `next build`'s full `tsc --noEmit` type\n // check (Docusaurus/Mintlify/Fern don't gate their own build on it),\n // so loose types, `window.ethereum`-style ambient globals, and\n // implicit `any` parameters that were fine there fail it here.\n // `@ts-nocheck` is valid in both `.ts(x)` and `.js(x)` files (a no-op\n // unless `checkJs` is on) and is the least invasive fix: it preserves\n // the component's real behavior instead of stripping or rewriting it.\n const replaced = applyReplacements(text, edits)\n // A `#!/...` shebang is only special on line 1 of the file (Node\n // strips it before parsing only there); inserting the `@ts-nocheck`\n // prologue above it would both break that and, since `// @ts-nocheck`\n // isn't itself a shebang, leave a dead shebang-looking comment mid\n // file. If the copied source starts with one, keep it first and\n // insert the prologue right after instead.\n const shebangMatch = /^#!.*\\r?\\n/.exec(replaced)\n const prologue = \"// @ts-nocheck\\n'use client';\\n\\n\"\n staged.set(destination, {\n path: destination,\n content: shebangMatch\n ? shebangMatch[0] + prologue + implicitReactImports(ast) + '\\n' + replaced.slice(shebangMatch[0].length)\n : prologue + implicitReactImports(ast) + '\\n' + replaced,\n })\n }\n visit(entry)\n for (const [path, file] of staged) copied.set(path, file)\n copiedBytes += stagedBytes\n return outputPath(entry)\n }\n\n /**\n * Copy a binary asset verbatim to a stable `public/` path (bypassing\n * `copyGraph`'s JS-module handling entirely — the asset is bound to its\n * URL string, never imported as a module) and return that URL. Used when\n * an import couldn't be copied as a component but names a real file the\n * page only ever references by URL (`src={Logo}`), never as a JSX tag.\n */\n function copyPublicAsset(path: string): string {\n checkedFile(path)\n const size = lstatSync(path).size\n if (size > MAX_FILE_BYTES || copiedBytes + size > MAX_COMPONENT_BYTES || copied.size >= MAX_COMPONENT_FILES) {\n throw new Error('component migration budget exceeded')\n }\n const publicName = `migrated-${hash(relative(confined, path))}${extname(path).toLowerCase()}`\n const destination = `public/${publicName}`\n if (!copied.has(destination)) {\n copied.set(destination, { path: destination, content: readFileSync(path) })\n copiedBytes += size\n }\n return `/${publicName}`\n }\n\n /**\n * Docusaurus ships SVGR out of the box, so `import Foo from './foo.svg';\n * <Foo />` renders the SVG as a real component there. The migrated\n * project has no SVGR loader, so importing an `.svg` file the ordinary\n * way (`copyGraph`'s ordinary path, used below) yields whatever the\n * bundler's default asset handling returns for it — a URL string or a\n * `{ src }` object, either way not a valid React element type — and\n * `<Foo />` throws \"Element type is invalid\" at render. Used only when\n * the import is actually rendered as a JSX tag (an attribute-only usage,\n * `src={Foo}`, needs no wrapper and is left as the plain import): stage a\n * tiny companion module next to the copied SVG that imports it as a URL\n * either way and renders a plain `<img>`, and register that instead of\n * the raw file.\n */\n function wrapSvgAsComponent(svgOutputPath: string): string {\n const wrapperPath = `${svgOutputPath}.component.tsx`\n if (!copied.has(wrapperPath)) {\n const content = [\n \"'use client'\",\n '',\n `import svgSource from ${JSON.stringify(`./${basename(svgOutputPath)}`)}`,\n '',\n 'export default function SvgImage(props: Record<string, unknown>) {',\n ' const src = typeof svgSource === \"string\" ? svgSource : (svgSource as { src: string }).src',\n ' // eslint-disable-next-line @next/next/no-img-element -- no SVGR loader is configured; this renders the raw file.',\n ' return <img src={src} alt=\"\" {...props} />',\n '}',\n '',\n ].join('\\n')\n copied.set(wrapperPath, { path: wrapperPath, content })\n }\n return wrapperPath\n }\n\n function register(path: string, imported: string): string {\n const name = `Migrated${hash(`${path}:${imported}`)}`\n registrations.set(name, { path, imported })\n return name\n }\n\n function transform(raw: string, currentFile: string): string {\n const parsedFrontmatter = parseFrontmatter(raw).content\n const frontmatter = raw.slice(0, raw.length - parsedFrontmatter.length)\n // remark-mdx does not parse a raw HTML comment (`<!-- ... -->`) at all —\n // a real source page commonly has one (Docusaurus' own\n // `<!-- prettier-ignore -->` ahead of a snippet import) and it\n // otherwise throws here before this pass ever runs, leaving whatever\n // import that comment sits near completely untouched. `normalizeMdx`\n // converts the same syntax later in the pipeline anyway, so doing it\n // here too (on this function's own working copy) is never wasted work.\n // Likewise a heading's explicit `{#custom-id}` suffix is never valid MDX\n // (a bare `{...}` in prose is always parsed as a JS expression, and no\n // JS expression starts with `#`) regardless of platform, so converting\n // it up front is always safe — and it must happen before this\n // function's own parse below, or that parse throws first and this\n // whole page's import analysis is skipped instead of just this one\n // page's expression.\n const content = normalizeExplicitHeadingIds(normalizeIndentedFences(normalizeHtmlComments(parsedFrontmatter)))\n let tree: MdxNode\n try {\n tree = parser.parse(content) as MdxNode\n } catch {\n warn('Custom component analysis could not parse this MDX; its source was preserved for manual migration.', currentFile)\n // The AST walk below is how every `@site/...`/relative component\n // import normally gets copied or removed; none of that runs on a page\n // that can't even be parsed. Left alone, an import like that survives\n // verbatim and breaks `next build` with \"Module not found\" for the\n // whole site, not just this page — the same failure mode the AST path\n // already guards against everywhere else. This is a text-only,\n // best-effort safety net (no AST here to drive a real copy), narrow by\n // design: only the single-binding default/named-as-default import\n // shape actually seen in practice, mirroring `SNIPPET_IMPORT_PATTERN`.\n return frontmatter + neutralizeUnresolvableImportsWithoutAst(content, currentFile, warn)\n }\n const aliases = new Map<string, string>()\n const unsupportedImports = new Map<string, string>()\n // Local names dropped by the lowercase-named `.mdx?` import case below\n // (Docusaurus' auto-generated per-file `toc` export, merged into\n // another page's own `toc` via `...viewsToc`) — collected here so the\n // spread-removal pass after the main walk can find every one of them,\n // regardless of which esmNode declared the import vs. used it.\n const droppedMdxDataBindings = new Set<string>()\n const edits: Array<Replacement> = []\n const declarations: Array<{ start: number; end: number; source: string }> = []\n const moduleImports: Array<string> = []\n const realPageImports: Array<string> = []\n const serverPageDeclarations: Array<string> = []\n const sharedImportEdits: Array<Replacement> = []\n let hasUnsupportedImports = false\n function hasExpressionReference(names: Set<string>, options: {\n excludedNodes?: Array<MdxNode>\n includeDeclarations?: boolean\n includeDirectTags?: boolean\n } = {}): boolean {\n let found = false\n function inspect(node: ts.Node): void {\n if (ts.isIdentifier(node) && names.has(node.text)) found = true\n ts.forEachChild(node, inspect)\n }\n walk(tree, (node) => {\n if (options.excludedNodes?.some((excluded) => node.position?.start.offset !== undefined\n && node.position.end.offset !== undefined\n && node.position.start.offset >= excluded.position!.start.offset!\n && node.position.end.offset <= excluded.position!.end.offset!)) return\n if (node.name && [...names].some((name) => node.name!.startsWith(`${name}.`)\n || (options.includeDirectTags && node.name === name))) found = true\n if (options.includeDeclarations !== false && node.type === 'mdxjsEsm' && node.value) {\n for (const statement of sourceFile(node.value, 'expression.tsx').statements) {\n if (!ts.isImportDeclaration(statement)) inspect(statement)\n }\n }\n const expressions = [\n ...(['mdxFlowExpression', 'mdxTextExpression'].includes(node.type) ? [node.value ?? ''] : []),\n ...(node.attributes ?? []).flatMap((attribute) => {\n if (attribute.type === 'mdxJsxExpressionAttribute' && typeof attribute.value === 'string') return [attribute.value]\n return attribute.value && typeof attribute.value === 'object' ? [attribute.value.value ?? ''] : []\n }),\n ]\n for (const expression of expressions) inspect(sourceFile(expression, 'expression.tsx'))\n })\n return found\n }\n /** True when `name` is ever a JSX tag's own root name (`<name ...>`), regardless of any other usage — narrower than `hasExpressionReference`'s combined signal, needed where a string binding (an asset's URL) is fine for any *other* usage but not this one. */\n function usedAsJsxTagName(name: string): boolean {\n let found = false\n walk(tree, (node) => { if (node.name === name) found = true })\n return found\n }\n // Docusaurus allows a real `import`/`export` ESM block anywhere in the\n // body, not just at the top of the file — a documentation page\n // demonstrating a live code example commonly nests one inside a JSX\n // wrapper (`<BrowserWindow>\\nimport Foo from './foo.svg'\\n\\n<Foo\n // /></BrowserWindow>`, straight from Docusaurus' own docs). remark-mdx\n // still parses each as its own `mdxjsEsm` node, just nested under that\n // wrapper's `children` instead of `tree.children` directly, so this\n // must walk the whole tree to find every one of them; a scan of only\n // `tree.children` silently skips a nested import, leaving the page\n // referencing a path the migrated project never has (\"Module not\n // found\") without any warning at all.\n const esmNodes: Array<MdxNode> = []\n walk(tree, (node) => { if (node.type === 'mdxjsEsm') esmNodes.push(node) })\n for (const node of esmNodes) {\n if (node.value === undefined || node.position?.start.offset === undefined) continue\n const ast = sourceFile(node.value, 'inline.tsx')\n for (const statement of ast.statements) {\n if (!ts.isImportDeclaration(statement)) {\n let unsupportedDependency = ts.isExportDeclaration(statement) && !!statement.moduleSpecifier\n function inspect(node: ts.Node): void {\n if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword\n || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) unsupportedDependency = true\n ts.forEachChild(node, inspect)\n }\n inspect(statement)\n if (unsupportedDependency) {\n hasUnsupportedImports = true\n warn('Inline MDX module dependencies require manual extraction; source was preserved.', currentFile)\n }\n declarations.push({\n start: node.position.start.offset + statement.getStart(ast),\n end: node.position.start.offset + statement.end,\n source: statement.getText(ast),\n })\n continue\n }\n const bindings = imports(statement)\n const rawSpecifier = ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : ''\n // `@site/...` is Docusaurus' and Mintlify's shared alias for the\n // project root; treat it exactly like the root-relative `/...` form\n // `resolveDependency` already understands, so a locally-owned\n // component copies the same way a relative import would.\n const specifier = rawSpecifier.startsWith('@site/') ? `/${rawSpecifier.slice('@site/'.length)}` : rawSpecifier\n if (isScaffoldProvidedImport(specifier)) {\n // Some translated Mintlify pages place a React hook import above a\n // fenced example. Keeping that unused import turns server MDX into\n // a module that illegally imports a client-only hook.\n if (specifier === 'react' && bindings.length > 0\n && bindings.every((binding) => REACT_GLOBALS.has(binding.imported))\n && !hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n continue\n }\n // Installed in the migrated project: keep it on the page (content\n // outside an extracted block may use it) and copy it into any\n // extracted client module, whose moved declarations may use it too.\n moduleImports.push(statement.getText(ast))\n continue\n }\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n if (SHARED_IMPORTS.has(specifier)) {\n const isUnusedReactHookImport = specifier === 'react' && bindings.length > 0\n && bindings.every((binding) => REACT_GLOBALS.has(binding.imported))\n && !hasExpressionReference(new Set(bindings.map((binding) => binding.local)))\n if (!isUnusedReactHookImport) moduleImports.push(statement.getText(ast))\n // A shared React import is normally retained in server MDX. An\n // unused hook import belongs only to a fenced example and would\n // cause Next's server-component build to reject the whole page.\n if (isUnusedReactHookImport) edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n else sharedImportEdits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } else if (specifier.startsWith('@theme/') || specifier.startsWith('@docusaurus/')) {\n // Docusaurus' own theme/runtime components (Tabs, TabItem, Link,\n // useBaseUrl, ...) are converted to Thally's equivalents by\n // normalizeMdx right after this pass; just drop the now-redundant\n // import and leave JSX usage untouched for that pass to rewrite.\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } else if (hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n // Only JSX usage (`<Widget />`) is rewritten below; a reference\n // in `{pkg.fn()}`, a prop, or an inline `export const` cannot be\n // rewritten the same way. Dropping the import would leave an\n // undefined identifier; keeping it imports a package that is not\n // installed in the migrated project, which fails `next build`\n // for the *whole* site with \"Module not found\" — not just this\n // page. Excluding the page is the only option that keeps the\n // rest of the site building; `pruneMissingNavigationPages` (see\n // repository.ts) then drops it from navigation too.\n warnings.push({\n code: 'skipped-file',\n message: `This page was excluded because it uses '${bindings.map((binding) => binding.local).join(', ')}' from ${unavailableImportLabel(rawSpecifier)} outside JSX (in an expression, prop, or inline declaration), and that import isn't available in the migrated project. Make '${rawSpecifier}' available and add the import back manually, or rewrite the page to avoid it.`,\n source: relative(root, currentFile).replace(/\\\\/g, '/'),\n })\n hasUnsupportedImports = true\n } else {\n // An npm package Thally's runtime does not ship is not installed\n // in the migrated project; leaving the import in place breaks\n // `next build` with \"Module not found\". Drop the import and\n // replace its JSX usage with a safe fallback instead (see the\n // `unsupportedImports` walk below) rather than shipping a page\n // that cannot compile.\n warn(`MDX import of ${unavailableImportLabel(rawSpecifier)} is not available in the migrated project; the import was removed and its usage replaced.`, currentFile)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n for (const binding of bindings) unsupportedImports.set(binding.local, rawSpecifier)\n }\n continue\n }\n if (/\\.mdx?$/.test(specifier)) {\n // A capitalized default/named import here is a JSX-usable\n // partial (`import Partial from './x.mdx'`, `<Partial />`) — the\n // earlier text-level snippet-inlining pass (`inlineMdxSnippets`,\n // repository.ts) already resolved and removed those before this\n // AST walk ever runs, so reaching this point with only lowercase\n // bindings means every one is a plain named value that pass\n // can't touch: Docusaurus' own convention of auto-generating a\n // `toc` export per `.mdx` file, commonly re-exported by spreading\n // it into another page's `toc` (`export const toc = [...viewsToc,\n // ...]`). The migrated project has no such module to import from\n // (\"Module not found\"), and no way to compute the value, so the\n // import and that one safe, common usage shape are both removed;\n // anything shaped differently is left for the npm-style\n // expression-reference check below to exclude the page instead of\n // guessing at a replacement.\n if (bindings.length > 0 && bindings.every((binding) => !/^[A-Z]/.test(binding.local))) {\n warn(`MDX named import of ${JSON.stringify(rawSpecifier)} isn't a component and has no equivalent in the migrated site (for example Docusaurus's generated 'toc' export), so it was removed, along with any '...${bindings.map((binding) => binding.local).join(\", '...\")}' spread of it.`, currentFile)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n for (const binding of bindings) droppedMdxDataBindings.add(binding.local)\n }\n continue\n }\n // A binary asset (`docusaurusLogo.svg`, a `.docx` handout, ...) is\n // never really \"a component\" — it's fine bound to any identifier\n // shape and referenced from an expression (`src={docusaurusLogo}`),\n // unlike the component-alias mechanism below, which can only\n // rewrite a literal JSX tag name, not an arbitrary expression\n // reference. Handle it before the component-shaped checks reject it\n // for the wrong reason (a lowercase local name, expression usage)\n // and leave a dead import behind. Only bail out of this path (to\n // the ordinary handling below, which removes the import either way)\n // when the same local name is *also* used as a JSX tag — a string\n // URL bound there would throw just as hard as the missing import.\n if (bindings.length && RESCUABLE_ASSET_EXTENSIONS.has(extname(specifier).toLowerCase())\n && !bindings.some((binding) => usedAsJsxTagName(binding.local))) {\n try {\n const href = copyPublicAsset(resolveDependency(specifier, currentFile))\n edits.push({\n start: node.position.start.offset + statement.getStart(ast),\n end: node.position.start.offset + statement.end,\n // `export`, not a bare `const`: this replaces an `import`\n // statement in place, and the final MDX compile (a fresh\n // parse of this text, not a reuse of this pass's own AST)\n // only recognizes a top-level JS block as ESM — evaluated and\n // its bindings put in scope — when it starts with `import` or\n // `export`. A bare `const` there is just prose to that parser\n // and renders as literal paragraph text instead, leaving\n // every reference to this binding a `ReferenceError` at\n // render (reproduced against hasura/graphql-engine's\n // databases/overview.mdx, which binds asset URLs this way).\n value: bindings.map((binding) => `export const ${binding.local} = ${JSON.stringify(href)};`).join('\\n'),\n })\n warn(`Asset import ${JSON.stringify(rawSpecifier)} was copied to ${href} and bound to that URL instead of importing it as a component.`, currentFile)\n continue\n } catch {\n // Not actually resolvable/copyable (missing file, budget) —\n // fall through to the ordinary handling below.\n }\n }\n if (!bindings.length || (statement.importClause?.namedBindings && ts.isNamespaceImport(statement.importClause.namedBindings))) {\n warn('Namespace or side-effect MDX imports require manual registration; the import was preserved.', currentFile)\n hasUnsupportedImports = true\n continue\n }\n // Unlike the unavailable-npm-package case above, a local/relative\n // import is fully owned by the migration: `copyGraph` below moves\n // the whole file (and its own local dependency graph) into the\n // project, and the statement it emits keeps every binding's original\n // local name (`as ${binding.local}`) — only the module specifier\n // changes. Nothing in the page body needs renaming, so it makes no\n // difference whether a binding is used as a bare JSX tag or only\n // referenced elsewhere (an enum member on a sibling prop, a member\n // tag, a wrapping declaration, ...): the copy is attempted either\n // way, and the page is excluded only if that copy genuinely fails\n // (an unsupported dependency inside the local graph — see the catch\n // below), not merely because of how the binding is used.\n try {\n const sourcePath = resolveDependency(specifier, currentFile)\n const path = copyGraph(sourcePath)\n const isSvgUsedAsTag = extname(path).toLowerCase() === '.svg' && bindings.some((binding) => usedAsJsxTagName(binding.local))\n for (const binding of bindings) {\n const registerPath = isSvgUsedAsTag ? wrapSvgAsComponent(path) : path\n const registerImported = isSvgUsedAsTag ? 'default' : binding.imported\n // MDX's own component-injection pass (recma-jsx-rewrite) only\n // rewrites a JSX tag it finds as a genuine, direct mdast JSX\n // node (`<Foo>` as its own markdown/JSX child) to pull from the\n // shared `_components` scope (the customComponents registry\n // below) — the alias-rename walk further down can likewise only\n // text-replace that same direct form. Any other shape —\n // `Capability.ToolUse` in a sibling prop's object literal,\n // `<Widget />` nested inside a `{...}` expression or an\n // `export const` declaration, a member tag `<Widget.Item />`,\n // a plain value passed as a prop (`as={Widget}`) — is invisible\n // to both, and registering it under an aliased key would leave\n // the literal reference an unresolved free variable\n // (`ReferenceError` at render; reproduced against a real\n // Cohere build for both an enum-in-a-prop and a component\n // nested in a `.map()` callback). Give any such binding a real\n // import instead, keeping its original local name and using the\n // project's `@/` alias so the specifier resolves regardless of\n // where the generated runtime module that embeds this page\n // ends up on disk.\n if (!isSvgUsedAsTag && hasExpressionReference(new Set([binding.local]))) {\n const helper = staticServerHelper(sourcePath, binding.imported, binding.local)\n if (helper) {\n serverPageDeclarations.push(helper)\n continue\n }\n const aliasSpecifier = portableSpecifier(`@/${registerPath.replace(/^src\\//, '').replace(/\\\\/g, '/')}`)\n realPageImports.push(`import { ${registerImported} as ${binding.local} } from ${JSON.stringify(aliasSpecifier)};`)\n continue\n }\n const name = register(registerPath, registerImported)\n aliases.set(binding.local, name)\n moduleImports.push(`import { ${registerImported} as ${binding.local} } from ${JSON.stringify(portableSpecifier(`./${relative(destinationRoot, registerPath).replace(/\\\\/g, '/')}`))};`)\n }\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } catch (error) {\n if (hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n warnings.push({\n code: 'skipped-file',\n message: `This page was excluded because local import ${JSON.stringify(rawSpecifier)} could not be copied and is used in an expression: ${error instanceof Error ? error.message : 'unsupported dependency'}.`,\n source: relative(root, currentFile).replace(/\\\\/g, '/'),\n })\n hasUnsupportedImports = true\n continue\n }\n const failedPackage = error instanceof Error\n ? error.message.match(/^external package (\\S+) requires manual installation and review$/)?.[1]\n : undefined\n if (failedPackage && YOUTUBE_ID_PACKAGES.has(failedPackage)) {\n // The local wrapper's own body just re-exports a known\n // YouTube-embed package one level down (Playwright's\n // `LiteYouTube` wraps `react-lite-youtube-embed` this way); the\n // wrapper itself can't be copied, but its usage is id-prop-shaped\n // exactly like a direct import of that package, so the same\n // working `<iframe>` fallback below applies instead of losing\n // the embed to the generic unknown-component neutralization.\n for (const binding of bindings) unsupportedImports.set(binding.local, failedPackage)\n edits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n continue\n }\n hasUnsupportedImports = true\n const importStart = node.position.start.offset + statement.getStart(ast)\n const importEnd = node.position.start.offset + statement.end\n // The component itself couldn't be copied (unsupported syntax, a\n // budget limit, a missing file, ...). Leaving the import in place\n // referenced a module that will never exist in the migrated\n // project, which fails `next build` for the *whole* site with\n // \"Module not found\" — not just this page (the same reasoning as\n // the unsupported-npm-import case above). Remove it. Its bindings\n // are known to be used only as JSX tags here (any expression/prop\n // usage already excluded this import from reaching this try, via\n // the `hasExpressionReference` check above), so a plain-page\n // rescan (`replaceUnknownComponents`, mdx.ts, run by repository.ts\n // after this transform) will find each now-undeclared tag and\n // neutralize it (a paired tag keeps its children in a `<div>`; a\n // self-closing one is removed) rather than leave a dangling\n // reference.\n let rescuedAssetHref: string | undefined\n if (RESCUABLE_ASSET_EXTENSIONS.has(extname(specifier).toLowerCase())) {\n // Only worth rescuing as a URL string when nothing ever renders\n // it as a JSX tag (`<Logo />`) — a string bound to a component\n // reference would throw just as hard as the missing import did.\n const usedAsJsxTag = bindings.some((binding) => hasExpressionReference(new Set([binding.local]), { includeDirectTags: true }))\n if (!usedAsJsxTag) {\n try {\n rescuedAssetHref = copyPublicAsset(resolveDependency(specifier, currentFile))\n } catch {\n rescuedAssetHref = undefined\n }\n }\n }\n if (rescuedAssetHref !== undefined) {\n edits.push({\n start: importStart,\n end: importEnd,\n // See the identical `export const` note on the other asset\n // rescue above — same reason.\n value: bindings.map((binding) => `export const ${binding.local} = ${JSON.stringify(rescuedAssetHref)};`).join('\\n'),\n })\n warn(`Asset import ${JSON.stringify(rawSpecifier)} could not be copied as a component; it was copied to ${rescuedAssetHref} and bound to that URL instead.`, currentFile)\n } else {\n edits.push({ start: importStart, end: importEnd, value: '' })\n warn(`Component import ${JSON.stringify(rawSpecifier)} could not be copied and was removed: ${error instanceof Error ? error.message : 'unsupported dependency'}. Its usage on this page was neutralized.`, currentFile)\n }\n }\n }\n }\n\n // Extract a page's own inline component that calls a React hook (Mintlify\n // treats hooks as pre-injected globals for such components, but Thally's\n // page module is a Server Component and cannot import a hook itself) into\n // a client module, together with every page-local declaration it uses.\n // `planInlineExtraction` decides what moves, what the page keeps a copy\n // of, and whether the move is safe at all; an unsafe one is left in place\n // and reported. Whatever the page still renders is wired back as a\n // registered tag, or a real import when it is reached by name.\n const refusedInlineComponents = new Set<string>()\n {\n const plan = planInlineExtraction({\n declarations,\n tree,\n copyableImports: [...moduleImports, ...realPageImports],\n helperDeclarations: serverPageDeclarations,\n unavailableImports: unsupportedImports,\n reactGlobals: REACT_GLOBALS,\n })\n for (const { name, reason } of plan.blocked) {\n refusedInlineComponents.add(name)\n warn(`Inline component \"${name}\" calls a React hook but was left in the page: ${reason}. Move it and everything it uses into a client component manually.`, currentFile)\n }\n const moduleSource = plan.moved.length === 0 ? '' : [\n ...plan.moduleImports, ...plan.moduleHelpers,\n ...[...plan.moved, ...plan.copied].sort((a, b) => a - b).map((index) => declarations[index].source),\n ].join('\\n\\n')\n if (plan.moved.length > 0\n && (copied.size >= MAX_COMPONENT_FILES || Buffer.byteLength(moduleSource) > MAX_FILE_BYTES\n || copiedBytes + Buffer.byteLength(moduleSource) > MAX_COMPONENT_BYTES)) {\n warn(`Inline component \"${plan.movedNames[0]}\" exceeded the component migration budget; source was preserved.`, currentFile)\n } else if (plan.moved.length > 0) {\n const path = `${destinationRoot}/inline-${hash(`${relative(root, currentFile)}:components`)}.jsx`\n const inlineSource = `${resolveInlineBuiltinReferences(moduleSource, plan.moduleNames)}\\n`\n copied.set(path, { path, content: `'use client';\\n${implicitReactImports(sourceFile(inlineSource, 'inline.jsx'))}\\n${inlineSource}` })\n copiedBytes += Buffer.byteLength(inlineSource)\n const movedIndexes = new Set(plan.moved)\n for (const index of plan.moved) edits.push({ start: declarations[index].start, end: declarations[index].end, value: '' })\n for (const name of plan.registryNames) {\n const registered = register(path, name)\n aliases.set(name, registered)\n // A root the page still extracts as interactive JSX (below) imports\n // the moved component from this module by its real name.\n moduleImports.push(`import { ${name} } from ${JSON.stringify(portableSpecifier(`./${relative(destinationRoot, path).replace(/\\\\/g, '/')}`))};`)\n }\n if (plan.pageImportNames.length > 0) {\n realPageImports.push(`import { ${plan.pageImportNames.join(', ')} } from ${JSON.stringify(portableSpecifier(`@/${path.replace(/^src\\//, '').replace(/\\\\/g, '/')}`))};`)\n }\n // A React import the page only kept for the code that just moved would\n // make the page itself import a hook; drop it once nothing else uses it.\n for (const entry of [...sharedImportEdits]) {\n const locals = [...sourceFile(content.slice(entry.start, entry.end), 'shared.tsx').statements]\n .flatMap((statement) => ts.isImportDeclaration(statement) ? imports(statement).map((binding) => binding.local) : [])\n if (locals.length === 0 || locals.some((local) => plan.pageReferences.has(local))) continue\n edits.push(entry)\n sharedImportEdits.splice(sharedImportEdits.indexOf(entry), 1)\n }\n for (let index = declarations.length - 1; index >= 0; index -= 1) {\n if (movedIndexes.has(index)) declarations.splice(index, 1)\n }\n }\n }\n\n // Remove every `...name` spread of a dropped MDX data import (see the\n // lowercase-binding `.mdx?` case above) from any array literal it\n // appears in, so the export that merges it (`export const toc =\n // [...viewsToc, ...]`) stays valid instead of throwing on the now-\n // undefined identifier. Only the spread element itself is touched\n // (plus one adjacent comma, so the array literal it lived in stays\n // syntactically valid); a bare reference to the same name elsewhere is\n // intentionally left alone for `hasExpressionReference`'s excluded-page\n // path elsewhere in this function to catch instead of guessing at it.\n if (droppedMdxDataBindings.size > 0) {\n for (const node of esmNodes) {\n if (node.value === undefined || node.position?.start.offset === undefined) continue\n const nodeStart = node.position.start.offset\n const nodeText = node.value\n const ast = sourceFile(nodeText, 'inline.tsx')\n function stripDroppedSpreads(inner: ts.Node): void {\n if (ts.isSpreadElement(inner) && ts.isIdentifier(inner.expression) && droppedMdxDataBindings.has(inner.expression.text)) {\n const start = nodeStart + inner.getStart(ast)\n let end = nodeStart + inner.end\n const following = nodeText.slice(inner.end).match(/^\\s*,/)\n if (following) end += following[0].length\n edits.push({ start, end, value: '' })\n return\n }\n ts.forEachChild(inner, stripDroppedSpreads)\n }\n for (const statement of ast.statements) stripDroppedSpreads(statement)\n }\n }\n\n // Docusaurus' own docs teach `require('./relative/asset.ext').default`\n // as the idiom for linking a JSX attribute (`href={...}`) straight to a\n // static asset — real, working MDX on the source site, but a dangling\n // `require()` of a path the migrated project never has once copied\n // verbatim (\"Module not found\" at build time). Only a JSX *attribute*\n // expression is handled here (`mdxFlowExpression`/`mdxTextExpression`\n // bodies never hit this shape in practice and the ESM-import loop above\n // already covers a bare top-level `require()`); each attribute's own\n // `position` bounds the replacement to just that attribute's text, so\n // this can never match the identical-looking call inside a *fenced code\n // example* documenting the very same idiom (a real risk here, since\n // Docusaurus' own assets.mdx page shows both side by side).\n walk(tree, (node) => {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== 'mdxJsxAttribute' || !attribute.value || typeof attribute.value !== 'object') continue\n const start = attribute.position?.start.offset\n const end = attribute.position?.end.offset\n if (start === undefined || end === undefined) continue\n const attributeText = content.slice(start, end)\n const match = attributeText.match(/require\\(\\s*(['\"])((?:\\.\\.?\\/|\\/|@site\\/)[^'\"]+?\\.(?:svg|png|jpe?g|webp|gif|avif|ico|docx|pdf))\\1\\s*\\)(?:\\.default|\\.src)?/)\n if (!match || match.index === undefined) continue\n try {\n const specifier = match[2]\n const normalized = specifier.startsWith('@site/') ? `/${specifier.slice('@site/'.length)}` : specifier\n // `true`: this is exactly the Playwright `require('../images/...')`\n // idiom (a page under a flattened project root reaching a shared\n // asset that only exists at the mirrored repository-root path) —\n // see `resolveDependency`'s `allowFlattenedMirror` doc.\n const resolvedPath = normalized.startsWith('/') ? resolveWithin(root, normalized.slice(1)) : resolveDependency(normalized, currentFile, true)\n const href = copyPublicAsset(resolvedPath)\n const replaced = attributeText.slice(0, match.index) + JSON.stringify(href) + attributeText.slice(match.index + match[0].length)\n edits.push({ start, end, value: replaced })\n } catch {\n // Not actually resolvable/copyable, even after the repository-root\n // fallback above. Leaving the dangling `require()` in place would\n // break the whole site's build (\"Module not found\"), so replace it\n // with an empty string (a broken image is degraded, not fatal) and\n // warn instead.\n const replaced = attributeText.slice(0, match.index) + JSON.stringify('') + attributeText.slice(match.index + match[0].length)\n edits.push({ start, end, value: replaced })\n warn(`Asset require(${JSON.stringify(match[2])}) could not be resolved and was removed; the reference was replaced with an empty string.`, currentFile)\n }\n }\n })\n\n // A page-local declaration (not imported) that uses a hook or an event\n // handler must move to the client module along with its invocation: left\n // inline, it compiles into the page's own server-rendered module, where\n // `useState` and friends are never in scope (see `implicitReactImports`,\n // only applied to extracted client files).\n // A component the extraction above refused (and warned about) stays where\n // it is; this pass must not move it, and the dependency that blocked it,\n // behind that decision.\n const statefulDeclarationNames = new Set(\n declarations\n .filter(({ source }) => /\\bon[A-Z]\\w*\\s*=|\\buse[A-Z]\\w*\\s*\\(/.test(source))\n .map(({ source }) => source.match(/^export const (\\w+)/)?.[1])\n .filter((name): name is string => !!name && !refusedInlineComponents.has(name)),\n )\n\n // Extract whole HTML JSX roots with event handlers. Markdown and global\n // built-ins remain server-rendered; React functions stay inside the client\n // module, so no function is serialized across a server/client boundary.\n const extracted: Array<{ node: MdxNode; name: string; jsx: string }> = []\n for (const candidate of tree.children ?? []) {\n const node = candidate.type === 'paragraph' && candidate.children?.length === 1 ? candidate.children[0] : candidate\n if (!['mdxJsxFlowElement', 'mdxJsxTextElement'].includes(node.type) || node.position?.start.offset === undefined || node.position.end.offset === undefined) continue\n let interactive = statefulDeclarationNames.has(node.name ?? '')\n let supported = true\n walk(node, (child) => {\n if (child.attributes?.some((attribute) => /^on[A-Z]/.test(attribute.name ?? ''))) interactive = true\n if (child.name && /^[A-Z]/.test(child.name) && !aliases.has(child.name) && !statefulDeclarationNames.has(child.name)) supported = false\n if (!['mdxJsxFlowElement', 'mdxJsxTextElement', 'mdxFlowExpression', 'mdxTextExpression', 'text', 'paragraph'].includes(child.type)) supported = false\n })\n if (!interactive) continue\n if (!supported || hasUnsupportedImports) {\n warn('Interactive MDX containing Markdown or unregistered components requires manual extraction; source was preserved.', currentFile)\n continue\n }\n const jsx = content.slice(node.position.start.offset, node.position.end.offset)\n // The JSX compiler is the final syntax gate: Markdown embedded in JSX\n // must not accidentally become JavaScript in the generated module.\n const result = ts.transpileModule(`export default function Inline() { return (${jsx}); }`, {\n fileName: 'inline.jsx', compilerOptions: { jsx: ts.JsxEmit.Preserve }, reportDiagnostics: true,\n })\n if (result.diagnostics?.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) {\n warn('Interactive MDX could not be safely extracted as JSX; source was preserved.', currentFile)\n continue\n }\n extracted.push({ node, name: `Inline${extracted.length}`, jsx })\n }\n if (extracted.length && declarations.length) {\n const declared = new Set<string>()\n function bind(name: ts.BindingName): void {\n if (ts.isIdentifier(name)) declared.add(name.text)\n else for (const element of name.elements) if (ts.isBindingElement(element)) bind(element.name)\n }\n for (const declaration of declarations) {\n for (const statement of sourceFile(declaration.source, 'declaration.tsx').statements) {\n if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) declared.add(statement.name.text)\n if (ts.isVariableStatement(statement)) for (const variable of statement.declarationList.declarations) bind(variable.name)\n }\n }\n const hasSharedDeclarations = hasExpressionReference(declared, {\n excludedNodes: extracted.map((entry) => entry.node),\n includeDeclarations: false,\n includeDirectTags: true,\n })\n if (hasSharedDeclarations) {\n warn('Interactive MDX shares declarations with remaining page content; source was preserved for manual extraction.', currentFile)\n extracted.length = 0\n }\n }\n if (extracted.length && (copied.size >= MAX_COMPONENT_FILES\n || Buffer.byteLength(content) > MAX_FILE_BYTES\n || copiedBytes + Buffer.byteLength(content) > MAX_COMPONENT_BYTES)) {\n warn('Interactive MDX exceeded the component migration budget; source was preserved.', currentFile)\n extracted.length = 0\n }\n if (extracted.length) {\n const path = `${destinationRoot}/inline-${hash(relative(root, currentFile))}.jsx`\n let declarationSource = [...new Set(declarations.map((entry) => entry.source))].join('\\n\\n')\n // Mintlify exposes this DOM id as its documented search trigger. Thally\n // opens search through the same keyboard event handled by CommandSearch.\n declarationSource = declarationSource.replace(/document\\.getElementById\\(\\s*(['\"])search-bar-entry\\1\\s*\\)\\.click\\(\\s*\\)/g,\n `document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', ctrlKey: true, bubbles: true }))`)\n const inlineSource = [\n ...moduleImports, '', declarationSource, '',\n ...extracted.map(({ name, jsx }) => `export function ${name}() {\\n return (${jsx});\\n}`), '',\n ].join('\\n')\n // A single leading directive: `inlineSource` no longer carries its own,\n // or Next rejects the file (\"use client\" must be the first statement).\n copied.set(path, { path, content: `'use client';\\n${implicitReactImports(sourceFile(inlineSource, 'inline.jsx'))}\\n${inlineSource}` })\n copiedBytes += Buffer.byteLength(inlineSource)\n for (const { node, name } of extracted) {\n edits.push({ start: node.position!.start.offset!, end: node.position!.end.offset!, value: `<${register(path, name)} />` })\n }\n edits.push(...declarations.map(({ start, end }) => ({ start, end, value: '' })), ...sharedImportEdits)\n }\n // A page-local callback cannot cross into a copied client component. Move\n // a self-contained JSX callback into a thin client adapter while keeping\n // the MDX children on the page. More complex callbacks remain passive.\n const pageFunctions = functionDeclaredNames(content)\n const passiveRoots: Array<MdxNode> = []\n const wrappedRoots = new Set<MdxNode>()\n walk(tree, (node) => {\n if (!node.name || !aliases.has(node.name) || !functionValuedAttribute(node, pageFunctions)\n || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n if (passiveRoots.some((root) => node.position!.start.offset! >= root.position!.start.offset!\n && node.position!.end.offset! <= root.position!.end.offset!)) return\n const functionAttributes = (node.attributes ?? []).filter((attribute) => {\n const value = attribute.value && typeof attribute.value === 'object' ? attribute.value.value?.trim() : undefined\n return !!value && pageFunctions.has(value)\n })\n if (functionAttributes.length === 1 && functionAttributes[0].name\n && functionAttributes[0].position?.start.offset !== undefined\n && functionAttributes[0].position.end.offset !== undefined) {\n const functionName = (functionAttributes[0].value as { value: string }).value.trim()\n const declaration = declarations.find((entry) => new RegExp(`^export const ${functionName}\\\\s*=`).test(entry.source))\n const safeDeclaration = declaration?.source.match(/^export const \\w+\\s*=\\s*\\(\\s*\\{\\s*children(?:\\s*,\\s*\\.\\.\\.props)?\\s*\\}\\s*\\)\\s*=>\\s*\\([\\s\\S]*\\)\\s*;?$/)\n && !/\\b(?:window|document|process|fetch|use[A-Z]\\w*)\\b/.test(declaration.source)\n && [...declaration.source.matchAll(/<([A-Z]\\w*)\\b/g)].every((match) => match[1] === 'CodeBlock')\n && [...declaration.source.matchAll(/\\{([^{}]*)\\}/g)].every((match) =>\n ['children', '...props', 'children, ...props'].includes(match[1].trim()))\n const binding = registrations.get(aliases.get(node.name)!)\n if (safeDeclaration && binding) {\n const fallbackDeclaration = declaration!.source.replace(/<CodeBlock\\b[^>]*>/g, '<pre><code>').replace(/<\\/CodeBlock>/g, '</code></pre>')\n const wrapperPath = `${destinationRoot}/callback-${hash(`${currentFile}:${node.position.start.offset}`)}.jsx`\n const imported = binding.imported === 'default' ? 'default' : binding.imported\n const importClause = imported === 'default' ? 'import Original' : `import { ${imported} as Original }`\n const specifier = portableSpecifier(`./${relative(destinationRoot, binding.path).replace(/\\\\/g, '/')}`)\n const wrapperName = register(wrapperPath, 'CallbackWrapper')\n copied.set(wrapperPath, { path: wrapperPath, content: [\n \"'use client';\", `${importClause} from ${JSON.stringify(specifier)};`,\n fallbackDeclaration,\n `export function CallbackWrapper({ children, ...props }) { return <Original {...props} ${functionAttributes[0].name}={${functionName}}>{children}</Original>; }`,\n ].join('\\n') })\n const start = node.position.start.offset\n const end = node.position.end.offset\n const source = content.slice(start, end)\n const opening = source.indexOf(`<${node.name}`)\n const closing = source.lastIndexOf(`</${node.name}`)\n if (opening >= 0) edits.push({ start: start + opening + 1, end: start + opening + 1 + node.name.length, value: wrapperName })\n if (closing >= 0) edits.push({ start: start + closing + 2, end: start + closing + 2 + node.name.length, value: wrapperName })\n edits.push({ start: functionAttributes[0].position!.start.offset!, end: functionAttributes[0].position!.end.offset!, value: '' })\n wrappedRoots.add(node)\n if (declaration!.source.includes('<CodeBlock')) warn(`Interactive <${node.name}> was retained with a basic code block in place of Mintlify's CodeBlock.`, currentFile)\n return\n }\n }\n const source = content.slice(node.position.start.offset, node.position.end.offset)\n const openingEnd = source.indexOf('>')\n const closingStart = source.lastIndexOf(`</${node.name}`)\n const children = openingEnd >= 0 && closingStart > openingEnd ? source.slice(openingEnd + 1, closingStart) : ''\n edits.push({ start: node.position.start.offset, end: node.position.end.offset,\n value: `<div data-migration-interactive-fallback=\"${node.name}\">${children}</div>` })\n passiveRoots.push(node)\n warn(`Interactive <${node.name}> passes a page-local function into a client component; its child content was retained without the interactive control. Move the callback into a client component to restore it.`, currentFile)\n })\n walk(tree, (node) => {\n const replacement = node.name ? aliases.get(node.name) : undefined\n if (!replacement || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n if (wrappedRoots.has(node)) return\n if (passiveRoots.some((root) => node.position!.start.offset! >= root.position!.start.offset!\n && node.position!.end.offset! <= root.position!.end.offset!)) return\n const start = node.position.start.offset\n const end = node.position.end.offset\n if (extracted.some((item) => start >= item.node.position!.start.offset! && end <= item.node.position!.end.offset!)) return\n const text = content.slice(start, end)\n const opening = text.indexOf(`<${node.name}`)\n if (opening >= 0) edits.push({ start: start + opening + 1, end: start + opening + 1 + node.name!.length, value: replacement })\n const closing = text.lastIndexOf(`</${node.name}`)\n if (closing >= 0) edits.push({ start: start + closing + 2, end: start + closing + 2 + node.name!.length, value: replacement })\n })\n // Every usage of a removed npm-package import is replaced whole (tag,\n // props, and children) rather than just its name: nothing in the\n // migrated project can render it. A video-embed-shaped usage (an `id`\n // prop, a name suggesting an embedded player) gets a trivial working\n // `<iframe>`; anything else becomes a visible, greppable MDX comment.\n walk(tree, (node) => {\n const specifier = node.name ? unsupportedImports.get(node.name) : undefined\n if (!specifier || node.position?.start.offset === undefined || node.position.end.offset === undefined) return\n const start = node.position.start.offset\n const end = node.position.end.offset\n const videoId = youtubeEmbedVideoId(node, specifier)\n const value = videoId\n ? `<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${videoId}\" title=\"Embedded video\" allowFullScreen />`\n : `{/* Removed <${node.name}>: unsupported import '${specifier}' */}`\n edits.push({ start, end, value })\n })\n const rendered = applyReplacements(content, edits)\n // Inserted after all offset-based edits (it has no position in the\n // original source) so it lands once, at the very top of the body.\n const pageStatements = [...new Set([...realPageImports, ...serverPageDeclarations])]\n const realImportsBlock = pageStatements.length ? `${pageStatements.join('\\n')}\\n\\n` : ''\n return frontmatter + realImportsBlock + rendered\n }\n\n function files(): Array<RenderedMigrationFile> {\n // A rescued asset (`copyPublicAsset`) lands in `copied` without ever\n // registering a component; it still needs emitting even when nothing\n // was registered.\n if (!copied.size) return []\n if (!registrations.size) return [...copied.values()]\n const entries = [...registrations.entries()].sort(([a], [b]) => a.localeCompare(b))\n return [...copied.values(), {\n path: 'src/mdx/custom-components.tsx',\n content: [\n '/** Repository components preserved by migration; this registry is customer-owned. */',\n \"import type { MDXComponents } from 'mdx/types'\", ...entries.map(([name, binding]) => {\n const path = portableSpecifier(`./${relative('src/mdx', binding.path).replace(/\\\\/g, '/')}`)\n return `import { ${binding.imported} as ${name} } from ${JSON.stringify(path)}`\n }), '',\n // Not every registered local binding is JSX-taggable — a companion\n // value from the same import (an enum used only as `Foo.Bar` inside\n // another component's prop, e.g.) is registered too, so the whole\n // MDX scope resolves it. `MDXComponents`' index signature expects a\n // component at every key, which such a value structurally is not;\n // cast rather than exclude it, since excluding it would leave a\n // dangling reference in the page that DOES need it.\n 'export const customComponents = {',\n ...entries.map(([name]) => ` ${name},`), '} as unknown as MDXComponents', '',\n ].join('\\n'),\n }]\n }\n return { transform, files }\n}\n\n/** Preserve an authored component registry while adding an isolated import map. */\nexport function mergeComponentRegistry(existing: string, incoming: string): Array<RenderedMigrationFile> {\n const fingerprint = hash(incoming)\n const name = `MigratedRegistry${fingerprint}`\n const registryPath = `./migrated-components-${fingerprint}`\n const source = sourceFile(existing, 'custom-components.tsx')\n const alreadyImported = source.statements.some((statement) => ts.isImportDeclaration(statement)\n && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === registryPath)\n let initializer: ts.Expression | undefined\n for (const statement of source.statements) {\n if (!ts.isVariableStatement(statement) || !statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue\n for (const declaration of statement.declarationList.declarations) {\n if (ts.isIdentifier(declaration.name) && declaration.name.text === 'customComponents') initializer = declaration.initializer\n }\n }\n while (initializer && (ts.isAsExpression(initializer) || ts.isSatisfiesExpression(initializer) || ts.isParenthesizedExpression(initializer))) initializer = initializer.expression\n if (!initializer || !ts.isObjectLiteralExpression(initializer)) {\n throw new Error('Cannot safely merge src/mdx/custom-components.tsx: export customComponents as an object literal before importing components. The existing registry was preserved.')\n }\n const content = alreadyImported ? existing : applyReplacements(existing, [\n { start: source.statements.filter((statement) => ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)).at(-1)?.end ?? 0,\n end: source.statements.filter((statement) => ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression)).at(-1)?.end ?? 0,\n value: `\\nimport { customComponents as ${name} } from ${JSON.stringify(registryPath)}\\n` },\n { start: initializer.getStart(source) + 1, end: initializer.getStart(source) + 1, value: `\\n ...${name},` },\n ])\n return [\n { path: `src/mdx/migrated-components-${fingerprint}.tsx`, content: incoming },\n { path: 'src/mdx/custom-components.tsx', content },\n ]\n}\n","/**\n * The one frontmatter parser for authored content in this package.\n *\n * Only YAML is supported. Parsing delimiters locally keeps legacy JavaScript\n * engines out of migration processes and treats language-tagged blocks as\n * opaque metadata rather than executable third-party input.\n *\n * Internal module — deliberately not part of the package's public API. The\n * app-side original is `src/lib/frontmatter.ts`; the packages keep their own\n * copies because they cannot import from the app.\n */\n\nimport { parse as parseYaml } from 'yaml'\n\ninterface ParsedFrontmatter {\n content: string\n data: Record<string, unknown>\n /** Set when the frontmatter block was invalid YAML; `data` is a best-effort salvage. */\n error?: string\n}\n\n/**\n * Best-effort recovery for frontmatter that failed to parse as a whole block:\n * try each top-level `key: value` line on its own. A line that is itself\n * invalid YAML (e.g. an unescaped reserved character) is skipped rather than\n * aborting the whole page.\n */\nfunction salvageFrontmatterLines(matter: string): Record<string, unknown> {\n const data: Record<string, unknown> = {}\n for (const line of matter.split(/\\r?\\n/)) {\n if (!/^[A-Za-z_][\\w-]*:\\s?/.test(line)) continue\n try {\n const parsedLine = parseYaml(line)\n if (parsedLine && typeof parsedLine === 'object' && !Array.isArray(parsedLine)) {\n Object.assign(data, parsedLine)\n }\n } catch {\n // Line is unrecoverable on its own; drop just that field.\n }\n }\n return data\n}\n\n/** Parse frontmatter without any path that can execute the content. */\nexport function parseFrontmatter(raw: string): ParsedFrontmatter {\n const source = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw\n const opening = /^---([^\\r\\n]*)\\r?\\n/.exec(source)\n if (!opening || opening[1].startsWith('-')) return { content: source, data: {} }\n\n const language = opening[1].trim().toLowerCase()\n const remainder = source.slice(opening[0].length)\n const closing = /^---[ \\t]*\\r?$/m.exec(remainder)\n const matter = closing ? remainder.slice(0, closing.index) : remainder\n let content = closing ? remainder.slice(closing.index + closing[0].length) : ''\n if (content.startsWith('\\r\\n')) content = content.slice(2)\n else if (content.startsWith('\\n')) content = content.slice(1)\n\n if (matter.trim() === '' || !['', 'yaml', 'yml'].includes(language)) {\n return { content, data: {} }\n }\n try {\n const parsed = parseYaml(matter)\n return {\n content,\n data: parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {},\n }\n } catch (err) {\n return {\n content,\n data: salvageFrontmatterLines(matter),\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n","/** Markdown/MDX normalization that preserves every component Thally supports. */\n\nimport type * as acorn from 'acorn'\nimport { posix } from 'node:path'\nimport { compileSync } from '@mdx-js/mdx'\nimport { nameToEmoji } from 'gemoji'\nimport remarkGfm from 'remark-gfm'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport { unified } from 'unified'\n\nimport { isThallyBuiltinComponent } from './builtin-components.js'\nimport { parseFrontmatter } from './frontmatter.js'\nimport type { MigrationPage, MigrationPlatform } from './types.js'\n\nexport interface MarkdownPageIdentity {\n id: string\n navigationId: string\n locale?: string\n}\n\nfunction titleFromId(id: string): string {\n const value = id.split('/').at(-1) ?? id\n if (value === 'introduction') return 'Introduction'\n return value\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\ninterface DescriptionNode {\n type: string\n value?: string\n alt?: string | null\n children?: Array<DescriptionNode>\n}\n\nconst descriptionParser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx)\n\nfunction firstParagraph(content: string): string {\n function plainText(node: DescriptionNode): string {\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'image') return node.alt ?? ''\n if (node.type === 'break') return ' '\n return (node.children ?? []).map(plainText).join('')\n }\n function findParagraph(node: DescriptionNode): string {\n if (node.type === 'paragraph') {\n const value = plainText(node).replace(/\\s+/g, ' ').trim()\n if (value) return value.slice(0, 240)\n }\n for (const child of node.children ?? []) {\n const value = findParagraph(child)\n if (value) return value\n }\n return ''\n }\n // Component wrappers, imports, expressions, and code fences are syntax, not\n // description copy. Reading paragraph nodes also finds prose nested inside\n // accordions without leaking their closing tags into page metadata.\n try {\n return findParagraph(descriptionParser.parse(content) as DescriptionNode)\n } catch {\n // Unparseable source is already retained for the migration validator. An\n // empty generated description is safer than exposing source-code fragments.\n return ''\n }\n}\n\nfunction docusaurusAdmonitionTag(kind: string): 'Error' | 'Info' | 'Note' | 'Warning' {\n if (kind === 'danger') return 'Error'\n if (kind === 'info') return 'Info'\n if (kind === 'caution' || kind === 'warning') return 'Warning'\n return 'Note'\n}\n\n/**\n * Convert Docusaurus' colon-fence admonitions without interpreting code-fence\n * contents. Longer delimiters support nested admonitions in the same way as\n * the source renderer.\n */\nfunction normalizeDocusaurusAdmonitions(body: string): string {\n const lines = body.split('\\n')\n const openAdmonitions: Array<{ delimiter: string; tag: string; openedAt: number }> = []\n const headingLines: Array<number> = []\n let codeFence: string | null = null\n\n const output = lines.map((line, index) => {\n const codeMatch = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (codeMatch) {\n if (!codeFence) codeFence = codeMatch[1]\n else if (codeMatch[1][0] === codeFence[0] && codeMatch[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(codeMatch[0].length))) codeFence = null\n return line\n }\n if (codeFence) return line\n if (/^#{1,6}\\s/.test(line)) headingLines.push(index)\n\n const opening = line.match(/^\\s*(:{3,})(note|tip|info|warning|caution|danger)(?:\\[([^\\]]+)\\]|\\s+(.+))?\\s*$/i)\n if (opening) {\n const tag = docusaurusAdmonitionTag(opening[2].toLowerCase())\n openAdmonitions.push({ delimiter: opening[1], tag, openedAt: index })\n const title = (opening[3] ?? opening[4])?.trim()\n return title ? `<${tag}>\\n**${title}**` : `<${tag}>`\n }\n\n const closing = line.match(/^\\s*(:{3,})\\s*$/)\n const current = openAdmonitions.at(-1)\n if (closing && current?.delimiter === closing[1]) {\n openAdmonitions.pop()\n return `</${current.tag}>`\n }\n return line\n })\n // Docusaurus tolerates an unterminated admonition in some archived docs.\n // Close it before the next top-level heading (or at EOF) so an otherwise\n // complete page remains importable instead of being discarded by MDX.\n const closingByLine = new Map<number, Array<string>>()\n for (const open of openAdmonitions.reverse()) {\n const at = headingLines.find((line) => line > open.openedAt) ?? output.length\n closingByLine.set(at, [...(closingByLine.get(at) ?? []), `</${open.tag}>`])\n }\n for (const [at, closing] of [...closingByLine].sort(([left], [right]) => right - left)) output.splice(at, 0, ...closing)\n return output.join('\\n')\n}\n\n/**\n * Docusaurus' `mdx-code-block` fence is an escape hatch for live MDX syntax,\n * often used to open a JSX element around ordinary Markdown and code blocks.\n * Remove only the special fence itself; its contents must pass through the\n * same component and link normalization as the rest of the page.\n */\nfunction unwrapDocusaurusMdxCodeBlocks(body: string): string {\n const output: Array<string> = []\n let fence: string | undefined\n let isMdxCodeBlock = false\n for (const line of body.split('\\n')) {\n const opening = !fence && line.match(/^ {0,3}(`{3,}|~{3,})mdx-code-block\\s*$/)\n if (opening) {\n fence = opening[1]\n isMdxCodeBlock = true\n continue\n }\n if (fence) {\n const closing = line.match(/^ {0,3}(`{3,}|~{3,})\\s*$/)\n if (closing && closing[1][0] === fence[0] && closing[1].length >= fence.length) {\n if (!isMdxCodeBlock) output.push(line)\n fence = undefined\n isMdxCodeBlock = false\n continue\n }\n // These blocks may be Docusaurus' only declaration of a theme or\n // npm component used later on the page. Opening just the JSX would\n // promote an unresolved import into Thally's server build, so leave\n // the entire page's source-specific fences intact.\n if (isMdxCodeBlock && /^\\s*(?:import|export)\\b/.test(line)) return body\n output.push(line)\n continue\n }\n const ordinaryFence = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (ordinaryFence) {\n fence = ordinaryFence[1]\n isMdxCodeBlock = false\n }\n output.push(line)\n }\n // An unmatched source fence remains visible to the MDX compiler, which\n // reports the malformed page rather than silently deleting its contents.\n return isMdxCodeBlock ? body : output.join('\\n')\n}\n\n/** Keep explicit heading anchors without leaving `{#id}` as an MDX expression. Frontmatter is left untouched. */\nexport function normalizeExplicitHeadingIds(raw: string): string {\n const { front, body } = splitFrontmatterBlock(raw)\n return front + replaceOutsideCode(body, (segment) => segment.split('\\n').map((line) => {\n if (!/^[ \\t]{0,3}#{1,6}[ \\t]+/.test(line)) return line\n const trimmed = line.trimEnd()\n // Check suffixes from the end instead of matching unbounded whitespace\n // against unbounded heading text; that combination backtracks on long\n // headings with no valid anchor.\n if (trimmed.endsWith('}')) {\n const marker = trimmed.lastIndexOf(' {#')\n if (marker >= 0) {\n const id = trimmed.slice(marker + 3, -1)\n if (/^[A-Za-z][A-Za-z0-9_-]*$/.test(id)) {\n return `<a id=\"${id}\"></a>\\n${trimmed.slice(0, marker).trimEnd()}`\n }\n }\n }\n // Docusaurus' heading plugin also accepts a trailing MDX comment.\n if (trimmed.endsWith('*/}')) {\n const marker = trimmed.lastIndexOf(' {/*')\n if (marker >= 0) {\n const comment = trimmed.slice(marker + 4, -3).trim()\n const id = comment.startsWith('#') ? comment.slice(1) : ''\n if (/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(id)) {\n return `<a id=\"${id}\"></a>\\n${trimmed.slice(0, marker).trimEnd()}`\n }\n }\n }\n return line\n }).join('\\n'))\n}\n\nconst GLOBAL_DOCUSARUS_COMPONENTS = new Set([\n 'Tabs',\n 'TabItem',\n 'Link',\n 'DocCardList',\n 'TOCInline',\n])\n\n/** Match the one simple import form Docusaurus injects without backtracking. */\nfunction removeGlobalDocusaurusImports(body: string): string {\n return replaceOutsideCode(body, (segment) => segment.replace(\n /\\bimport\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])(@(?:theme|docusaurus)\\/[^'\"]+)\\2\\s*;?/g,\n (statement: string, component: string) => GLOBAL_DOCUSARUS_COMPONENTS.has(component) ? '' : statement,\n ))\n}\n\nconst JS_LITERAL_KEYWORDS = new Set(['true', 'false', 'null', 'undefined'])\n// A leading identifier segment (`x` in `x.y.z`) may be any valid JS/Unicode\n// identifier, not just ASCII — `{café}`, `{$var}` are both real bare\n// references a page's own ESM could bind, and Fern's literal-brace prose\n// (the thing this whole pass is trying to leave alone) never happens to\n// look like one, so escaping stays conservative either way.\nconst BARE_IDENTIFIER_PATH = /^[\\p{ID_Start}$_][\\p{ID_Continue}$]*(?:\\.[\\p{ID_Start}$_][\\p{ID_Continue}$]*)*$/u\n// Double-mustache templating syntax (`{{now}}`, `{{customer}}`) is common in\n// prose copied from other platforms (Liquid/Handlebars-style variable\n// interpolation). MDX parses the outer `{...}` as an expression container and\n// the inner `{now}` as a JS object-literal shorthand property, so the node's\n// value looks like `{now}` — a single bare identifier wrapped in its own\n// braces — never a real JSX prop (which appears inside an attribute, not\n// standalone body/flow text). Matching this shape lets the same \"leave a\n// $ref alone unless we can hint an undeclared reference\" caution apply to\n// double-brace template text as it already does to single-brace text.\nconst BARE_OBJECT_SHORTHAND = /^\\{\\s*([\\p{ID_Start}$_][\\p{ID_Continue}$]*)\\s*\\}$/u\n/**\n * Pure JS built-ins that exist identically in the server and browser render.\n * Only a dotted path rooted at one (`{Math.PI}`, `{Number.MAX_SAFE_INTEGER}`)\n * is left as a live expression. A bare name (`{window}`, `{Date}`,\n * `{console}`) is always escaped: it would render an object/function (a\n * React crash or silently empty text), and host globals such as `window`,\n * `document`, `navigator`, or `process` do not exist on both sides at all.\n */\nconst SAFE_BUILTIN_ROOTS = new Set([\n 'Math', 'JSON', 'Number', 'String', 'Object', 'Array', 'Intl', 'Boolean', 'Symbol', 'BigInt', 'Reflect',\n])\n\ninterface MdxOffsetNode {\n type: string\n depth?: number\n value?: string\n name?: string | null\n data?: { estree?: acorn.Program | null }\n children?: Array<MdxOffsetNode>\n position?: { start: { offset?: number }; end: { offset?: number } }\n}\n\n/** Use a page's leading H1 as its title without rendering it twice. */\nfunction leadingPageHeading(body: string): { title: string; start: number; end: number } | undefined {\n try {\n const root = descriptionParser.parse(body) as MdxOffsetNode\n const first = root.children?.find((node) => node.type !== 'mdxjsEsm' && node.type !== 'html')\n if (first?.type !== 'heading' || first.depth !== 1) return undefined\n const text = (node: MdxOffsetNode): string => node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression'\n ? ''\n : node.value ?? (node.children ?? []).map(text).join('')\n const title = text(first).replace(/\\s+/g, ' ').trim()\n const start = first.position?.start.offset\n const end = first.position?.end.offset\n return title && start !== undefined && end !== undefined ? { title, start, end } : undefined\n } catch {\n return undefined\n }\n}\n\n/** Recursively collects every name a binding pattern introduces (`{a, b: {c}}`, `[p, ...rest]`, `x = 1`). */\nfunction collectPatternNames(pattern: acorn.AnyNode, names: Set<string>): void {\n switch (pattern.type) {\n case 'Identifier':\n names.add((pattern as acorn.Identifier).name)\n break\n case 'ObjectPattern':\n for (const property of (pattern as acorn.ObjectPattern).properties) {\n collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, names)\n }\n break\n case 'ArrayPattern':\n for (const element of (pattern as acorn.ArrayPattern).elements) {\n if (element) collectPatternNames(element, names)\n }\n break\n case 'AssignmentPattern':\n collectPatternNames((pattern as acorn.AssignmentPattern).left, names)\n break\n case 'RestElement':\n collectPatternNames((pattern as acorn.RestElement).argument, names)\n break\n default:\n break\n }\n}\n\n/** Adds the name(s) a single top-level declaration statement introduces (`const`/`let`/`var`, `function`, `class`). */\nfunction collectDeclarationNames(node: acorn.AnyNode | null | undefined, names: Set<string>): void {\n if (!node) return\n if (node.type === 'VariableDeclaration') {\n for (const declarator of (node as acorn.VariableDeclaration).declarations) collectPatternNames(declarator.id, names)\n } else if ((node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') && (node as acorn.FunctionDeclaration | acorn.ClassDeclaration).id) {\n names.add(((node as acorn.FunctionDeclaration | acorn.ClassDeclaration).id as acorn.Identifier).name)\n }\n}\n\n/**\n * Bind every name a page's own ESM statement introduces — an import\n * (default, namespace, or named/destructured, however deeply nested its\n * destructuring goes), or a top-level `const`/`let`/`var`/`function`/`class`\n * — so a prose brace referencing one of them is treated as real,\n * already-bound code rather than ambiguous Fern prose. Read from the ESTree\n * remark-mdx attaches to the `mdxjsEsm` node (real ESM syntax including JSX,\n * not a regex approximation), so `export const a = 1, b = 2`, nested\n * destructuring, and multi-declarator statements all resolve\n * correctly. `export { x } from './y'` (a re-export) and a local `export {\n * x }` (which only re-exposes an already-declared local) never introduce a\n * new binding, so neither is added here — matching real JS module\n * semantics, since referencing `x` in prose is exactly as undefined as it\n * would be in the compiled component.\n */\nfunction collectEsmBindings(node: MdxOffsetNode, declared: Set<string>): void {\n // remark-mdx already parsed this ESM (with JSX support) and keeps the\n // result on the node; re-parsing it with plain acorn fails on any JSX.\n const program = node.data?.estree\n if (!program) {\n collectEsmBindingsByPattern(node.value ?? '', declared)\n return\n }\n for (const statement of program.body) {\n if (statement.type === 'ImportDeclaration') {\n for (const specifier of statement.specifiers) declared.add(specifier.local.name)\n } else if (statement.type === 'ExportNamedDeclaration') {\n collectDeclarationNames(statement.declaration, declared)\n } else if (statement.type === 'ExportDefaultDeclaration') {\n collectDeclarationNames(statement.declaration, declared)\n } else {\n collectDeclarationNames(statement, declared)\n }\n }\n}\n\n/**\n * Fallback when no parsed ESM tree is available: collect simple declared and\n * imported names by pattern, so the page's own bindings are still recognized.\n * Approximate (destructuring is not followed, nested declarations are\n * included), but never records nothing for a page that does bind names.\n */\nfunction collectEsmBindingsByPattern(source: string, declared: Set<string>): void {\n for (const match of source.matchAll(/\\b(?:const|let|var|class|function\\s*\\*?)\\s+([\\p{ID_Start}$_][\\p{ID_Continue}$]*)/gu)) declared.add(match[1])\n for (const match of source.matchAll(/\\bimport\\s+([^'\";]*?)\\s+from\\b/g)) {\n const clause = match[1]\n for (const name of clause.replace(/\\{[^}]*\\}/, '').matchAll(/(?:\\*\\s+as\\s+)?([\\p{ID_Start}$_][\\p{ID_Continue}$]*)/gu)) declared.add(name[1])\n for (const entry of clause.match(/\\{([^}]*)\\}/)?.[1].split(',') ?? []) {\n const local = entry.trim().split(/\\s+as\\s+/).at(-1)?.trim()\n if (local) declared.add(local)\n }\n }\n}\n\n/**\n * Fern's own MDX renderer tolerates a bare `{word}` in prose as literal text\n * (e.g. `\"connection to {vendor} failed\"`, `<Note>connection to {vendor}\n * failed</Note>`); Thally's MDX pipeline evaluates `{...}` as a JS expression\n * and throws `ReferenceError` when the identifier isn't defined. `{vendor}`\n * is syntactically valid MDX either way — a text expression — so the fix\n * isn't a character scan but telling real code from prose: parse the page,\n * then escape a bare identifier/dotted-path text expression\n * (`mdxTextExpression`/`mdxFlowExpression`) anywhere in the body tree,\n * including inside a JSX element's children (a `<Note>`/`<Tabs>` callout is\n * the common Fern case) — but never a JSX *attribute* expression\n * (`prop={x}`, which lives on the node's `attributes`, not its `children`,\n * and this walk never visits it), never ESM, never code. Real component\n * code — `{items.map((item) => <li>{item}</li>)}` — parses as a single\n * expression node whose JSX lives only in its `estree`, not as further mdast\n * children, so this walk cannot (and must not) descend into it and escape\n * the inner `{item}`; only a leaf expression node with every mdast ancestor\n * being JSX/markdown is ever a candidate. `props` (MDX's implicit prop) and\n * anything the page's own ESM imports or declares are exempt. A page whose\n * source doesn't parse is left untouched; the migration's MDX-compile check\n * reports the real problem instead.\n */\n/** Trimmed line begins a fenced code block (```` ``` ```` or `~~~`, 3+ characters). */\nconst FENCE_OPEN = /^(`{3,}|~{3,})/\n\n/**\n * KaTeX-style `$$...$$` math (block, on its own lines, or inline mid-\n * paragraph) is common in Fern docs (and any other Markdown source) but has\n * no Thally renderer (no `remark-math`/`rehype-katex`) — worse, the raw\n * LaTeX inside (`\\begin{align*}`, bare `{...}`) crashes the MDX parser\n * before `escapeFernLiteralBraces` below even gets a chance to run, so the\n * whole page fails to compile and is silently excluded. Content is\n * preserved, never dropped: a block becomes a fenced ` ```math ` code\n * block, an inline span becomes an inline code span — both opaque to MDX's\n * `{...}` expression parsing. This is a plain line scan (not an MDX parse,\n * which is exactly what the source can't survive yet) that tracks fenced\n * code blocks so a real code sample's own `$$` is never touched, and must\n * run before any MDX-aware pass.\n */\n/**\n * Mask, within a single line, every backtick code span and every JSX/HTML\n * tag (open, close, or self-closing — including its attribute values) so\n * `protectMathBlocks`'s inline `$...$` scan below can never mistake a `$`\n * inside either for a math delimiter, and a matched math span can never\n * straddle a masked region (the placeholder has no `$` in it, so the regex\n * simply can't span across one). A JSX tag never spans a `$...$` scan's own\n * line here because `protectMathBlocks` processes text line by line; a tag\n * split across lines is already opaque to it for other reasons.\n */\nfunction maskInlineSpansForMath(line: string): { masked: string; unmask: (text: string) => string } {\n const blocks: Array<string> = []\n const stash = (text: string): string => {\n blocks.push(text)\n return `\\u0000${blocks.length - 1}\\u0000`\n }\n const codeMasked = line.split(/(`[^`]*`)/).map((segment, index) => (\n index % 2 === 1 ? stash(segment) : segment\n )).join('')\n const tagMasked = codeMasked.replace(/<\\/?[a-zA-Z][^<>]*>/g, stash)\n // Also mask a JSX expression container (`{...}`), one level of nesting\n // deep, so `$` inside one (e.g. a prop value built from a template\n // literal that isn't itself backtick-quoted) is never read as a math\n // delimiter. Two passes handle one level of `{...{...}...}` nesting; a\n // line-local regex can't balance further than that, which is fine here —\n // anything left over simply isn't masked, the conservative default. A\n // `{` immediately after `$` is deliberately left unmasked: that is a\n // template-literal interpolation (`${...}`), not a JSX container, and the\n // caller's own `$(?!{)` guard needs to see the literal `{` to reject it.\n const masked = [tagMasked, tagMasked].reduce((text) => text.replace(/(?<!\\$)\\{[^{}]*\\}/g, stash), tagMasked)\n return {\n masked,\n unmask: (text) => text.replace(/\\u0000(\\d+)\\u0000/g, (_match, index: string) => blocks[Number(index)]),\n }\n}\n\n/**\n * Whether `content` (the real, unmasked text between a matched pair of\n * inline `$...$`) looks like actual TeX rather than two unrelated dollar\n * amounts or a stray currency symbol: a backslash command (`\\times`,\n * `\\text{...}`), `^`/`_` (super/subscript), or a brace group. A bare\n * variable-style token with no space and no digit (`$S$`, `$x$`) is also\n * accepted without any of those — KaTeX/Pandoc's own convention for a\n * single-symbol inline reference, and the shape of the paradex-docs repro.\n */\nconst TEX_SIGNAL = /\\\\[a-zA-Z]|[\\^_{]/\nfunction hasTexSignal(content: string): boolean {\n return TEX_SIGNAL.test(content) || (!/\\s/.test(content) && !/\\d/.test(content))\n}\n\n/**\n * Net count of `{`, `(`, `[` minus their closers on `line` — a lazy,\n * string/comment-unaware bracket count (not a real JS parse) used only to\n * tell when a multi-line `import`/`export` ESM statement has closed. Real\n * component source rarely has an unbalanced bracket inside a string on the\n * same line as an ESM statement's own delimiters, and this is a heuristic\n * for skipping a scan, not a correctness-critical parse.\n * TODO: raw character count, ignores strings/comments; a real AST pass\n * would be exact, add one if this heuristic misfires on real content.\n */\nfunction bracketDelta(line: string): number {\n let delta = 0\n for (const ch of line) {\n if (ch === '{' || ch === '(' || ch === '[') delta += 1\n else if (ch === '}' || ch === ')' || ch === ']') delta -= 1\n }\n return delta\n}\n\n/** Trimmed line opens a top-level `import`/`export` ESM statement (Docusaurus/MDX allow one anywhere a block can start, not just at the top of the file). */\nconst ESM_OPEN = /^(?:import|export)\\b/\n\nexport function protectMathBlocks(raw: string): { body: string; converted: boolean; guardTriggered?: boolean } {\n const { front, body } = splitFrontmatterBlock(raw)\n const lines = body.split(/\\r\\n|\\r|\\n/)\n const output: Array<string> = []\n let inFence = false\n let fenceToken = ''\n // Fern also allows a block delimited by a bare `$` alone on its own line\n // (not just `$$`), e.g. `$\\n\\text{...}\\n$`; a block must close on the\n // same delimiter that opened it.\n let mathBlockDelimiter: '$$' | '$' | null = null\n let mathLines: Array<string> = []\n let converted = false\n // Depth of an open `import`/`export` ESM statement (counted in\n // `bracketDelta`): while positive, every line belongs to page-authored\n // JS/JSX source (e.g. an inlined snippet's `export const X = () => {...}`\n // component body), not markdown/math prose, and is copied through\n // untouched — never scanned for `$`, so a template literal's `${expr}`\n // inside it can never be misread as a math delimiter.\n let esmDepth = 0\n for (const line of lines) {\n const trimmed = line.trim()\n if (mathBlockDelimiter) {\n if (trimmed === mathBlockDelimiter) {\n output.push('```math', ...mathLines, '```')\n mathBlockDelimiter = null\n mathLines = []\n converted = true\n } else {\n mathLines.push(line)\n }\n continue\n }\n if (inFence) {\n if (trimmed.startsWith(fenceToken)) inFence = false\n output.push(line)\n continue\n }\n if (esmDepth > 0) {\n output.push(line)\n esmDepth = Math.max(0, esmDepth + bracketDelta(line))\n continue\n }\n const fenceOpen = FENCE_OPEN.exec(trimmed)\n if (fenceOpen) {\n inFence = true\n fenceToken = fenceOpen[1].slice(0, 3)\n output.push(line)\n continue\n }\n if (trimmed === '$$' || trimmed === '$') {\n mathBlockDelimiter = trimmed\n continue\n }\n if (ESM_OPEN.test(trimmed)) {\n output.push(line)\n esmDepth = Math.max(0, bracketDelta(line))\n continue\n }\n if (line.includes('$')) {\n // Mask inline code spans (`` `$FOO` ``), JSX/HTML tags (including\n // their attribute values, e.g. `<Badge color=\"$primary\">`), and a\n // JSX expression container (`{...}`) before scanning for math, so\n // none of them can be mistaken for a math delimiter and a math span\n // can never cross into one — a masked placeholder has no `$` in it,\n // so the scan below simply can't see inside one or pair a `$`\n // outside it with one that was inside it. What's left unmasked is\n // ordinary prose/JSX text content.\n const { masked, unmask } = maskInlineSpansForMath(line)\n // One combined pass, `$$...$$` tried before single-`$...$` at each\n // position: doing these as two sequential passes let the second\n // (single-`$`) regex re-match dollar signs the first pass had just\n // wrapped in backticks, corrupting its own output. Single-`$` inline\n // math (the other half of the KaTeX convention, e.g. `$F = S \\times\n // e^{\\,f\\,T}$`, or a bare `$S$`) only counts when its content\n // doesn't start/end with whitespace, holds no further `$`, and looks\n // like real TeX (`hasTexSignal`) — the same rule KaTeX/Pandoc use to\n // tell real inline math from an ordinary sentence mentioning two\n // dollar amounts (`$50 and $100`, whose span content ends in a space\n // and so never matches). Neither alternative ever opens on `${`\n // (a template-literal interpolation, not a math delimiter). An\n // author-escaped `\\$` (a literal dollar sign) is never treated as a\n // delimiter.\n const updatedMasked = masked.replace(\n /\\$\\$(?!\\{)([^\\n]+?)\\$\\$|(?<!\\\\)\\$(?!\\{)([^\\s$](?:[^$\\n]*[^\\s$])?)\\$/g,\n (whole: string, block: string | undefined, inline: string | undefined) => {\n if (block !== undefined) {\n converted = true\n return `\\`$$${block}$$\\``\n }\n if (inline !== undefined && hasTexSignal(unmask(inline))) {\n converted = true\n return `\\`$${inline}$\\``\n }\n return whole\n },\n )\n output.push(unmask(updatedMasked))\n continue\n }\n output.push(line)\n }\n // An unterminated `$$` block means the source was malformed to begin\n // with; leave it untouched rather than eating the rest of the page into\n // one giant fenced block.\n if (mathBlockDelimiter) return { body: raw, converted: false }\n const protectedBody = front + output.join('\\n')\n if (!converted) return { body: protectedBody, converted }\n // Math conversion must never turn a page that used to compile into one\n // that doesn't (e.g. a false-positive match that corrupts real code).\n // If the protected body fails to compile as MDX but the untouched\n // original did, the conversion made things worse — keep the original and\n // let the caller warn, rather than silently excluding the page later.\n try {\n compileSync(protectedBody, { outputFormat: 'program' })\n return { body: protectedBody, converted }\n } catch {\n try {\n compileSync(raw, { outputFormat: 'program' })\n return { body: raw, converted: false, guardTriggered: true }\n } catch {\n // The original didn't compile either (the usual case math protection\n // exists for) — the protected attempt is still the better bet.\n return { body: protectedBody, converted }\n }\n }\n}\n\nexport function escapeFernLiteralBraces(raw: string): string {\n // Never touch the YAML frontmatter block: its `{...}` values (e.g. a\n // description containing a literal brace) are YAML scalars, not MDX\n // expressions, and running the MDX parser over them corrupts the block.\n // Split it off first — mirroring `parseFrontmatter`'s own delimiter\n // handling, including a leading BOM and CRLF line endings, which a naive\n // `/^---\\n/` guard misses and lets the frontmatter get parsed as MDX.\n const { front, body } = splitFrontmatterBlock(raw)\n\n let root: MdxOffsetNode\n try {\n root = descriptionParser.parse(body) as MdxOffsetNode\n } catch {\n return raw\n }\n\n const declared = new Set<string>(['props'])\n const collectEsm = (node: MdxOffsetNode) => {\n if (node.type === 'mdxjsEsm') collectEsmBindings(node, declared)\n for (const child of node.children ?? []) collectEsm(child)\n }\n collectEsm(root)\n\n const edits: Array<{ start: number; end: number; value: string }> = []\n const visit = (node: MdxOffsetNode) => {\n if (node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression') {\n const value = (node.value ?? '').trim()\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n const root = value.split('.')[0]\n const safeBuiltinPath = value.includes('.') && SAFE_BUILTIN_ROOTS.has(root)\n const isBareIdentifier = BARE_IDENTIFIER_PATH.test(value) && !JS_LITERAL_KEYWORDS.has(value)\n && !declared.has(root) && !safeBuiltinPath\n const shorthandMatch = value.match(BARE_OBJECT_SHORTHAND)\n const isDoubleBraceTemplate = shorthandMatch !== null && !declared.has(shorthandMatch[1])\n const isIssueList = /^[A-Za-z][A-Za-z0-9]*-\\d+(?:\\s*,\\s*[A-Za-z][A-Za-z0-9]*-\\d+)*$/.test(value)\n if ((isBareIdentifier || isDoubleBraceTemplate || isIssueList) && start !== undefined && end !== undefined) {\n // Escape every literal brace in the matched span rather than\n // rebuilding it from `value`, so this handles both `{name}` and\n // `{{name}}` (and any other brace nesting) the same way.\n const rawSpan = body.slice(start, end)\n edits.push({ start, end, value: rawSpan.replace(/\\\\/g, '\\\\\\\\').replace(/[{}]/g, '\\\\$&') })\n }\n // A leaf node: mdast never gives it further `children` (its JSX, if\n // any, lives only inside `data.estree`), so there is nothing to recurse into.\n return\n }\n for (const child of node.children ?? []) visit(child)\n }\n visit(root)\n if (edits.length === 0) return raw\n\n const escapedBody = edits\n .sort((left, right) => right.start - left.start)\n .reduce((result, edit) => `${result.slice(0, edit.start)}${edit.value}${result.slice(edit.end)}`, body)\n return front + escapedBody\n}\n\n/**\n * Split `raw` into its untouched YAML frontmatter block (including a leading\n * BOM, if present) and the remaining MDX body, using the same delimiter\n * rules as `parseFrontmatter` (BOM-aware, CRLF-safe) so the two always agree\n * on where the frontmatter ends. Unlike `parseFrontmatter`, this returns the\n * frontmatter block verbatim (not parsed) because callers here only need to\n * avoid rewriting it, not read its values.\n */\nfunction splitFrontmatterBlock(raw: string): { front: string; body: string } {\n const hasBom = raw.charCodeAt(0) === 0xfeff\n const bom = hasBom ? raw[0] : ''\n const source = hasBom ? raw.slice(1) : raw\n const opening = /^---([^\\r\\n]*)\\r?\\n/.exec(source)\n if (!opening || opening[1].startsWith('-')) return { front: bom, body: source }\n const remainder = source.slice(opening[0].length)\n const closing = /^---[ \\t]*\\r?$/m.exec(remainder)\n if (!closing) return { front: bom, body: source }\n const end = opening[0].length + closing.index + closing[0].length\n return { front: bom + source.slice(0, end), body: source.slice(end) }\n}\n\n/**\n * `components.ts`'s `createComponentMigrator` renames a successfully copied\n * or extracted component's JSX tag to `Migrated<12-hex-char-hash>` and\n * registers it in the project-wide `src/mdx/custom-components.tsx` (merged\n * into every page by `mdx-components.tsx`, not imported per-page) — so a\n * page's own ESM never mentions it, even though it does resolve. Recognize\n * the naming convention rather than re-deriving it from `components.ts`,\n * which would need this module to depend on that one's private `hash()`.\n */\nconst MIGRATED_COMPONENT_TAG = /^Migrated[0-9a-f]{12}$/\n\n/** True when the JSX span itself (not merely its opening tag) is self-closing, e.g. `<Foo />`. */\nfunction isSelfClosingJsx(text: string): boolean {\n return /\\/>\\s*$/.test(text)\n}\n\n/** Replace the leading `<name` / trailing `</name` occurrences of a tag with `newName`, for a tag with no children to preserve (self-closing, or an empty pair). */\nfunction renameTagOccurrences(text: string, name: string, newName: string): string {\n let result = text\n const openIndex = result.indexOf(`<${name}`)\n if (openIndex >= 0) result = `${result.slice(0, openIndex + 1)}${newName}${result.slice(openIndex + 1 + name.length)}`\n const closeIndex = result.lastIndexOf(`</${name}`)\n if (closeIndex >= 0) result = `${result.slice(0, closeIndex + 2)}${newName}${result.slice(closeIndex + 2 + name.length)}`\n return result\n}\n\n/**\n * Reconstructs `body.slice(loStart, hiEnd)` verbatim except through\n * `renderNode` at each of `children`'s own spans — the gaps between/around\n * them (markdown or JSX syntax the children's own positions don't cover,\n * such as a parent JSX element's attributes) are copied through unchanged.\n */\nfunction renderChildrenSpan(\n children: Array<MdxOffsetNode>,\n loStart: number,\n hiEnd: number,\n body: string,\n renderNode: (node: MdxOffsetNode) => string,\n): string {\n let cursor = loStart\n let out = ''\n for (const child of children) {\n const start = child.position?.start.offset\n const end = child.position?.end.offset\n if (start === undefined || end === undefined) continue\n out += body.slice(cursor, start)\n out += renderNode(child)\n cursor = end\n }\n out += body.slice(cursor, hiEnd)\n return out\n}\n\n/**\n * Replaces a page-authored (or Docusaurus/Fern-only) `<Link href=\"...\">`\n * with a plain `<a href=\"...\">`, keeping every attribute and all children\n * exactly as authored — only the tag name changes, so nested content\n * (including any unknown component the fallback below also rewrites) is\n * preserved. A page that declares or imports its own `Link` keeps it\n * untouched; that binding, not this generic one, is what actually renders.\n */\nexport function replaceLinkWithAnchor(raw: string): string {\n return replaceUnknownComponents(raw, () => {}, { onlyRenameLinkTag: true })\n}\n\n/**\n * Fallback for any capitalized JSX tag Thally cannot render: not a builtin\n * (`isThallyBuiltinComponent`) and not declared or imported by the page\n * itself. Mintlify/Docusaurus content commonly references a project-local or\n * npm component that `components.ts`'s copy step already handles when it can\n * be resolved — this only ever fires for what's left: a name with nothing\n * backing it at all, which would otherwise throw \"Expected component X to be\n * defined\" at render. A paired tag becomes a plain `<div>`, keeping its\n * children (so nested prose/markup survives); a self-closing tag is removed\n * outright, since it has no content to keep. `warn` is called once per\n * distinct component name found. `<Link>` is renamed to `<a>` instead of\n * falling into that generic path, since it's common enough to warrant a\n * real mapping (Mintlify/Docusaurus content routinely writes `<Link\n * href=\"...\">`) rather than losing the link.\n *\n * Frontmatter is split off first (see `escapeFernLiteralBraces`) so a YAML\n * value can never be mistaken for JSX.\n */\nexport function replaceUnknownComponents(\n raw: string,\n warn: (name: string) => void,\n options: { onlyRenameLinkTag?: boolean } = {},\n): string {\n const { front, body } = splitFrontmatterBlock(raw)\n\n let root: MdxOffsetNode\n try {\n root = descriptionParser.parse(body) as MdxOffsetNode\n } catch {\n return raw\n }\n\n const declared = new Set<string>(['props'])\n const collectEsm = (node: MdxOffsetNode) => {\n if (node.type === 'mdxjsEsm') collectEsmBindings(node, declared)\n for (const child of node.children ?? []) collectEsm(child)\n }\n collectEsm(root)\n\n const warned = new Set<string>()\n const renderNode = (node: MdxOffsetNode): string => {\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n if (start === undefined || end === undefined) return ''\n const isJsx = node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement'\n const tagRoot = node.name ? node.name.split('.')[0] : undefined\n const text = body.slice(start, end)\n\n if (isJsx && tagRoot === 'Link' && !declared.has('Link')) {\n if (isSelfClosingJsx(text) || !node.children?.length) return renameTagOccurrences(text, node.name!, 'a')\n const openEnd = node.children[0].position?.start.offset ?? start\n const closeStart = node.children.at(-1)!.position?.end.offset ?? end\n return renameTagOccurrences(body.slice(start, openEnd), node.name!, 'a')\n + renderChildrenSpan(node.children, openEnd, closeStart, body, renderNode)\n + renameTagOccurrences(body.slice(closeStart, end), node.name!, 'a')\n }\n\n if (!options.onlyRenameLinkTag && isJsx && tagRoot && /^[A-Z]/.test(tagRoot)\n && !isThallyBuiltinComponent(node.name!) && !declared.has(tagRoot) && !MIGRATED_COMPONENT_TAG.test(tagRoot)) {\n if (!warned.has(node.name!)) {\n warned.add(node.name!)\n warn(node.name!)\n }\n if (isSelfClosingJsx(text)) return ''\n if (!node.children?.length) return '<div></div>'\n const openEnd = node.children[0].position?.start.offset ?? start\n const closeStart = node.children.at(-1)!.position?.end.offset ?? end\n const children = renderChildrenSpan(node.children, openEnd, closeStart, body, renderNode)\n // A flow (block-level) unknown component can wrap block content —\n // a fenced code block, a heading, another flow element — and MDX\n // only recognizes that as block content when it's set off from the\n // surrounding tag by a blank line; gluing it straight onto `<div>`\n // (the previous behavior) reads as inline text, which derails the\n // parser and can surface as an unrelated \"unclosed `<div>`\" error\n // once it hits the real closing tag. The source component's own\n // markup may have had no blank line there at all (a permissive\n // renderer doesn't require one), so always add it rather than\n // trying to detect when it's needed. An inline (text-level) unknown\n // component never contains block content, so it stays glued.\n return node.type === 'mdxJsxFlowElement' ? `<div>\\n\\n${children}\\n\\n</div>` : `<div>${children}</div>`\n }\n\n if (!node.children?.length) return text\n return renderChildrenSpan(node.children, start, end, body, renderNode)\n }\n\n return front + renderNode(root)\n}\n\n/**\n * Replace every fenced code block and inline `code span` in `body` with an\n * opaque single-line placeholder, so a textual rename can run as one pass\n * over the WHOLE body — including a tag or comment that spans multiple\n * lines — without ever matching inside code, then restore the original code\n * text afterward. A rename that only ever sees one line at a time (the old\n * approach) misses anything spanning lines: a `<!--\\n...\\n-->` comment, a\n * `<Warn\\n title=\"x\">` opening tag whose `</Warn>` gets renamed with no\n * matching open, a Docusaurus `<Link\\n to=\"/a\">` likewise. Every rename in\n * this module that isn't already AST-based goes through this one masker\n * instead of re-implementing fence tracking.\n */\nfunction maskCode(body: string): { masked: string; unmask: (text: string) => string } {\n // NUL is never valid in MDX; strip it so it can't collide with the \\u0000\n // placeholder markers stashed below.\n const source = body.replace(/\\u0000/g, '')\n\n const blocks: Array<string> = []\n const stash = (text: string): string => {\n blocks.push(text)\n return `\\u0000${blocks.length - 1}\\u0000`\n }\n\n const lines: Array<string> = []\n let codeFence: string | null = null\n let fenceBuffer: Array<string> = []\n // Note: MDX (mdx-js) disables CommonMark indented code blocks, so\n // 4-space-indented text is never code here and is intentionally left\n // unmasked, matching @mdx-js/mdx's own parsing.\n for (const line of source.split('\\n')) {\n const fenceMatch = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (codeFence) {\n fenceBuffer.push(line)\n // A closing fence has no info string. ` ```python` inside an open\n // Markdown fence is content, not a close; treating it as one can mask\n // every later HTML tag and leave React-invalid attributes untouched.\n if (fenceMatch && fenceMatch[1][0] === codeFence[0]\n && fenceMatch[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(fenceMatch[0].length))) {\n lines.push(stash(fenceBuffer.join('\\n')))\n codeFence = null\n fenceBuffer = []\n }\n continue\n }\n if (fenceMatch) {\n codeFence = fenceMatch[1]\n fenceBuffer = [line]\n continue\n }\n lines.push(line.split(/(`[^`]*`)/).map((segment, index) => (\n index % 2 === 1 ? stash(segment) : segment\n )).join(''))\n }\n // An unterminated fence (malformed source) still must not be rewritten.\n if (fenceBuffer.length) lines.push(stash(fenceBuffer.join('\\n')))\n\n return {\n masked: lines.join('\\n'),\n unmask: (text) => text.replace(/\\u0000(\\d+)\\u0000/g, (_match, index: string) => blocks[Number(index)]),\n }\n}\n\n/**\n * Apply a textual rename to the WHOLE body outside fenced/inline code (via\n * `maskCode`), so a match may span multiple lines.\n */\nexport function replaceOutsideCode(body: string, transform: (whole: string) => string): string {\n const { masked, unmask } = maskCode(body)\n return unmask(transform(masked))\n}\n\n/**\n * Fern authors often link sibling MDX files from Card props and Markdown.\n * Resolve only links to files that actually became pages; unknown paths,\n * external URLs, assets, and examples retain their authored destinations.\n */\nexport function rewriteFernRelativePageLinks(\n body: string,\n currentSourcePath: string,\n routesBySourcePath: ReadonlyMap<string, string>,\n): string {\n const rewrite = (target: string): string => {\n if (!target || target.startsWith('/') || target.startsWith('#') || target.startsWith('?')\n || target.includes('\\\\') || /[\\u0000-\\u001f\\u007f]/.test(target)\n || /^[A-Za-z][A-Za-z\\d+.-]*:/.test(target)) return target\n const suffixAt = target.search(/[?#]/)\n const pathname = suffixAt < 0 ? target : target.slice(0, suffixAt)\n const suffix = suffixAt < 0 ? '' : target.slice(suffixAt)\n if (!pathname || pathname.startsWith('//') || pathname.split('/').some((part) => /%2f|%5c/i.test(part))) return target\n const source = posix.normalize(posix.join(posix.dirname(currentSourcePath.replace(/\\\\/g, '/')), pathname))\n const candidates = /\\.mdx?$/i.test(source) ? [source] : [source, `${source}.mdx`, `${source}.md`, `${source}/index.mdx`, `${source}/index.md`]\n const route = candidates.map((candidate) => routesBySourcePath.get(candidate)).find(Boolean)\n return route ? `/${route.replace(/^\\/+/, '')}${suffix}` : target\n }\n return replaceOutsideCode(body, (text) => text\n .replace(/(\\]\\()(<[^>\\n]+>|[^\\s)]+)(?=\\s|\\))/g,\n (_match, opening: string, target: string) => `${opening}${target.startsWith('<') && target.endsWith('>') ? `<${rewrite(target.slice(1, -1))}>` : rewrite(target)}`)\n .replace(/(\\b(?:href|to)\\s*=\\s*)([\"'])([^\"'\\n]+)\\2/g,\n (_match, opening: string, quote: string, target: string) => `${opening}${quote}${rewrite(target)}${quote}`)\n .replace(/(\\b(?:href|to)\\s*=\\s*\\{\\s*)([\"'])([^\"'\\n]+)\\2(?=\\s*\\})/g,\n (_match, opening: string, quote: string, target: string) => `${opening}${quote}${rewrite(target)}${quote}`))\n}\n\n/** Convert Fern's indented file-list shorthand to Thally's nested Tree nodes. */\nfunction normalizeFernFileTrees(body: string): string {\n return replaceOutsideCode(body, (whole) => whole.replace(/<FileTree\\s*>\\s*\\n([\\s\\S]*?)\\n\\s*<\\/FileTree>/g,\n (original: string, contents: string) => {\n const lines = contents.split(/\\r?\\n/).filter((line) => line.trim())\n if (!lines.length) return original\n const nodes: Array<{ indent: number; name: string; isFolder: boolean }> = []\n for (const line of lines) {\n const match = /^( *)(?:-|\\*|\\+)\\s+(.+?)\\s*$/.exec(line)\n if (!match || match[1].length % 2 !== 0 || match[2].includes('\\u0000')) return original\n nodes.push({ indent: match[1].length / 2, name: match[2], isFolder: match[2].endsWith('/') })\n }\n const output = ['<Tree>']\n const folders: Array<number> = []\n for (const node of nodes) {\n while (folders.length > node.indent) {\n output.push('</Folder>')\n folders.pop()\n }\n // A child without a parent folder is not a reliable tree. Retain the\n // Fern source so migration validation can report it explicitly.\n if (node.indent > folders.length || (node.indent > 0 && folders.length === 0)) return original\n const name = `{${JSON.stringify(node.name)}}`\n if (node.isFolder) {\n output.push(`<Folder name=${name} defaultOpen>`)\n folders.push(node.indent)\n } else {\n output.push(`<File name=${name} />`)\n }\n }\n while (folders.length) {\n output.push('</Folder>')\n folders.pop()\n }\n output.push('</Tree>')\n return output.join('\\n')\n }))\n}\n\n/**\n * Converts an HTML comment (`<!-- text -->`) to MDX's own comment syntax\n * (`{/* text *\\/}`), skipping fenced/inline code. remark-mdx does not parse\n * `<!-- -->` at all — a real Markdown/Docusaurus source commonly has one\n * (`<!-- prettier-ignore -->` ahead of a snippet import is a common\n * Docusaurus pattern) and it otherwise throws \"Unexpected character `!`\"\n * wherever something needs a real MDX parse of the page — not just this\n * module's `normalizeMdx`, but `components.ts`'s independent component\n * analysis too, before that pass ever gets a chance to run.\n */\nexport function normalizeHtmlComments(body: string): string {\n return replaceOutsideCode(body, (whole) => whole.replace(/<!--([\\s\\S]*?)-->/g, (_match, comment: string) => `{/*${comment}*/}`))\n}\n\n/**\n * Rewrite Fern's callout intents to Thally's fixed callout tags without\n * touching fenced code. Delimiters are tracked with a stack so nested and\n * sibling callouts each close with the tag their own opening intent chose.\n * A single scan is required: collecting every opener before visiting any\n * closer incorrectly pairs sibling and nested callouts.\n */\nfunction normalizeFernCallouts(body: string): string {\n return replaceOutsideCode(body, (whole) => {\n const openTags: Array<string | null> = []\n const output: string[] = []\n let cursor = 0\n while (cursor < whole.length) {\n const opening = whole.indexOf('<Callout', cursor)\n const closing = whole.indexOf('</Callout>', cursor)\n const next = opening < 0 ? closing : closing < 0 ? opening : Math.min(opening, closing)\n if (next < 0) break\n output.push(whole.slice(cursor, next))\n if (next === closing) {\n const tag = openTags.pop()\n output.push(tag ? `</${tag}>` : '</Callout>')\n cursor = next + '</Callout>'.length\n continue\n }\n const attributeStart = next + '<Callout'.length\n if (!/[\\s/>]/.test(whole[attributeStart] ?? '')) {\n output.push('<Callout')\n cursor = attributeStart\n continue\n }\n // JSX attributes may contain quoted `>` or expression comparisons.\n // Locate the delimiter in one pass instead of using a backtracking\n // regex over arbitrary source content.\n let end = attributeStart\n let quote: string | null = null\n let expressionDepth = 0\n for (; end < whole.length; end++) {\n const character = whole[end]\n if (quote) {\n if (character === quote && whole[end - 1] !== '\\\\') quote = null\n } else if (character === '\"' || character === \"'\") {\n quote = character\n } else if (character === '{') {\n expressionDepth++\n } else if (character === '}' && expressionDepth > 0) {\n expressionDepth--\n } else if (character === '>' && expressionDepth === 0) {\n break\n }\n }\n if (end === whole.length) {\n output.push(whole.slice(next))\n cursor = whole.length\n break\n }\n const attributes = whole.slice(attributeStart, end)\n const intent = findStaticCalloutIntent(attributes)\n const isSelfClosing = attributes.trimEnd().endsWith('/')\n if (!intent) {\n output.push(whole.slice(next, end + 1))\n if (!isSelfClosing) openTags.push(null)\n } else {\n const value = intent.value.toLowerCase()\n const tag = value === 'warning' ? 'Warning'\n : value === 'success' || value === 'tip' ? 'Tip'\n : value === 'error' || value === 'danger' ? 'Error' : 'Note'\n output.push(`<${tag}${attributes.slice(0, intent.start)}${attributes.slice(intent.end)}>`)\n if (!isSelfClosing) openTags.push(tag)\n }\n cursor = end + 1\n }\n output.push(whole.slice(cursor))\n return output.join('')\n })\n}\n\n/** Find only a static, quoted intent attribute; preserve every other prop. */\nfunction findStaticCalloutIntent(attributes: string): { start: number; end: number; value: string } | null {\n let cursor = 0\n while (cursor < attributes.length) {\n const start = cursor\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n if (cursor === start) { cursor++; continue }\n const nameStart = cursor\n while (/[A-Za-z0-9_-]/.test(attributes[cursor] ?? '')) cursor++\n const name = attributes.slice(nameStart, cursor)\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n if (attributes[cursor] !== '=') continue\n cursor++\n while (/\\s/.test(attributes[cursor] ?? '')) cursor++\n const quote = attributes[cursor]\n if (quote !== '\"' && quote !== \"'\") {\n // Other props may be JSX expressions. Skip balanced braces so a\n // string inside an expression cannot masquerade as an attribute.\n if (quote === '{') {\n let depth = 0\n do {\n if (attributes[cursor] === '{') depth++\n if (attributes[cursor] === '}') depth--\n cursor++\n } while (cursor < attributes.length && depth > 0)\n } else {\n while (cursor < attributes.length && !/\\s/.test(attributes[cursor])) cursor++\n }\n continue\n }\n const valueStart = ++cursor\n while (cursor < attributes.length && attributes[cursor] !== quote) cursor++\n const value = attributes.slice(valueStart, cursor)\n if (cursor < attributes.length) cursor++\n if (name === 'intent') return { start, end: cursor, value }\n }\n return null\n}\n\n/**\n * Unwrap Fern's per-tab `<CodeBlock>` only while inside a `<CodeGroup>`\n * (renamed from Fern's `<CodeBlocks>` earlier in the pipeline). Mintlify also\n * ships a genuine, globally available `<CodeBlock>` component for\n * programmatic rendering inside custom React components — that usage never\n * nests inside a `<CodeGroup>`, so it survives untouched.\n */\nfunction unwrapFernCodeBlockTabs(body: string): string {\n return replaceOutsideCode(body, (whole) => {\n let groupDepth = 0\n return whole.replace(/<CodeGroup\\b[^>]*>|<\\/CodeGroup>|<CodeBlock\\b[^>]*>|<\\/CodeBlock>/g, (match) => {\n if (match.startsWith('<CodeGroup')) {\n groupDepth++\n return match\n }\n if (match === '</CodeGroup>') {\n groupDepth = Math.max(0, groupDepth - 1)\n return match\n }\n return groupDepth > 0 ? '' : match\n })\n })\n}\n\n// TODO: a plain <pre>/<code> shim, not Thally's styled Pre/CodeGroup —\n// upgrade to a registered `CodeBlock` MDX built-in (mirroring Code/CodeGroup)\n// once the scaffold template ships one.\nconst STANDALONE_CODE_BLOCK_SHIM = [\n 'export const CodeBlock = ({ children, filename, ...rest }) => (',\n ' <pre {...rest}>',\n ' {filename ? <div>{filename}</div> : null}',\n ' <code>{children}</code>',\n ' </pre>',\n ');',\n].join('\\n')\n\n/** Extracts the source text of each top-level `export const X = (...) => (…|{…` body. */\nfunction exportDeclarationBodies(body: string): Array<string> {\n const bodies: Array<string> = []\n const opener = /export const \\w+ = [^\\n]*=> ([({])/g\n for (const match of body.matchAll(opener)) {\n const open = match[1]\n const close = open === '(' ? ')' : '}'\n let depth = 1\n let i = (match.index ?? 0) + match[0].length\n while (i < body.length && depth > 0) {\n if (body[i] === open) depth++\n else if (body[i] === close) depth--\n i++\n }\n bodies.push(body.slice((match.index ?? 0) + match[0].length, i))\n }\n return bodies\n}\n\n/**\n * True when `export const NAME = ` (ending right at `sourceIndex`) assigns a\n * real function expression — `function` or an arrow function — rather than a\n * plain value whose initializer merely contains `=>` further in, the way\n * `list.map((x) => x)` does. Only a genuine function reference crosses the\n * server/client boundary as a prop; a value like `items` above does not.\n */\nexport function isFunctionInitializer(source: string, sourceIndex: number): boolean {\n let index = sourceIndex\n const skipSpace = () => { while (/\\s/.test(source[index] ?? '')) index++ }\n // Keywords must end at a word boundary: `functionList`, `asyncMode`, and\n // `classNames` are ordinary identifiers, not function expressions.\n const keyword = (word: string) => new RegExp(`^${word}(?![\\\\w$])`).test(source.slice(index))\n skipSpace()\n if (keyword('async')) {\n index += 'async'.length\n skipSpace()\n // `async => x` is an arrow whose parameter is named `async`.\n if (source.startsWith('=>', index)) return true\n }\n if (keyword('function') || keyword('class')) return true\n if (source[index] === '(') {\n let depth = 0\n for (; index < source.length; index++) {\n if (source[index] === '(') depth++\n else if (source[index] === ')') {\n depth--\n if (depth === 0) {\n index++\n break\n }\n }\n }\n skipSpace()\n return source.startsWith('=>', index)\n }\n const identifier = /^[A-Za-z_$][\\w$]*/.exec(source.slice(index))\n if (!identifier) return false\n index += identifier[0].length\n skipSpace()\n return source.startsWith('=>', index)\n}\n\n/**\n * Detects a page-authored function (`export const Name = () => ...`) passed\n * as a bare JSX prop value (`someProp={Name}`) elsewhere on the same page.\n * Next renders an MDX page as a Server Component by default; an extracted\n * interactive snippet it imports is `'use client'` (see `components.ts`).\n * Passing a plain function across that boundary as a prop throws at render\n * (\"Functions cannot be passed directly to Client Components\") even though\n * the MDX itself compiles cleanly — Mintlify's own renderer has no such\n * server/client split, so this content is valid there. Thally has no import\n * mechanism that moves the declaration into the client module instead, so\n * the page is reported and excluded rather than shipped broken.\n *\n * Two things keep this from over-firing: fenced/inline code (a doc example\n * showing this exact shape) never counts, via `maskCode`; and only a real\n * function initializer counts as \"a function\" — `export const items =\n * list.map((x) => x)` is a plain value, not one, even though its own\n * initializer happens to contain `=>`.\n */\nexport function hasClientBoundaryFunctionProp(body: string): boolean {\n const { masked } = maskCode(body)\n const declared = [...functionDeclaredNames(body)]\n return declared.some((name) => new RegExp(`\\\\w+=\\\\{${name}\\\\}`).test(masked))\n}\n\n/**\n * A page's top-level `export` identifiers that are actually functions — a\n * `function`/`async function` declaration, or an `export const NAME = `\n * whose initializer is a real function expression (see\n * `isFunctionInitializer`). Excludes plain values (`export const diagram =\n * 'graph TD'`), even when their initializer text happens to contain `=>`\n * further in (`export const items = list.map((x) => x)`). Callers that need\n * to know whether a prop value crosses the server/client boundary as a\n * function must check against this set, not every `export const` name —\n * confusing the two would exclude pages that merely pass a string or object\n * to a client component.\n */\nexport function functionDeclaredNames(body: string): Set<string> {\n const { masked } = maskCode(body)\n const names = new Set<string>()\n for (const match of masked.matchAll(/export const (\\w+)\\s*=\\s*/g)) {\n if (isFunctionInitializer(masked, (match.index ?? 0) + match[0].length)) names.add(match[1])\n }\n // Function declarations (incl. `default`, `async`, generators) and classes:\n // a class is a constructor function and is just as unserializable.\n for (const match of masked.matchAll(/export\\s+(?:default\\s+)?(?:async\\s+)?(?:function\\s*\\*?\\s*|class\\s+)(\\w+)/g)) {\n names.add(match[1])\n }\n // One level of aliasing: `export const Alias = Demo` where `Demo` is one.\n for (const match of masked.matchAll(/^export const (\\w+)\\s*=\\s*(\\w+)\\s*;?\\s*$/gm)) {\n if (names.has(match[2])) names.add(match[1])\n }\n return names\n}\n\n/**\n * A page's own `export const` declarations sometimes reference a Mintlify\n * global built-in by bare JS identifier (e.g. `<CodeBlock>` or `<Icon>`\n * inside a custom render function) instead of through prose, where Thally's\n * MDX registry wires it in automatically via `_components`. A bare reference\n * with nothing importing or declaring it throws `ReferenceError` at render.\n * Provide it the same way the source page would have gotten it implicitly:\n * a real import where Thally ships an equivalent, otherwise a minimal\n * same-file shim (see `STANDALONE_CODE_BLOCK_SHIM`).\n */\nfunction provideScopedGlobalReferences(body: string): string {\n const alreadyBound = (name: string): boolean => new RegExp(`\\\\b${name}\\\\s*[=:]|\\\\bimport\\\\s+.*\\\\b${name}\\\\b`).test(body)\n const referencedIn = exportDeclarationBodies(body).join('\\n')\n\n let result = body\n if (/<Icon\\b/.test(referencedIn) && !alreadyBound('Icon')) {\n result = `import { Icon } from '@/components/mdx/content-icon';\\n\\n${result}`\n }\n if (/<CodeBlock\\b/.test(referencedIn) && !alreadyBound('CodeBlock')) {\n result = `${STANDALONE_CODE_BLOCK_SHIM}\\n\\n${result}`\n }\n return result\n}\n\n/**\n * Docusaurus authors a `<Tabs>` block's human labels once, in its own\n * `values={[{ label, value }, ...]}` prop, and each `<TabItem value=\"...\">`\n * repeats only the machine `value`. Thally's `<Tab title=\"...\">` has no\n * separate values table, so each tab's title must be resolved from the\n * parent's `values` entry (a `TabItem`'s own `label` still wins when given).\n * Docusaurus-only props that Thally's `<Tabs>` does not read are dropped so\n * they don't linger as dead JSX attributes on the migrated component.\n */\nfunction normalizeDocusaurusTabs(body: string): string {\n let result = body\n for (let depth = 0; depth < 20; depth += 1) {\n const updated = result.replace(/<Tabs\\b([^>]*)>((?:(?!<Tabs\\b)[\\s\\S])*?)<\\/Tabs>/g, (_match, attributes: string, inner: string) => {\n const labelByValue = new Map<string, string>()\n const valuesSource = attributes.match(/\\bvalues=\\{(\\[[\\s\\S]*?\\])\\s*\\}/)?.[1]\n if (valuesSource) {\n for (const entry of valuesSource.matchAll(/\\{([^{}]*)\\}/g)) {\n const label = entry[1].match(/\\blabel:\\s*(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const value = entry[1].match(/\\bvalue:\\s*(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n if (value) labelByValue.set(value, label ?? value)\n }\n }\n const cleanedAttributes = attributes\n .replace(/\\s*defaultValue=(?:\\{[^}]*\\}|\"[^\"]*\"|'[^']*')/g, '')\n .replace(/\\s*values=\\{[\\s\\S]*?\\]\\s*\\}/g, '')\n .replace(/\\s*values=\\{[^{}]*\\}/g, '')\n .replace(/\\s*groupId=(?:\"[^\"]*\"|'[^']*')/g, '')\n .replace(/\\s*queryString(?:=(?:\\{[^}]*\\}|\"[^\"]*\"|'[^']*'))?/g, '')\n const rewrittenInner = inner\n .replace(/<TabItem\\b([^>]*)>/g, (_itemMatch, itemAttributes: string) => {\n const label = itemAttributes.match(/\\blabel=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const value = itemAttributes.match(/\\bvalue=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n const title = label ?? (value && labelByValue.get(value)) ?? value ?? 'Tab'\n return `<Tab title=\"${title.replace(/\"/g, '"')}\">`\n })\n .replace(/<\\/TabItem>/g, '</Tab>')\n return `<ThallyTabs${cleanedAttributes}>${rewrittenInner}</ThallyTabs>`\n })\n if (updated === result) break\n result = updated\n }\n return result.replace(/<ThallyTabs\\b/g, '<Tabs').replace(/<\\/ThallyTabs>/g, '</Tabs>')\n}\n\nconst TAB_FENCE_OPEN = /^(`{3,}|~{3,})(\\S*)\\s+tab\\b(.*)$/\n\n/**\n * `docusaurus-remark-plugin-tab-blocks` marks each fence in a tab group with\n * a `tab` meta keyword (```` ```js tab title=\"npm\" ````). Thally has no\n * matching remark plugin, but its `<CodeGroup>` already reads the same\n * `title=` fence attribute for tab labels, so consecutive tab-marked fences\n * are wrapped in one and the now-meaningless `tab` keyword is dropped. Only\n * fences that opt in via that keyword are touched — this never fires\n * speculatively on an ordinary fence.\n */\nfunction normalizeDocusaurusTabBlocks(body: string): string {\n const lines = body.split('\\n')\n const output: Array<string> = []\n let index = 0\n while (index < lines.length) {\n const open = lines[index].match(TAB_FENCE_OPEN)\n if (!open) {\n output.push(lines[index])\n index++\n continue\n }\n const blocks: Array<Array<string>> = []\n while (index < lines.length) {\n const start = lines[index].match(TAB_FENCE_OPEN)\n if (!start) break\n const marker = start[1]\n const block = [`${start[1]}${start[2]}${start[3]}`]\n index++\n while (index < lines.length && lines[index].trim() !== marker) {\n block.push(lines[index])\n index++\n }\n block.push(lines[index] ?? marker)\n index++\n blocks.push(block)\n let lookahead = index\n while (lookahead < lines.length && lines[lookahead].trim() === '') lookahead++\n if (!lines[lookahead] || !TAB_FENCE_OPEN.test(lines[lookahead])) break\n index = lookahead\n }\n if (blocks.length > 1) {\n output.push('<CodeGroup>', '')\n for (const block of blocks) output.push(...block, '')\n output.pop()\n output.push('</CodeGroup>')\n } else {\n output.push(...blocks[0])\n }\n }\n return output.join('\\n')\n}\n\n/**\n * Split a CSS declaration list on top-level `;` only — a `;` inside\n * `url(...)` (a data URI commonly contains one) must not end the\n * declaration early.\n */\nfunction splitCssDeclarations(value: string): Array<string> {\n const parts: Array<string> = []\n let depth = 0\n let current = ''\n for (const char of value) {\n if (char === '(') depth++\n else if (char === ')') depth = Math.max(0, depth - 1)\n if (char === ';' && depth === 0) {\n parts.push(current)\n current = ''\n } else {\n current += char\n }\n }\n if (current.trim()) parts.push(current)\n return parts\n}\n\n/**\n * Convert a CSS property name to the key a JSX style object expects:\n * camelCase, vendor prefixes capitalized (`-webkit-transform` ->\n * `WebkitTransform`) except React's own `-ms-` quirk (`msTransform`, not\n * `MsTransform`), and a custom property (`--x`) left as a literal string key.\n */\nfunction cssPropertyToJsKey(property: string): string {\n if (property.startsWith('--')) return JSON.stringify(property)\n const camel = property.replace(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase())\n return camel.startsWith('Ms') ? camel.slice(0, 1).toLowerCase() + camel.slice(1) : camel\n}\n\n/**\n * Convert an HTML `style=\"...\"` attribute's raw CSS text into the object\n * literal a JSX `style={{...}}` prop requires.\n *\n * TODO: `!important` cannot be expressed in a React style object at all\n * (there is no per-declaration escape hatch), so it is dropped rather than\n * left in a value string where it would do nothing; upgrade to a `!` layer\n * of inline `<style>` injection if a real page ever needs it.\n */\nfunction cssTextToStyleObjectLiteral(cssText: string): string {\n const entries = splitCssDeclarations(cssText).flatMap((declaration) => {\n const colon = declaration.indexOf(':')\n if (colon === -1) return []\n const property = declaration.slice(0, colon).trim()\n const value = declaration.slice(colon + 1).replace(/\\s*!\\s*important\\s*$/i, '').trim()\n if (!property || !value || !/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return []\n return [`${cssPropertyToJsKey(property)}: ${JSON.stringify(value)}`]\n })\n return `{${entries.join(', ')}}`\n}\n\n/**\n * Rewrite a string `style=\"...\"`/`style='...'` attribute on a lowercase\n * (intrinsic HTML) JSX element into `style={{...}}`. JSX (unlike HTML)\n * requires `style` to be a mapping from property to value; a raw string —\n * common in Markdown/MDX pasted from HTML, e.g. a copied DataFrame table —\n * throws at render instead of just being ignored, so this must run\n * unconditionally, not only for a known source platform. An already-correct\n * `style={...}` expression is untouched (the match requires a quote right\n * after `=`), as is any component tag (uppercase-first is never matched).\n */\nfunction convertHtmlStyleAttributes(body: string): string {\n return body.replace(\n // The separator before `style=` must be `\\s+`, not a single `\\s`: a\n // multi-line tag indents its attributes, so more than one whitespace\n // character (a newline plus spaces) commonly precedes it.\n /<([a-z][a-zA-Z0-9]*)((?:\\s+[^\\s\"'=<>/]+(?:=(?:\"[^\"]*\"|'[^']*'))?)*)\\s+style=([\"'])([\\s\\S]*?)\\3((?:\\s+[^\\s\"'=<>/]+(?:=(?:\"[^\"]*\"|'[^']*'))?)*)\\s*(\\/?)>/g,\n (_match, tag: string, before: string, _quote: string, styleText: string, after: string, selfClose: string) => (\n `<${tag}${before} style={${cssTextToStyleObjectLiteral(styleText)}}${after}${selfClose ? ' /' : ''}>`\n ),\n )\n}\n\n/** Mintlify allows presentational JSX in Update labels; Thally uses the label as an anchor id. */\nfunction normalizeMintlifyUpdateLabels(body: string): string {\n return body.replace(/(<Update\\b[^>]*\\blabel=)\\{(<\\>[\\s\\S]*?<\\/\\>)\\}/g, (match, prefix: string, fragment: string) => {\n let root: DescriptionNode\n try {\n root = descriptionParser.parse(fragment) as DescriptionNode\n } catch {\n return match\n }\n const plainText = (node: DescriptionNode): string | null => {\n // Preserve only parsed text nodes. Dropping markup with a regex can\n // leave a partial tag in the output when an attribute contains `>`.\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'mdxTextExpression' || node.type === 'mdxFlowExpression' || node.type === 'mdxjsEsm') return null\n const parts = (node.children ?? []).map(plainText)\n return parts.some((part) => part === null) ? null : parts.join('')\n }\n const label = plainText(root)?.replace(/\\s+/g, ' ').trim()\n // Dynamic labels cannot be flattened safely; preserve their source form.\n return label && !/[{}]/.test(label) ? `${prefix}{${JSON.stringify(label)}}` : match\n })\n}\n\n/** Preserve Mintlify's generated `param-*` links on authored settings fields. */\nfunction normalizeMintlifyParameterAnchors(body: string): string {\n const seen = new Set<string>()\n const anchorFor = (name: string): string => {\n const id = `param-${name.toLowerCase().replace(/[._]/g, '-')}`\n if (seen.has(id)) return ''\n seen.add(id)\n return `<a id=\"${id}\"></a>\\n`\n }\n // `replaceOutsideCode` masks inline backticks as well as fenced code, so\n // scan heading lines separately to retain the authored setting name.\n let fence: string | undefined\n const withHeadings = body.split('\\n').map((line) => {\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = undefined\n return line\n }\n if (fence) return line\n const heading = line.match(/^ {0,3}#{1,6}\\s+`([A-Za-z][A-Za-z0-9._-]*)`(?:\\s|$)/)\n return heading ? `${anchorFor(heading[1])}${line}` : line\n }).join('\\n')\n return replaceOutsideCode(withHeadings, (segment) => segment\n .replace(/<(ResponseField|ParamField)\\b([^>]*?)\\bname=(?:\"([A-Za-z][A-Za-z0-9._-]*)\"|'([A-Za-z][A-Za-z0-9._-]*)')([^>]*)>/g,\n (match: string, _tag: string, _before: string, doubleQuoted: string, singleQuoted: string) =>\n `${anchorFor(doubleQuoted ?? singleQuoted)}${match}`))\n}\n\ninterface FenceLine { index: number; indent: string; char: string; length: number; info: string; rest: string }\n\nfunction matchFenceLine(line: string): FenceLine | null {\n const match = line.match(/^(\\s*)(`{3,}|~{3,})(.*)$/)\n if (!match) return null\n return { index: -1, indent: match[1], char: match[2][0], length: match[2].length, info: match[3].trim(), rest: match[3] }\n}\n\n/**\n * Widen an outer fence (for example a ```mdx block demonstrating authored\n * Markdown) whose content contains a same-or-greater-length nested fence.\n * CommonMark has no concept of fence nesting, so an inner fence of matching\n * length closes the outer one early and strands the rest as raw JSX/markdown.\n * A nested fence is identified by carrying an info string; a bare fence line\n * always closes the innermost open block, matching authoring convention.\n */\nfunction normalizeNestedCodeFences(body: string): string {\n const lines = body.split('\\n')\n const fences = lines\n .map((line, index) => {\n const fence = matchFenceLine(line)\n return fence ? { ...fence, index } : null\n })\n .filter((fence): fence is FenceLine => fence !== null)\n if (fences.length === 0) return body\n\n interface Block { open: FenceLine; close: FenceLine; children: Array<Block> }\n const stack: Array<{ open: FenceLine; children: Array<Block> }> = []\n const roots: Array<Block> = []\n for (const fence of fences) {\n const top = stack.at(-1)\n if (top && fence.info === '' && fence.char === top.open.char && fence.length >= top.open.length) {\n stack.pop()\n const block: Block = { open: top.open, close: fence, children: top.children }\n const parent = stack.at(-1)\n if (parent) parent.children.push(block)\n else roots.push(block)\n } else {\n stack.push({ open: fence, children: [] })\n }\n }\n // An unresolved stack means the fences do not actually nest; leave the\n // source untouched rather than guess at intent.\n if (stack.length > 0) return body\n\n const widenedLengths = new Map<number, number>()\n function requiredLength(block: Block): number {\n const deepestChild = Math.max(0, ...block.children.map(requiredLength))\n const length = Math.max(block.open.length, deepestChild > 0 ? deepestChild + 1 : 0)\n widenedLengths.set(block.open.index, length)\n widenedLengths.set(block.close.index, length)\n return length\n }\n roots.forEach(requiredLength)\n\n return lines\n .map((line, index) => {\n const targetLength = widenedLengths.get(index)\n const fence = targetLength ? matchFenceLine(line) : null\n if (!targetLength || !fence || targetLength <= fence.length) return line\n return `${fence.indent}${fence.char.repeat(targetLength)}${fence.rest}`\n })\n .join('\\n')\n}\n\n/** Replace fenced code blocks and inline code spans with same-length filler. */\nfunction maskCodeRegions(body: string): string {\n let inFence = false\n return body.split('\\n').map((line) => {\n if (/^\\s*(`{3,}|~{3,})/.test(line)) {\n inFence = !inFence\n return ' '.repeat(line.length)\n }\n if (inFence) return ' '.repeat(line.length)\n return line.replace(/`[^`]*`/g, (span) => ' '.repeat(span.length))\n }).join('\\n')\n}\n\nfunction isKnownComponentName(name: string, body: string): boolean {\n if (isThallyBuiltinComponent(name)) return true\n if (new RegExp(`^\\\\s*export\\\\s+(?:const|function|default\\\\s+function)\\\\s+${name}\\\\b`, 'm').test(body)) return true\n if (new RegExp(`^\\\\s*import\\\\s+(?:\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}|${name})\\\\s+from\\\\s+['\"][^'\"]+['\"]`, 'm').test(body)) return true\n return false\n}\n\n/**\n * Mintlify content occasionally uses a bare capitalized word in angle\n * brackets as a prose placeholder — for example \"<Feature> requires a Pro\n * plan\" — which is invalid JSX: a tag must self-close or have a matching\n * close. Left alone, this crashes MDX compilation for the whole page. A tag\n * name that never closes or self-closes anywhere in the document, and isn't\n * a known built-in, imported, or locally declared component, is almost\n * certainly such a placeholder — escape it to literal text rather than\n * losing the page.\n */\nfunction escapeOrphanCapitalizedTags(body: string): string {\n const masked = maskCodeRegions(body)\n // The attribute group is lazy so a trailing self-close slash is captured by\n // its own group instead of being swallowed as the last attribute character.\n const tagPattern = /<(\\/?)([A-Z][A-Za-z0-9]*)(?:\\s+[^<>]*?)?(\\/?)>/g\n const opens = new Map<string, Array<{ start: number; end: number }>>()\n const closedOrSelfClosed = new Set<string>()\n for (const match of masked.matchAll(tagPattern)) {\n const [full, closing, name, selfClosing] = match\n if (closing || selfClosing) {\n closedOrSelfClosed.add(name)\n continue\n }\n const start = match.index!\n const list = opens.get(name) ?? []\n list.push({ start, end: start + full.length })\n opens.set(name, list)\n }\n const edits: Array<{ start: number; end: number }> = []\n for (const [name, ranges] of opens) {\n if (closedOrSelfClosed.has(name) || isKnownComponentName(name, body)) continue\n edits.push(...ranges)\n }\n if (edits.length === 0) return body\n // The scan above is textual, so it cannot tell prose from a string inside an\n // expression or export. A page that already compiles needs no escaping;\n // never rewrite one.\n try {\n compileSync(body, { outputFormat: 'program' })\n return body\n } catch {\n // Fails to compile: escape the placeholders below.\n }\n edits.sort((a, b) => a.start - b.start)\n let result = ''\n let cursor = 0\n for (const edit of edits) {\n result += body.slice(cursor, edit.start)\n result += body.slice(edit.start, edit.end).replace(/^</, '<').replace(/>$/, '>')\n cursor = edit.end\n }\n return result + body.slice(cursor)\n}\n\nconst REACT_HOOK_NAMES = ['useState', 'useEffect', 'useRef', 'useCallback', 'useMemo', 'useContext', 'useReducer']\n\n/**\n * Mintlify documents these seven hooks as pre-injected globals for a page's\n * inline `export const Widget = () => {...}` components. The migrator's\n * component extraction (components.ts) moves a component that really calls\n * one of these hooks into its own client module, so this is only a fallback\n * for a hook call the extractor doesn't own (for example directly in the\n * page body). Detection is fence-aware: merely showing `useState(...)` in a\n * documentation code sample must not import it — that import alone, unused\n * or not, marks the compiled page a Client Component and breaks the build.\n */\nfunction injectReactHookImports(body: string): string {\n const masked = maskCodeRegions(body)\n const used = REACT_HOOK_NAMES.filter((hook) => (\n new RegExp(`\\\\b${hook}\\\\s*\\\\(`).test(masked)\n && !new RegExp(`import\\\\s*\\\\{[^}]*\\\\b${hook}\\\\b[^}]*\\\\}\\\\s*from\\\\s*['\"]react['\"]`).test(body)\n ))\n return used.length > 0 ? `import { ${used.join(', ')} } from 'react'\\n\\n${body}` : body\n}\n\n/** Normalize only syntax Thally cannot render; supported source JSX stays intact. */\nexport function normalizeMdx(body: string, platform?: MigrationPlatform, unwrapMdxCodeBlocks = true): string {\n // A caller that doesn't know the source platform (the URL crawler, when it\n // can't identify one) must not guess — applying every platform's textual\n // renames to a page of unknown origin corrupts one that happens to use the\n // same component name for something else, e.g. a Mintlify page's own\n // `<Success>` becoming `<Tip>`, a Fern-only alias. An omitted platform\n // therefore runs no platform-specific renames; a caller exercising one\n // must pass it explicitly.\n const runFern = platform === 'fern'\n const runMintlify = platform === 'mintlify'\n const runDocusaurus = platform === 'docusaurus'\n\n // A heading's explicit `{#custom-id}` anchor (see `normalizeExplicitHeadingIds`)\n // means the same thing on every platform, so — unlike the platform-specific\n // renames below — this always runs, even when `platform` is omitted.\n // `normalizeExplicitHeadingIds` also covers Docusaurus' `{/* #id */}`\n // comment form.\n const sourceBody = runDocusaurus && unwrapMdxCodeBlocks ? unwrapDocusaurusMdxCodeBlocks(body) : body\n let rewritten = normalizeDocusaurusAdmonitions(normalizeExplicitHeadingIds(runFern ? normalizeFernFileTrees(normalizeFernCallouts(normalizeNestedCodeFences(sourceBody))) : normalizeNestedCodeFences(sourceBody)))\n if (runDocusaurus) {\n // Docusaurus resolves GitHub emoji names in Markdown text. Leaving the\n // shortcodes literal makes comparison tables unreadable after import; the\n // code masker keeps examples and inline code byte-for-byte intact.\n rewritten = replaceOutsideCode(rewritten, (segment) => segment.replace(\n /:([+\\w-]+):/g,\n (shortcode: string, name: string) => nameToEmoji[name] ?? shortcode,\n ))\n // Docusaurus injects these theme components globally. Thally also\n // exposes its equivalents globally, so source-only imports must not survive.\n rewritten = normalizeDocusaurusTabBlocks(normalizeDocusaurusTabs(removeGlobalDocusaurusImports(rewritten)))\n // Data-only @site imports are often used solely by Docusaurus' tab\n // metadata. Once those props are projected to <Tab> labels, remove only\n // imports whose binding has no remaining use on the page.\n rewritten = replaceOutsideCode(rewritten, (segment) => segment.replace(\n /\\bimport\\s+([A-Za-z_$][\\w$]*)\\s+from\\s+(['\"])(@site\\/[^'\"]+)\\2\\s*;?/g,\n (statement: string, binding: string, _quote: string, _source: string, offset: number) => {\n const withoutStatement = segment.slice(0, offset) + segment.slice(offset + statement.length)\n return new RegExp(`\\\\b${binding}\\\\s*(?:\\\\.|\\\\[|\\\\})`).test(withoutStatement) ? statement : ''\n },\n ))\n rewritten = rewritten.replace(/^\\n{2,}/, '\\n')\n }\n if (runMintlify) rewritten = normalizeMintlifyParameterAnchors(rewritten)\n rewritten = replaceOutsideCode(rewritten, (segment) => {\n let result = convertHtmlStyleAttributes(segment)\n .replace(/<!--([\\s\\S]*?)-->/g, (_match, content: string) => `{/*${content}*/}`)\n .replace(/<Danger(\\s[^>]*)?>/g, '<Error$1>')\n .replace(/<\\/Danger>/g, '</Error>')\n .replace(/<Warn(\\s[^>]*)?>/g, '<Warning$1>')\n .replace(/<\\/Warn>/g, '</Warning>')\n .replace(/<Check(\\s[^>]*)?>/g, '<Note$1>')\n .replace(/<\\/Check>/g, '</Note>')\n .replace(/<Tree\\.Folder/g, '<Folder')\n .replace(/<\\/Tree\\.Folder>/g, '</Folder>')\n .replace(/<Tree\\.File/g, '<File')\n .replace(/<\\/Tree\\.File>/g, '</File>')\n if (runDocusaurus) {\n result = result\n // A TabItem outside any <Tabs>...</Tabs> pair (malformed source)\n // never reaches normalizeDocusaurusTabs' block match above; fall\n // back to its own label/value so it still renders as a Tab.\n .replace(/<TabItem\\b([^>]*)>/g, (_match, attributes: string) => {\n const title = attributes.match(/\\blabel=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n ?? attributes.match(/\\bvalue=(?:\"([^\"]*)\"|'([^']*)')/)?.slice(1).find(Boolean)\n ?? 'Tab'\n return `<Tab title=\"${title.replace(/\"/g, '"')}\">`\n })\n .replace(/<\\/TabItem>/g, '</Tab>')\n .replace(/<Link\\b([^>]*)\\bto=(?:\"([^\"]*)\"|'([^']*)')([^>]*)>/g, (_match, before: string, doubleQuoted: string, singleQuoted: string, after: string) => (\n `<a${before}href=\"${doubleQuoted ?? singleQuoted}\"${after}>`\n ))\n .replace(/<\\/Link>/g, '</a>')\n // The repository adapter expands DocCardList from the resolved\n // sidebar after page discovery. Its source tag has no runtime peer.\n .replace(/<(?:DocCardList|TOCInline)\\b[^>]*\\/>/g, '')\n }\n if (runMintlify) {\n result = normalizeMintlifyUpdateLabels(result)\n // Mintlify documents `<FileTree>` as a plain alias of `<Tree>`; Thally\n // only registers the latter.\n .replace(/<FileTree(\\s[^>]*)?>/g, '<Tree$1>')\n .replace(/<\\/FileTree>/g, '</Tree>')\n // Mintlify's `<GitHub.Repo repo=\"owner/name\" />` is the same repository\n // card Thally already registers as `<GitHub repo=\"owner/name\" />`.\n .replace(/<GitHub\\.Repo/g, '<GitHub')\n .replace(/<\\/GitHub\\.Repo>/g, '</GitHub>')\n // `<Column>` is an unstyled wrapper for arbitrary content inside\n // `<Columns>`; Thally's grid already treats any direct child as a\n // column, so a plain `<div>` (built into MDX, no registry entry\n // needed) matches.\n .replace(/<Column(\\s[^>]*)?>/g, '<div$1>')\n .replace(/<\\/Column>/g, '</div>')\n }\n if (runFern) {\n result = result\n // Fern-only wrappers with a direct Thally equivalent.\n .replace(/<CodeBlocks(\\s[^>]*)?>/g, '<CodeGroup$1>')\n .replace(/<\\/CodeBlocks>/g, '</CodeGroup>')\n .replace(/<ParameterField\\b/g, '<ParamField')\n .replace(/<\\/ParameterField>/g, '</ParamField>')\n .replace(/<Cards(\\s[^>]*)?>/g, '<CardGroup$1>')\n .replace(/<\\/Cards>/g, '</CardGroup>')\n .replace(/<Success(\\s[^>]*)?>/g, '<Tip$1>')\n .replace(/<\\/Success>/g, '</Tip>')\n .replace(/<Launch(\\s[^>]*)?>/g, '<Note$1>')\n .replace(/<\\/Launch>/g, '</Note>')\n // Fern's <Files> wraps <File>/<Folder> nodes Thally already renders\n // directly (also reached via the Docusaurus <Tree.Folder> rename above).\n .replace(/<Files(\\s[^>]*)?>\\n?/g, '')\n .replace(/<\\/Files>/g, '')\n }\n return result\n })\n if (runFern) rewritten = unwrapFernCodeBlockTabs(rewritten)\n const normalized = escapeOrphanCapitalizedTags(provideScopedGlobalReferences(rewritten))\n if (runDocusaurus && sourceBody !== body) {\n try {\n compileSync(normalized, { outputFormat: 'program' })\n } catch {\n // Some Docusaurus sites use this fence for imports or JSX fragments\n // whose surrounding source requires their private remark transforms.\n // Retain the original fenced page instead of dropping it entirely.\n return normalizeMdx(body, platform, false)\n }\n }\n return normalized\n}\n\n/** Parse source Markdown or MDX into the canonical page representation. */\nexport function parseMarkdownPage(input: {\n id: string\n navigationId?: string\n locale?: string\n raw: string\n source: string\n /** Gates platform-specific textual renames in `normalizeMdx`; omitted runs them all. */\n platform?: MigrationPlatform\n /** Resolve platform-specific routes from the already-parsed frontmatter. */\n resolveIdentity?: (\n frontmatter: Record<string, unknown>,\n fallback: MarkdownPageIdentity,\n ) => MarkdownPageIdentity\n}): MigrationPage | null {\n const parsed = parseFrontmatter(input.raw)\n const fallbackIdentity: MarkdownPageIdentity = {\n id: input.id,\n navigationId: input.navigationId ?? input.id,\n ...(input.locale ? { locale: input.locale } : {}),\n }\n const identity = input.resolveIdentity?.(parsed.data, fallbackIdentity) ?? fallbackIdentity\n let body = injectReactHookImports(normalizeMdx(parsed.content, input.platform)).trim()\n const keywords = Array.isArray(parsed.data.keywords)\n ? parsed.data.keywords.filter((value): value is string => typeof value === 'string')\n : []\n const heading = leadingPageHeading(body)\n const title = typeof parsed.data.title === 'string' && parsed.data.title.trim()\n ? parsed.data.title.trim()\n : heading?.title ?? titleFromId(identity.navigationId)\n if (heading && heading.title === title) {\n body = `${body.slice(0, heading.start)}${body.slice(heading.end)}`.trim()\n }\n const navTitle = typeof parsed.data.sidebarTitle === 'string' && parsed.data.sidebarTitle.trim()\n ? parsed.data.sidebarTitle.trim()\n : typeof parsed.data.navTitle === 'string' && parsed.data.navTitle.trim()\n ? parsed.data.navTitle.trim()\n : undefined\n const badge = typeof parsed.data.tag === 'string' && parsed.data.tag.trim()\n ? parsed.data.tag.trim()\n : typeof parsed.data.badge === 'string' && parsed.data.badge.trim()\n ? parsed.data.badge.trim()\n : undefined\n const sourceMode = typeof parsed.data.mode === 'string' ? parsed.data.mode : undefined\n // Mintlify's frame mode and Thally's wide mode both retain the sidebar while\n // removing the on-page table of contents. Other shared modes map directly.\n const mode = sourceMode === 'frame'\n ? 'wide'\n : ['default', 'wide', 'custom', 'center', 'home'].includes(sourceMode ?? '')\n ? sourceMode as MigrationPage['mode']\n : undefined\n const description = typeof parsed.data.description === 'string' && parsed.data.description.trim()\n ? parsed.data.description.trim()\n : firstParagraph(body)\n return {\n id: identity.id,\n navigationId: identity.navigationId,\n locale: identity.locale,\n title,\n navTitle,\n description,\n ...(input.platform === 'docusaurus' || input.platform === 'fern'\n ? { descriptionPlacement: 'body' as const }\n : {}),\n badge,\n keywords,\n mode,\n hidden: parsed.data.hidden === true ? true : undefined,\n noindex: parsed.data.noindex === true || parsed.data.noindex === 'true' ? true : undefined,\n openapi: typeof parsed.data.openapi === 'string' ? parsed.data.openapi.trim() : undefined,\n body,\n source: input.source,\n ...(parsed.error ? { frontmatterError: parsed.error } : {}),\n }\n}\n","/**\n * Thally's registered MDX built-in component tag names, kept in one place so\n * the unknown-component fallback (`mdx.ts`) knows what already renders\n * without guessing. Mirrors the registry in the Thally runtime's\n * `src/components/mdx/builtin-components.tsx` (read-only from this package,\n * which ships standalone and cannot import app source at runtime).\n *\n * A drift guard (`src/components/mdx/client-registry.test.ts`, in the app\n * package) recomputes this set straight from that registry's AST and fails\n * CI if the two disagree, so a renderer change that adds or removes a\n * built-in fails loudly here instead of silently going stale in the\n * migrator.\n */\nexport const THALLY_BUILTIN_COMPONENTS: ReadonlySet<string> = new Set([\n 'CodeGroup', 'Info', 'Warning', 'Check', 'Danger', 'Error', 'Note', 'Tip',\n 'Callout', 'AccordionGroup', 'Latex', 'Hero', 'Card', 'CardGroup',\n 'Columns', 'Frame', 'Accordion', 'Tooltip', 'Icon', 'Steps', 'Step',\n 'Tabs', 'Tab', 'Badge', 'Update', 'RequestExample', 'ResponseExample',\n 'Panel', 'ContentPanel', 'InlinePanel', 'InlineRequestExample',\n 'InlineResponseExample', 'Tile', 'TileGroup', 'Prompt', 'PromptUser',\n 'PromptAssistant', 'Terminal', 'TerminalInput', 'TerminalOutput',\n 'AgentPrompt', 'Color', 'Tree', 'Folder', 'File', 'ResponseField',\n 'ParamField', 'Expandable', 'Mermaid', 'View', 'Embed', 'LegacyView',\n 'GitHub', 'Github', 'Visibility', 'Human', 'Agent', 'BannerPreview', 'Banner',\n 'CodeBlock', 'Column', 'FileTree', 'LiteYouTubeEmbed', 'MDX', 'Video', 'YouTube',\n])\n\n/** True for a builtin tag, or a member-expression tag on one (`Color.Item` -> `Color`). */\nexport function isThallyBuiltinComponent(name: string): boolean {\n return THALLY_BUILTIN_COMPONENTS.has(name) || THALLY_BUILTIN_COMPONENTS.has(name.split('.')[0])\n}\n","/** Safe path normalization used before reading or writing migrated content. */\n\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\n\nconst SAFE_SEGMENT = /[^a-z0-9._-]+/gi\n\n/**\n * Remove trailing forward slashes in linear time. Keeping leading slashes is\n * important because callers may still need to reject absolute paths.\n */\nexport function trimTrailingSlashes(value: string): string {\n let end = value.length\n while (end > 0 && value.charCodeAt(end - 1) === 47) end--\n return value.slice(0, end)\n}\n\n/** Remove forward slashes from both ends without a backtracking expression. */\nexport function trimEdgeSlashes(value: string): string {\n let start = 0\n let end = value.length\n while (start < end && value.charCodeAt(start) === 47) start++\n while (end > start && value.charCodeAt(end - 1) === 47) end--\n return value.slice(start, end)\n}\n\n/** Turn a source path segment into a stable URL/file-system slug. */\nexport function slugifySegment(value: string, preserveCase = false): string {\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // Malformed percent escapes are legal in source filenames. Treat them as\n // literal slug input instead of letting one file abort the whole import.\n }\n const normalized = preserveCase ? decoded : decoded.toLowerCase()\n return normalized\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(SAFE_SEGMENT, '-')\n .replace(/(^-|-$)/g, '')\n}\n\n/**\n * Normalize a page reference to a Thally content id. Invalid or traversal\n * references return `null` instead of being allowed near the file system.\n */\nexport function pageIdFromReference(value: string, preserveCase = false): string | null {\n const withoutQuery = value.split(/[?#]/, 1)[0].replace(/\\\\/g, '/').replace(/^\\/+/, '')\n if (!withoutQuery || withoutQuery.includes('\\0')) return null\n const rawSegments = withoutQuery.split('/').filter(Boolean)\n if (rawSegments.some((segment) => segment === '..' || segment === '.')) return null\n const last = rawSegments.at(-1)?.replace(/\\.(?:mdx?|rst|txt)$/i, '') ?? ''\n // `index` collapses to its parent directory at any depth, matching how\n // Mintlify and Next.js both treat directory indexes. `readme` only does the\n // same at the content root (`readme.md` -> `/`); a nested `readme` is a\n // real, addressable page (`migration/readme.md` -> `/migration/readme`)\n // and must not collide with a sibling `migration/index.md`.\n const isRootLevelReadme = rawSegments.length === 1 && /^readme$/i.test(last)\n const collapsesToParent = /^index$/i.test(last) || isRootLevelReadme\n const baseSegments = collapsesToParent ? rawSegments.slice(0, -1) : rawSegments\n if (!collapsesToParent) {\n baseSegments[baseSegments.length - 1] = last\n }\n const segments = baseSegments.map((segment) => slugifySegment(segment, preserveCase)).filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\n/**\n * Resolve language directories and legacy language-prefixed sections to the\n * same content identity used by default-language navigation. A hyphenated\n * section is only an alias when its unprefixed counterpart actually exists.\n */\nexport function mintlifyLocalizedReference(\n value: string,\n locale: string,\n defaultPageIds: ReadonlySet<string> = new Set(),\n): string {\n const reference = value.replace(/^\\/+/, '')\n const localePrefix = `${locale.toLowerCase()}/`\n if (reference.toLowerCase().startsWith(localePrefix)) return reference.slice(localePrefix.length)\n const sectionPrefix = `${locale.toLowerCase()}-`\n if (reference.toLowerCase().startsWith(sectionPrefix)) {\n const candidate = reference.slice(sectionPrefix.length)\n const candidateId = pageIdFromReference(candidate, true)\n if (candidateId && defaultPageIds.has(candidateId)) return candidate\n }\n // A versioned site nests the locale one level in instead of leading\n // (\"edge/ar/introduction\", not \"ar/edge/introduction\") — every version's\n // page references repeat this shape for every language, so the locale\n // segment shows up mid-path rather than only as a directory prefix. Drop\n // the first segment that exactly matches the locale wherever it falls,\n // so the resulting identity is shared across languages instead of the\n // caller re-adding a locale prefix on top of one already embedded here.\n const segments = reference.split('/')\n const localeIndex = segments.findIndex((segment) => segment.toLowerCase() === locale.toLowerCase())\n if (localeIndex > 0) {\n return [...segments.slice(0, localeIndex), ...segments.slice(localeIndex + 1)].join('/')\n }\n return value\n}\n\n/** Resolve an untrusted relative path and prove it remains below `root`. */\nexport function resolveWithin(root: string, candidate: string): string {\n return resolveWithinRoot(root, candidate, root)\n}\n\n/**\n * Resolve an untrusted relative path against `baseDir`, but only require the\n * result to stay below `confineRoot` (which may be an ancestor of `baseDir`).\n * Used where a config file's relative paths are conventionally resolved\n * against the file's own directory, yet the security boundary is a wider\n * root (e.g. the whole repository checkout).\n */\nexport function resolveWithinRoot(baseDir: string, candidate: string, confineRoot: string): string {\n if (isAbsolute(candidate) || candidate.includes('\\0')) {\n throw new Error(`Unsafe migration path: ${candidate}`)\n }\n const target = resolve(baseDir, candidate)\n const fromRoot = relative(resolve(confineRoot), target)\n if (fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {\n throw new Error(`Migration path escapes its root: ${candidate}`)\n }\n return target\n}\n\n/** Return a slash-separated, traversal-free asset path. */\nexport function normalizeAssetPath(value: string): string | null {\n const normalized = value.replace(/\\\\/g, '/').replace(/^\\/+/, '')\n if (!normalized || normalized.includes('\\0')) return null\n const segments = normalized.split('/').filter(Boolean)\n if (segments.some((segment) => segment === '.' || segment === '..')) return null\n return segments.join('/')\n}\n","/**\n * Analysis behind the migrator's extraction of a page's own inline\n * components into a `'use client'` module (see `components.ts`).\n *\n * A page component that calls a React hook cannot stay in the page: Next\n * compiles an MDX page as a Server Component. Moving only that component is\n * not enough, because it may use other declarations from the same page (a\n * sibling component, a helper, a data array) that the client module cannot\n * reach. This module computes what has to travel with it, what the page\n * still needs a copy of, and refuses (with a reason) when a dependency cannot\n * be made available in the client module, so a page is never left half moved.\n */\n\nimport ts from 'typescript'\n\nimport { isThallyBuiltinComponent } from './builtin-components.js'\n\nexport interface InlineDeclaration { start: number; end: number; source: string }\n\ntype RefKind = 'tag' | 'member' | 'prop' | 'other'\ninterface Ref { name: string; kind: RefKind }\n\ninterface Unit {\n index: number\n source: string\n names: Array<string>\n refs: Array<Ref>\n /** Page-level names this declaration reassigns or mutates. */\n assigned: Array<string>\n hooks: boolean\n /** Handlers, browser globals: cannot render in a Server Component. */\n clientOnly: boolean\n componentLike: boolean\n blockers: Array<string>\n}\n\n/** Minimal MDX syntax-tree shape needed to find the page's own references. */\nexport interface InlineTree {\n type: string\n name?: string | null\n value?: string\n attributes?: Array<{ type: string; name?: string; value?: string | { type?: string; value?: string } | null }>\n children?: Array<InlineTree>\n}\n\nexport interface InlinePlan {\n /** Blocked roots, each with the reason it was left in the page. */\n blocked: Array<{ name: string; reason: string }>\n /** Declarations deleted from the page (declaration indexes). */\n moved: Array<number>\n /** Declarations the page keeps and the client module also receives. */\n copied: Array<number>\n /** Names of every moved declaration. */\n movedNames: Array<string>\n /** Import statements the client module needs, in source order. */\n moduleImports: Array<string>\n /** Server-side helper declarations (page-level text) the module also needs. */\n moduleHelpers: Array<string>\n /** Moved names used as a JSX tag in the page body (registered, then renamed). */\n registryNames: Array<string>\n /** Moved names the page reaches by their real name (import statement needed). */\n pageImportNames: Array<string>\n /** Local names every module statement may reference without a built-in lookup. */\n moduleNames: Set<string>\n /** Names still referenced by the page after the move (drives import cleanup). */\n pageReferences: Set<string>\n}\n\nconst SERVER_ONLY_IDENTIFIERS = new Set(['process', 'require', 'module', 'exports', '__dirname', '__filename', 'Buffer'])\nconst BROWSER_IDENTIFIERS = new Set([\n 'window', 'document', 'localStorage', 'sessionStorage', 'navigator', 'location', 'history',\n 'IntersectionObserver', 'ResizeObserver', 'MutationObserver', 'matchMedia', 'requestAnimationFrame',\n 'cancelAnimationFrame', 'alert', 'confirm', 'prompt', 'HTMLElement', 'Element', 'Node', 'Event',\n 'KeyboardEvent', 'MouseEvent', 'CustomEvent', 'FormData', 'File', 'FileReader', 'Image', 'Audio',\n 'XMLHttpRequest', 'WebSocket', 'getComputedStyle', 'innerWidth', 'innerHeight', 'scrollTo',\n])\n/** Bare names any module may reference without declaring them. */\n// An explicit list: the set of globals a Node process happens to have varies by\n// version, and the answer must not depend on which one runs the migration.\nconst JS_GLOBALS = new Set([\n 'undefined', 'NaN', 'Infinity', 'globalThis', 'arguments',\n 'Object', 'Function', 'Array', 'Number', 'Boolean', 'String', 'Symbol', 'BigInt', 'Date', 'RegExp',\n 'Error', 'AggregateError', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',\n 'JSON', 'Math', 'Intl', 'Reflect', 'Proxy', 'Promise', 'Map', 'Set', 'WeakMap', 'WeakSet', 'WeakRef',\n 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Atomics', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray',\n 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array',\n 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent',\n 'console', 'fetch', 'URL', 'URLSearchParams', 'Headers', 'Request', 'Response', 'AbortController', 'AbortSignal',\n 'TextEncoder', 'TextDecoder', 'atob', 'btoa', 'structuredClone', 'queueMicrotask', 'performance',\n 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval',\n])\nconst IMPLICIT_MODULE_NAMES = new Set(['React', 'MintlifyComponents'])\n\nfunction parse(source: string): ts.SourceFile {\n return ts.createSourceFile('inline.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)\n}\n\nfunction bindingNames(name: ts.BindingName, into: Set<string>): void {\n if (ts.isIdentifier(name)) into.add(name.text)\n else for (const element of name.elements) if (ts.isBindingElement(element)) bindingNames(element.name, into)\n}\n\nfunction isFunctionLike(node: ts.Node): node is ts.FunctionLikeDeclaration {\n return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)\n || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node)\n || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)\n}\n\n/** Every name a function scope binds: parameters, and any declaration in its body outside nested functions. */\nfunction functionScope(fn: ts.FunctionLikeDeclaration): Set<string> {\n const scope = new Set<string>()\n if ((ts.isFunctionExpression(fn) || ts.isFunctionDeclaration(fn)) && fn.name) scope.add(fn.name.text)\n for (const parameter of fn.parameters) bindingNames(parameter.name, scope)\n function collect(node: ts.Node): void {\n if (ts.isVariableDeclaration(node)) bindingNames(node.name, scope)\n if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && node.name) scope.add(node.name.text)\n if (isFunctionLike(node)) return\n ts.forEachChild(node, collect)\n }\n if (fn.body) ts.forEachChild(fn.body, collect)\n if (fn.body && !ts.isBlock(fn.body)) collect(fn.body)\n return scope\n}\n\n/** Free (unbound) identifier references in one declaration, with how each is used. */\nfunction collectRefs(root: ts.Node): { refs: Array<Ref>; assigned: Array<string>; awaitOutsideAsync: boolean; dynamicImport: boolean } {\n const refs: Array<Ref> = []\n const assigned: Array<string> = []\n let awaitOutsideAsync = false\n let dynamicImport = false\n function bound(name: string, scopes: Array<Set<string>>): boolean {\n return scopes.some((scope) => scope.has(name))\n }\n function push(name: string, kind: RefKind, scopes: Array<Set<string>>): void {\n if (!bound(name, scopes)) refs.push({ name, kind })\n }\n function walkNode(node: ts.Node, scopes: Array<Set<string>>, inAsync: boolean): void {\n if (ts.isTypeNode(node)) return\n if (isFunctionLike(node)) {\n const nextScopes = [...scopes, functionScope(node)]\n const async = !!node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)\n for (const parameter of node.parameters) {\n if (!ts.isIdentifier(parameter.name)) walkNode(parameter.name, nextScopes, async)\n if (parameter.initializer) walkNode(parameter.initializer, nextScopes, async)\n }\n if (node.body) walkNode(node.body, nextScopes, async)\n return\n }\n if (ts.isAwaitExpression(node) && !inAsync) awaitOutsideAsync = true\n const target = ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment\n ? node.left\n : (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))\n && (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)\n ? node.operand\n : undefined\n if (target) {\n let base: ts.Node = target\n while (ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) base = base.expression\n if (ts.isIdentifier(base) && !bound(base.text, scopes)) assigned.push(base.text)\n }\n if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) dynamicImport = true\n if (ts.isIdentifier(node)) {\n const parent = node.parent\n const kind: RefKind = ts.isJsxExpression(parent) && parent.parent && ts.isJsxAttribute(parent.parent) ? 'prop' : 'other'\n push(node.text, kind, scopes)\n return\n }\n if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {\n let tag: ts.Node = node.tagName\n while (ts.isPropertyAccessExpression(tag)) tag = tag.expression\n if (ts.isIdentifier(tag)) {\n // A lowercase, non-member tag is an intrinsic element, not a reference.\n if (node.tagName !== tag || /^[A-Z]/.test(tag.text)) push(tag.text, node.tagName === tag ? 'tag' : 'member', scopes)\n }\n walkNode(node.attributes, scopes, inAsync)\n return\n }\n if (ts.isJsxClosingElement(node)) return\n if (ts.isJsxAttribute(node)) {\n if (node.initializer) walkNode(node.initializer, scopes, inAsync)\n return\n }\n if (ts.isPropertyAccessExpression(node)) {\n walkNode(node.expression, scopes, inAsync)\n return\n }\n if (ts.isQualifiedName(node)) return\n if (ts.isPropertyAssignment(node)) {\n if (ts.isComputedPropertyName(node.name)) walkNode(node.name.expression, scopes, inAsync)\n walkNode(node.initializer, scopes, inAsync)\n return\n }\n if (ts.isShorthandPropertyAssignment(node)) {\n push(node.name.text, 'other', scopes)\n if (node.objectAssignmentInitializer) walkNode(node.objectAssignmentInitializer, scopes, inAsync)\n return\n }\n if (ts.isBindingElement(node)) {\n if (node.propertyName && ts.isComputedPropertyName(node.propertyName)) walkNode(node.propertyName.expression, scopes, inAsync)\n if (node.initializer) walkNode(node.initializer, scopes, inAsync)\n if (!ts.isIdentifier(node.name)) walkNode(node.name, scopes, inAsync)\n return\n }\n if (ts.isVariableDeclaration(node)) {\n if (!ts.isIdentifier(node.name)) walkNode(node.name, scopes, inAsync)\n if (node.initializer) walkNode(node.initializer, scopes, inAsync)\n return\n }\n if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {\n node.members.forEach((member) => walkNode(member, scopes, inAsync))\n for (const clause of node.heritageClauses ?? []) for (const type of clause.types) walkNode(type.expression, scopes, inAsync)\n return\n }\n if (ts.isPropertyDeclaration(node)) {\n if (node.initializer) walkNode(node.initializer, scopes, inAsync)\n return\n }\n if (ts.isLabeledStatement(node)) {\n walkNode(node.statement, scopes, inAsync)\n return\n }\n if (ts.isBreakOrContinueStatement(node)) return\n ts.forEachChild(node, (child) => walkNode(child, scopes, inAsync))\n }\n // A top-level declaration's own name is module-level, so a self-reference\n // (recursion) is reported like any other page-level name.\n walkNode(root, [], false)\n return { refs, assigned, awaitOutsideAsync, dynamicImport }\n}\n\nfunction declaredNames(statement: ts.Statement): { names: Array<string>; componentLike: boolean; defaultExport: boolean } {\n const isDefault = !!(ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined)?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)\n || ts.isExportAssignment(statement)\n const names = new Set<string>()\n let componentLike = false\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n bindingNames(declaration.name, names)\n const initializer = declaration.initializer && unwrap(declaration.initializer)\n if (ts.isIdentifier(declaration.name) && /^[A-Z]/.test(declaration.name.text) && initializer\n && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer) || ts.isClassExpression(initializer))) {\n componentLike = true\n }\n }\n } else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {\n names.add(statement.name.text)\n componentLike = /^[A-Z]/.test(statement.name.text)\n }\n return { names: [...names], componentLike, defaultExport: isDefault }\n}\n\nfunction unwrap(expression: ts.Expression): ts.Expression {\n let current = expression\n while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current)) current = current.expression\n return current\n}\n\nfunction analyzeUnit(index: number, source: string, reactGlobals: ReadonlySet<string>): Unit {\n const sf = parse(source)\n const statement = sf.statements[0]\n const blockers: Array<string> = []\n if (!statement || sf.statements.length !== 1) {\n return { index, source, names: [], refs: [], assigned: [], hooks: false, clientOnly: false, componentLike: false, blockers: ['is not a single declaration'] }\n }\n const { names, componentLike, defaultExport } = declaredNames(statement)\n if (defaultExport) blockers.push('is a default export')\n const { refs, assigned, awaitOutsideAsync, dynamicImport } = collectRefs(statement)\n if (awaitOutsideAsync) blockers.push('uses await outside an async function')\n if (dynamicImport) blockers.push('uses a dynamic import()')\n // An async component is a Server Component; it has no client equivalent.\n const initializer = ts.isVariableStatement(statement) && statement.declarationList.declarations.length === 1\n ? statement.declarationList.declarations[0].initializer && unwrap(statement.declarationList.declarations[0].initializer)\n : statement\n if (initializer && isFunctionLike(initializer) && initializer.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) {\n blockers.push('is an async (server) component')\n }\n for (const { name } of refs) {\n if (SERVER_ONLY_IDENTIFIERS.has(name)) blockers.push(`uses the server-only \\`${name}\\``)\n }\n let handlers = false\n function scanHandlers(node: ts.Node): void {\n if (ts.isJsxAttribute(node) && ts.isIdentifier(node.name) && /^on[A-Z]/.test(node.name.text)) handlers = true\n ts.forEachChild(node, scanHandlers)\n }\n scanHandlers(statement)\n return {\n index,\n source,\n names,\n refs,\n assigned,\n hooks: refs.some(({ name }) => reactGlobals.has(name)) || /\\bReact\\.(?:use[A-Z]\\w*|createContext|forwardRef|memo)\\b/.test(source),\n clientOnly: handlers || refs.some(({ name }) => BROWSER_IDENTIFIERS.has(name)),\n componentLike,\n blockers: [...new Set(blockers)],\n }\n}\n\nfunction helperNames(source: string): Array<string> {\n const statement = parse(source).statements[0]\n return statement ? declaredNames(statement).names : []\n}\n\nfunction importLocals(statementText: string): Array<string> {\n const sf = parse(statementText)\n const locals: Array<string> = []\n for (const statement of sf.statements) {\n if (!ts.isImportDeclaration(statement) || !statement.importClause) continue\n const clause = statement.importClause\n if (clause.name) locals.push(clause.name.text)\n const named = clause.namedBindings\n if (named && ts.isNamespaceImport(named)) locals.push(named.name.text)\n if (named && ts.isNamedImports(named)) for (const element of named.elements) locals.push(element.name.text)\n }\n return locals\n}\n\n/** Free identifier references in an MDX expression string (`{...}` body or attribute value). */\nfunction expressionRefs(expression: string): Array<Ref> {\n const sf = parse(`const __expression = (${expression})`)\n const statement = sf.statements[0]\n return statement ? collectRefs(statement).refs : []\n}\n\nfunction bodyReferences(tree: InlineTree): { mdastTags: Set<string>; refs: Array<Ref> } {\n const mdastTags = new Set<string>()\n const refs: Array<Ref> = []\n function visit(node: InlineTree): void {\n if (node.type === 'mdxjsEsm') return\n if (['mdxJsxFlowElement', 'mdxJsxTextElement'].includes(node.type) && node.name) {\n const root = node.name.split('.')[0]\n if (node.name.includes('.')) refs.push({ name: root, kind: 'member' })\n else mdastTags.add(root)\n }\n if (['mdxFlowExpression', 'mdxTextExpression'].includes(node.type) && node.value) refs.push(...expressionRefs(node.value))\n for (const attribute of node.attributes ?? []) {\n const value = attribute.value\n if (attribute.type === 'mdxJsxExpressionAttribute' && typeof value === 'string') {\n refs.push(...expressionRefs(`{${value}}`))\n } else if (value && typeof value === 'object' && typeof value.value === 'string') {\n refs.push(...expressionRefs(value.value).map((ref, _index, all) => (\n all.length === 1 && value.value!.trim() === ref.name ? { name: ref.name, kind: 'prop' as const } : ref\n )))\n }\n }\n for (const child of node.children ?? []) visit(child)\n }\n visit(tree)\n return { mdastTags, refs }\n}\n\nexport function planInlineExtraction(input: {\n declarations: Array<InlineDeclaration>\n tree: InlineTree\n /** Import statements the client module may copy verbatim (already valid from the module's own directory). */\n copyableImports: Array<string>\n /** Page-level declarations synthesized by the migrator (static helpers), by source text. */\n helperDeclarations: Array<string>\n /** Local names of imports the migration removed, with their package. */\n unavailableImports: Map<string, string>\n reactGlobals: ReadonlySet<string>\n}): InlinePlan {\n const units = input.declarations.map((declaration, index) => analyzeUnit(index, declaration.source, input.reactGlobals))\n const owner = new Map<string, number>()\n for (const unit of units) for (const name of unit.names) owner.set(name, unit.index)\n // A page-level custom hook (`useTheme`) makes whatever calls it a hook user too.\n for (let changed = true; changed;) {\n changed = false\n for (const unit of units) {\n if (unit.hooks) continue\n if (unit.refs.some(({ name }) => /^use[A-Z]/.test(name) && units[owner.get(name) ?? -1]?.hooks)) { unit.hooks = true; changed = true }\n }\n }\n\n const importByLocal = new Map<string, string>()\n for (const statement of input.copyableImports) for (const local of importLocals(statement)) importByLocal.set(local, statement)\n const helperByName = new Map<string, string>()\n for (const helper of input.helperDeclarations) {\n for (const name of helperNames(helper)) helperByName.set(name, helper)\n }\n\n const body = bodyReferences(input.tree)\n\n const dependencies = (unit: Unit): Set<number> => {\n const found = new Set<number>()\n for (const { name } of unit.refs) {\n const target = owner.get(name)\n if (target !== undefined && target !== unit.index) found.add(target)\n }\n return found\n }\n const closureOf = (rootIndex: number): Set<number> => {\n const seen = new Set<number>([rootIndex])\n const queue = [rootIndex]\n while (queue.length) for (const next of dependencies(units[queue.pop()!])) {\n if (!seen.has(next)) { seen.add(next); queue.push(next) }\n }\n return seen\n }\n\n /** Why one declaration can never live in the client module, whatever the page does. */\n const intrinsicBlocker = (unit: Unit): string | undefined => {\n if (unit.blockers.length > 0) return `\\`${unit.names[0] ?? 'a dependency'}\\` ${unit.blockers[0]}`\n for (const { name, kind } of unit.refs) {\n if (owner.has(name) || importByLocal.has(name) || helperByName.has(name)) continue\n if (input.unavailableImports.has(name)) {\n return `\\`${unit.names[0]}\\` uses \\`${name}\\`, imported from ${input.unavailableImports.get(name)}, which is not available in the migrated project`\n }\n if (input.reactGlobals.has(name) || IMPLICIT_MODULE_NAMES.has(name) || JS_GLOBALS.has(name) || BROWSER_IDENTIFIERS.has(name)) continue\n if ((kind === 'tag' || kind === 'member') && isThallyBuiltinComponent(name)) continue\n return `\\`${unit.names[0]}\\` uses \\`${name}\\`, which is not declared or imported on the page`\n }\n return undefined\n }\n\n const roots = units\n .filter((unit) => unit.hooks && unit.names.some((name) => /^[A-Z]/.test(name)))\n .map((unit) => unit.index)\n const blocked: Array<{ name: string; reason: string }> = []\n const active = new Set(roots)\n\n const block = (rootIndex: number, reason: string): void => {\n active.delete(rootIndex)\n blocked.push({ name: units[rootIndex].names.find((name) => /^[A-Z]/.test(name)) ?? units[rootIndex].names[0], reason })\n }\n for (const rootIndex of roots) {\n for (const member of closureOf(rootIndex)) {\n const reason = intrinsicBlocker(units[member])\n if (reason) { block(rootIndex, reason); break }\n }\n }\n\n for (let round = 0; round <= units.length + 1; round += 1) {\n const inModule = new Set<number>()\n for (const rootIndex of active) for (const member of closureOf(rootIndex)) inModule.add(member)\n\n // A declaration that cannot render on the server, or that calls one that\n // cannot, must be moved; everything else the page still uses stays too.\n const clientSide = new Set<number>()\n for (const index of inModule) if (units[index].hooks || units[index].clientOnly) clientSide.add(index)\n for (let changed = true; changed;) {\n changed = false\n for (const index of inModule) {\n if (clientSide.has(index)) continue\n const unit = units[index]\n const callsClient = unit.refs.some(({ name, kind }) => {\n const target = owner.get(name)\n return target !== undefined && clientSide.has(target) && kind !== 'tag' && kind !== 'prop'\n })\n if (callsClient) { clientSide.add(index); changed = true }\n }\n }\n for (const rootIndex of active) clientSide.add(rootIndex)\n\n const nonModuleRefs: Array<Ref> = [...body.refs]\n for (const unit of units) if (!inModule.has(unit.index)) nonModuleRefs.push(...unit.refs)\n const referencedByPage = (index: number): boolean => units[index].names.some((name) => (\n body.mdastTags.has(name) || nonModuleRefs.some((ref) => ref.name === name)\n ))\n\n const kept = new Set<number>()\n for (const index of inModule) {\n if (clientSide.has(index)) continue\n if (!units[index].componentLike || referencedByPage(index)) kept.add(index)\n }\n for (let changed = true; changed;) {\n changed = false\n for (const index of kept) for (const dependency of dependencies(units[index])) {\n if (inModule.has(dependency) && !clientSide.has(dependency) && !kept.has(dependency)) { kept.add(dependency); changed = true }\n }\n }\n const moved = new Set<number>([...inModule].filter((index) => !kept.has(index)))\n\n // Page code that stays behind may only render a moved declaration, or hand\n // it to a client component; calling or reading it would run it on the server.\n const pageRefs: Array<Ref> = [...nonModuleRefs]\n for (const index of kept) pageRefs.push(...units[index].refs)\n const violation = [...moved].find((index) => clientSide.has(index) && units[index].names.some((name) => (\n pageRefs.some((ref) => ref.name === name && ref.kind !== 'tag' && ref.kind !== 'prop')\n )))\n if (violation !== undefined) {\n const names = units[violation].names\n const readsIt = (ref: Ref): boolean => names.includes(ref.name) && ref.kind !== 'tag' && ref.kind !== 'prop'\n // A component that only reads the moved value (a context provider next\n // to its consumer) can travel with it, so the value keeps one identity.\n const readers = units.filter((unit) => !moved.has(unit.index) && unit.refs.some(readsIt))\n const promotable = !body.refs.some(readsIt) && readers.every((unit) => (\n unit.componentLike && !active.has(unit.index)\n && [...closureOf(unit.index)].every((member) => !intrinsicBlocker(units[member]))\n ))\n if (promotable && readers.length > 0) {\n for (const unit of readers) active.add(unit.index)\n continue\n }\n for (const rootIndex of [...active]) {\n if (closureOf(rootIndex).has(violation)) {\n block(rootIndex, `\\`${names[0]}\\` is also read or called by page code that stays on the server`)\n }\n }\n continue\n }\n\n // A copy of mutable state would diverge: the page and the client module\n // would each count on their own. Refuse when page code reaches it.\n const reachable = new Set<number>([...kept].filter(referencedByPage))\n for (let changed = true; changed;) {\n changed = false\n for (const index of [...reachable]) for (const dependency of dependencies(units[index])) {\n if (kept.has(dependency) && !reachable.has(dependency)) { reachable.add(dependency); changed = true }\n }\n }\n const mutated = [...reachable].find((index) => units.some((unit) => unit.assigned.some((name) => units[index].names.includes(name))))\n if (mutated !== undefined) {\n for (const rootIndex of [...active]) {\n if (closureOf(rootIndex).has(mutated)) {\n block(rootIndex, `\\`${units[mutated].names[0]}\\` is mutable state that page code also uses, so a copy in the client module would diverge`)\n }\n }\n continue\n }\n\n const movedNames = [...moved].flatMap((index) => units[index].names)\n const registryNames = movedNames.filter((name) => body.mdastTags.has(name))\n const importNames = movedNames.filter((name) => pageRefs.some((ref) => ref.name === name))\n const moduleMembers = [...inModule].sort((a, b) => a - b)\n const moduleNames = new Set<string>(moduleMembers.flatMap((index) => units[index].names))\n const usedImports: Array<string> = []\n const usedHelpers: Array<string> = []\n for (const index of moduleMembers) {\n for (const { name } of units[index].refs) {\n const statement = importByLocal.get(name)\n if (statement && !usedImports.includes(statement)) usedImports.push(statement)\n const helper = helperByName.get(name)\n if (helper && !usedHelpers.includes(helper)) usedHelpers.push(helper)\n }\n }\n for (const statement of usedImports) for (const local of importLocals(statement)) moduleNames.add(local)\n for (const helper of usedHelpers) for (const name of helperNames(helper)) moduleNames.add(name)\n const pageReferences = new Set<string>(pageRefs.map((ref) => ref.name))\n for (const tag of body.mdastTags) pageReferences.add(tag)\n return {\n blocked,\n moved: [...moved].sort((a, b) => a - b),\n copied: [...kept].sort((a, b) => a - b),\n movedNames,\n moduleImports: usedImports,\n moduleHelpers: usedHelpers,\n registryNames: [...new Set(registryNames)],\n pageImportNames: [...new Set(importNames)],\n moduleNames,\n pageReferences,\n }\n }\n return { blocked, moved: [], copied: [], movedNames: [], moduleImports: [], moduleHelpers: [], registryNames: [], pageImportNames: [], moduleNames: new Set(), pageReferences: new Set() }\n}\n\n/** JSX tag names (capitalized, unbound) a module's source uses, for built-in lookup. */\nexport function unboundTags(moduleSource: string, boundNames: ReadonlySet<string>): Array<string> {\n const sf = parse(moduleSource)\n const tags = new Set<string>()\n for (const statement of sf.statements) {\n if (ts.isImportDeclaration(statement)) continue\n for (const ref of collectRefs(statement).refs) {\n if ((ref.kind === 'tag' || ref.kind === 'member') && /^[A-Z]/.test(ref.name) && !boundNames.has(ref.name)) tags.add(ref.name)\n }\n }\n return [...tags].sort()\n}\n","/**\n * Static Docusaurus repository projection. Sidebar modules are attacker-owned\n * source files, so this adapter reads only JSON5-compatible object literals and\n * never imports, evaluates, or executes JavaScript/TypeScript configuration.\n */\n\nimport { existsSync, lstatSync, readFileSync } from 'node:fs'\nimport { extname, posix } from 'node:path'\n\nimport JSON5 from 'json5'\nimport { parse as parseYaml } from 'yaml'\n\nimport type { MarkdownPageIdentity } from './mdx.js'\nimport { isRedirectPathSafe } from './navigation.js'\nimport { pageIdFromReference, resolveWithin, slugifySegment } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_CONFIG_BYTES = 20_000_000\nconst CATEGORY_FILENAMES = ['_category_.json', '_category_.yml', '_category_.yaml']\nconst SIDEBAR_FILENAMES = [\n 'sidebars.json',\n 'sidebars.js',\n 'sidebars.cjs',\n 'sidebars.mjs',\n 'sidebars.ts',\n]\n\nexport interface DocusaurusPageDescriptor {\n sourcePath: string\n docId: string\n navigationId: string\n sidebarPosition?: number\n title: string\n}\n\nexport interface DocusaurusSidebars {\n config: Record<string, unknown>\n sourcePath: string\n}\n\nexport interface DocusaurusNavigationResult {\n docsConfig: MigrationDocsConfig\n generatedPages: Array<MigrationPage>\n referencedNavigationIds: Set<string>\n warnings: Array<MigrationWarning>\n}\n\ninterface ProjectionContext {\n contentRoot: string\n descriptors: Array<DocusaurusPageDescriptor>\n descriptorByDocId: Map<string, DocusaurusPageDescriptor>\n generatedPages: Array<MigrationPage>\n generatedIds: Set<string>\n referencedNavigationIds: Set<string>\n sourceUrl: string\n routePrefix: string\n sidebarSource: string\n warnings: Array<MigrationWarning>\n}\n\ninterface CategoryMetadata {\n label?: string\n position?: number\n link?: unknown\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction stripNumberPrefix(value: string): string {\n return value.replace(/^\\d+[-_]+/, '')\n}\n\nfunction normalizeDocId(value: string): string {\n return value\n .split(/[?#]/, 1)[0]\n .replace(/\\\\/g, '/')\n .replace(/^\\/+/, '')\n .replace(/\\.(?:mdx?)$/i, '')\n .split('/')\n .filter(Boolean)\n .map(stripNumberPrefix)\n .join('/')\n}\n\nfunction docusaurusSlugifySegment(value: string): string {\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // Malformed escapes remain literal input and are normalized safely below.\n }\n return decoded\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/(^-|-$)/g, '')\n}\n\nfunction docusaurusRouteId(value: string): string | null {\n const segments = normalizeDocId(value)\n .split('/')\n .map(docusaurusSlugifySegment)\n .filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\nfunction defaultDocusaurusRouteId(value: string): string | null {\n const segments = normalizeDocId(value).split('/').filter(Boolean)\n if (/^(?:index|readme)$/i.test(segments.at(-1) ?? '')) segments.pop()\n const normalized = segments.map(docusaurusSlugifySegment).filter(Boolean)\n return normalized.join('/') || 'introduction'\n}\n\nfunction storageIdForRoute(routeId: string): string {\n return /(?:^|\\/)(?:index|readme)$/i.test(routeId) ? `${routeId}/index` : routeId\n}\n\nfunction titleCase(value: string): string {\n return stripNumberPrefix(value)\n .replace(/sidebar$/i, '')\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\nfunction routeFromSlug(slug: string, fallback: string, sourceDirectory?: string): string | null {\n if (slug === '/') return 'introduction'\n if (slug.startsWith('/')) return docusaurusRouteId(slug)\n const fallbackDirectory = sourceDirectory ?? (fallback === 'introduction' ? '' : posix.dirname(fallback))\n const resolved = posix.normalize(posix.join(fallbackDirectory, slug))\n if (resolved === '..' || resolved.startsWith('../')) return null\n return docusaurusRouteId(resolved)\n}\n\n/** Resolve Docusaurus `id`, `slug`, and numeric-prefix semantics once. */\nexport function resolveDocusaurusPageIdentity(\n sourcePath: string,\n frontmatter: Record<string, unknown>,\n fallback: MarkdownPageIdentity,\n): { identity: MarkdownPageIdentity; descriptor: Omit<DocusaurusPageDescriptor, 'title'> } {\n const sourceDocId = normalizeDocId(sourcePath)\n const sourceDirectory = posix.dirname(sourceDocId)\n const configuredId = typeof frontmatter.id === 'string' && frontmatter.id.trim()\n ? stripNumberPrefix(frontmatter.id.trim())\n : null\n const docId = configuredId\n ? normalizeDocId(sourceDirectory === '.' ? configuredId : posix.join(sourceDirectory, configuredId))\n : sourceDocId\n // Docusaurus collapses a source `index` document by default, but an explicit\n // `slug: index` remains a literal route. Keep those two cases distinct.\n const defaultNavigationId = defaultDocusaurusRouteId(docId) ?? fallback.navigationId\n const configuredSlug = typeof frontmatter.slug === 'string' ? frontmatter.slug.trim() : ''\n const navigationId = configuredSlug\n ? routeFromSlug(\n configuredSlug,\n defaultNavigationId,\n sourceDirectory === '.' ? '' : sourceDirectory,\n ) ?? defaultNavigationId\n : defaultNavigationId\n const position = typeof frontmatter.sidebar_position === 'number'\n && Number.isFinite(frontmatter.sidebar_position)\n ? frontmatter.sidebar_position\n : undefined\n return {\n identity: { id: storageIdForRoute(navigationId), navigationId },\n descriptor: {\n sourcePath: sourcePath.replace(/\\\\/g, '/'),\n docId,\n navigationId,\n ...(position === undefined ? {} : { sidebarPosition: position }),\n },\n }\n}\n\nfunction sourceReferenceKey(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/^\\/+/, '').replace(/\\.(?:mdx?)$/i, '').replace(/\\/$/, '')\n}\n\ninterface SourceHeading {\n index: number\n level: number\n id: string | null\n}\n\nfunction sourceHeadings(body: string): Array<SourceHeading> {\n const headings: Array<SourceHeading> = []\n const lines = body.split('\\n')\n let fence: string | null = null\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]\n const marker = line.match(/^ {0,3}(`{3,}|~{3,})/)\n if (marker) {\n if (!fence) fence = marker[1]\n else if (marker[1][0] === fence[0] && marker[1].length >= fence.length\n && /^\\s*$/.test(line.slice(marker[0].length))) fence = null\n continue\n }\n if (fence) continue\n const heading = line.match(/^ {0,3}(#{2,6})\\s+(.+?)\\s*#*\\s*$/)\n if (!heading) continue\n const preceding = lines[index - 1]?.match(/^<a id=\"([\\p{L}\\p{N}_.:$-]{1,120})\"><\\/a>$/u)\n // The runtime extracts rendered heading text from MDX elements. Only\n // plain text can be mapped reliably without evaluating authored MDX.\n const plainText = !/[<>{}\\[\\]`*_]/.test(heading[2])\n const generatedId = plainText\n ? heading[2].normalize('NFC').toLowerCase()\n .replace(/[^\\p{L}\\p{M}\\p{N}]+/gu, '-').replace(/(^-|-$)/g, '')\n : null\n headings.push({ index, level: heading[1].length, id: preceding?.[1] ?? generatedId })\n }\n return headings\n}\n\n/**\n * Preserve original-language fragments in translated Docusaurus pages when\n * their heading outlines are identical. An inserted alias never replaces an\n * explicit translated ID, and ambiguous or edited outlines are left alone.\n */\nexport function addDocusaurusTranslatedHeadingAliases(pages: Array<MigrationPage>): void {\n const byRoute = new Map(pages.map((page) => [page.navigationId, page]))\n for (const page of pages) {\n const locale = page.source.match(/(?:^|[/#])i18n\\/([A-Za-z]{2,8}(?:-[A-Za-z0-9]{2,8})*)\\/docusaurus-plugin-content-docs\\//)?.[1]\n if (!locale) continue\n const originalRoute = page.navigationId === locale ? 'introduction'\n : page.navigationId.startsWith(`${locale}/`) ? page.navigationId.slice(locale.length + 1) : null\n if (!originalRoute) continue\n const original = byRoute.get(originalRoute)\n if (!original) continue\n const originalHeadings = sourceHeadings(original.body)\n const translatedHeadings = sourceHeadings(page.body)\n if (!originalHeadings.length || originalHeadings.length !== translatedHeadings.length\n || originalHeadings.some((heading, index) => heading.level !== translatedHeadings[index].level)) continue\n\n const occupied = new Set(translatedHeadings.map((heading) => heading.id).filter((id): id is string => !!id))\n for (const match of page.body.matchAll(/<a\\s+id=\"([^\"]+)\"/g)) occupied.add(match[1])\n const originalIdCounts = new Map<string, number>()\n for (const heading of originalHeadings) {\n if (heading.id) originalIdCounts.set(heading.id, (originalIdCounts.get(heading.id) ?? 0) + 1)\n }\n const aliases = new Map<number, string>()\n for (let index = 0; index < originalHeadings.length; index++) {\n const id = originalHeadings[index].id\n if (!id || occupied.has(id) || originalIdCounts.get(id) !== 1) continue\n aliases.set(translatedHeadings[index].index, id)\n occupied.add(id)\n }\n if (aliases.size) page.body = page.body.split('\\n').flatMap((line, index) => {\n const alias = aliases.get(index)\n return alias ? [`<a id=\"${alias}\"></a>`, line] : [line]\n }).join('\\n')\n }\n}\n\n/** Fill Docusaurus category card lists from the sidebar tree they summarize. */\nexport function expandDocusaurusDocCardLists(\n pages: Array<MigrationPage>,\n config: MigrationDocsConfig,\n sourceRoutes: ReadonlySet<string>,\n): void {\n const pageByRoute = new Map(pages.map((page) => [page.navigationId, page]))\n const containsRoute = (items: Array<string | MigrationNavigationGroup>, route: string): boolean =>\n items.some((item) => typeof item === 'string'\n ? item === route\n : containsRoute(item.pages, route))\n const findGroup = (items: Array<string | MigrationNavigationGroup>, route: string): MigrationNavigationGroup | undefined => {\n for (const item of items) {\n if (typeof item === 'string' || !containsRoute(item.pages, route)) continue\n return findGroup(item.pages, route) ?? item\n }\n return undefined\n }\n const firstRoute = (items: Array<string | MigrationNavigationGroup>): string | undefined => {\n for (const item of items) {\n if (typeof item === 'string') return item\n const candidate = firstRoute(item.pages)\n if (candidate) return candidate\n }\n return undefined\n }\n for (const page of pages) {\n if (!sourceRoutes.has(page.navigationId)) continue\n const group = config.tabs.map((tab) => findGroup([\n ...(tab.pages ?? []),\n ...(tab.groups ?? []),\n ], page.navigationId)).find(Boolean)\n if (!group) {\n page.body = page.body.replace(/<div data-thally-doc-card-list=\"\"\\s*\\/>/g, '')\n continue\n }\n const cards = group.pages.flatMap((item) => {\n if (typeof item === 'string') {\n if (item === page.navigationId) return []\n const target = pageByRoute.get(item)\n return [{ title: target?.title ?? item.split('/').at(-1) ?? item, route: item }]\n }\n const slug = slugifySegment(item.group)\n const routes = [...item.pages].flatMap((child) => typeof child === 'string' ? [child] : [])\n const route = routes.find((candidate) => candidate === slug || candidate.endsWith(`/${slug}`))\n ?? firstRoute(item.pages)\n return route ? [{ title: item.group, route }] : []\n })\n const markup = cards.length\n ? `<CardGroup>\\n${cards.map(({ title, route }) => ` <Card title={${JSON.stringify(title)}} href={${JSON.stringify(`/${route === 'introduction' ? '' : route}`)}} />`).join('\\n')}\\n</CardGroup>`\n : ''\n page.body = page.body.replace(/<div data-thally-doc-card-list=\"\"\\s*\\/>/g, markup)\n if (markup && !page.body.includes(markup)) page.body = [page.body.trim(), markup].filter(Boolean).join('\\n\\n')\n }\n}\n\n/**\n * Rewrite Docusaurus file/doc-id links after every final slug is known. This is\n * deliberately line based so examples inside fenced code remain byte-for-byte\n * source content. A link whose `#fragment` uses a case-preserved heading id\n * (live Docusaurus keeps case intact; Thally always lowercases its auto-slug)\n * is left as-is here — `preserveDocusaurusLinkedAnchors` (repository.ts)\n * repairs those afterward by adding an explicit anchor matching the literal\n * fragment, which also covers repeated table-field ids that this\n * path-only resolver has no visibility into.\n */\nexport function rewriteDocusaurusLinks(\n body: string,\n current: DocusaurusPageDescriptor,\n descriptors: Array<DocusaurusPageDescriptor>,\n options: {\n sourceOrigin?: string\n onExternalLink?: (target: string) => void\n /** Copy destinations, without a leading slash, after asset budgeting. */\n assetPaths?: ReadonlySet<string>\n } = {},\n): string {\n const routes = new Map<string, string>()\n for (const descriptor of descriptors) {\n const sourceKey = sourceReferenceKey(descriptor.sourcePath)\n routes.set(sourceKey, descriptor.navigationId)\n routes.set(sourceReferenceKey(descriptor.docId), descriptor.navigationId)\n routes.set(sourceReferenceKey(descriptor.navigationId), descriptor.navigationId)\n const sourceRoute = pageIdFromReference(sourceKey)\n if (sourceRoute) routes.set(sourceRoute, descriptor.navigationId)\n }\n const currentDirectory = posix.dirname(sourceReferenceKey(current.sourcePath))\n\n function copiedAssetTarget(target: string): string | null {\n if (!target.startsWith('/') || target.startsWith('//') || target.includes('\\\\')) return null\n const suffixIndex = target.search(/[?#]/)\n const path = suffixIndex >= 0 ? target.slice(0, suffixIndex) : target\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n if (path.startsWith('/docs/') && options.assetPaths?.has(path.slice('/docs/'.length))) {\n return `/${path.slice('/docs/'.length)}${suffix}`\n }\n return options.assetPaths?.has(path.slice(1)) ? target : null\n }\n\n function rewriteTarget(target: string): string {\n if (!target || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(target)) return target\n if (target.startsWith('#')) return target\n const suffixIndex = target.search(/[?#]/)\n const path = suffixIndex >= 0 ? target.slice(0, suffixIndex) : target\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n // Docusaurus sites often publish `static/img/foo` as `/img/foo` while\n // authors refer to it as `/docs/img/foo`. Strip the docs mount only after\n // the copy pass proves the resulting asset exists.\n const copiedAsset = copiedAssetTarget(target)\n if (copiedAsset) return copiedAsset\n const candidates = path.startsWith('/')\n ? [\n sourceReferenceKey(path),\n sourceReferenceKey(path).replace(/^docs\\//, ''),\n sourceReferenceKey(path).replace(/^docs\\/(?:next|current|latest)\\//, ''),\n ]\n : [\n sourceReferenceKey(posix.normalize(posix.join(currentDirectory, path))),\n sourceReferenceKey(path),\n ]\n const route = candidates.map((candidate) => routes.get(candidate)).find(Boolean)\n if (!route) {\n if (path.startsWith('/') && path !== '/' && options.sourceOrigin) {\n options.onExternalLink?.(target)\n return new URL(target, options.sourceOrigin).toString()\n }\n return target\n }\n return `${route === 'introduction' ? '/' : `/${route}`}${suffix}`\n }\n\n let codeFence: string | null = null\n return body.split('\\n').map((line) => {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (fence) {\n if (!codeFence) codeFence = fence[1]\n else if (fence[1][0] === codeFence[0] && fence[1].length >= codeFence.length\n && /^\\s*$/.test(line.slice(fence[0].length))) codeFence = null\n return line\n }\n if (codeFence) return line\n return line\n .replace(/(\\]\\()([^\\s)]+)(?=[\\s)]|$)/g, (_match, prefix: string, target: string) => `${prefix}${rewriteTarget(target)}`)\n .replace(/(\\bhref=\")([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${rewriteTarget(target)}${suffix}`)\n .replace(/(\\bsrc=\")([^\"]+)(\")/g, (_match, prefix: string, target: string, suffix: string) => `${prefix}${copiedAssetTarget(target) ?? target}${suffix}`)\n // Markdown reference links carry their destination in a later\n // definition line. Docusaurus resolves `[label]` through that line, so\n // rewriting only inline links leaves an apparently working link in the\n // content whose click still goes to `/page.md` and 404s on Thally.\n .replace(/^(\\s{0,3}\\[[^\\]]+\\]:\\s*)(<[^>]+>|\\S+)/, (_match, prefix: string, destination: string) => {\n const bracketed = destination.startsWith('<') && destination.endsWith('>')\n const target = bracketed ? destination.slice(1, -1) : destination\n const rewritten = rewriteTarget(target)\n return `${prefix}${bracketed ? `<${rewritten}>` : rewritten}`\n })\n }).join('\\n')\n}\n\n/** Read a static Docusaurus site origin for links outside imported docs. */\nexport function readDocusaurusSiteOrigin(repositoryRoot: string): string | undefined {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return undefined\n const address = readBoundedText(configPath).match(/\\burl['\"]?\\s*:\\s*(['\"])(https?:\\/\\/[^'\"]+)\\1/)?.[2]\n if (!address) return undefined\n try {\n return new URL(address).origin\n } catch {\n return undefined\n }\n}\n\nfunction readBoundedText(path: string): string {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('The Docusaurus sidebar config is larger than 20 MB and could not be imported.')\n }\n return readFileSync(path, 'utf8')\n}\n\nfunction matchingObjectLiteral(source: string, start: number): string | null {\n let depth = 0\n let quote: string | null = null\n let isEscaped = false\n let lineComment = false\n let blockComment = false\n let objectStart = -1\n\n for (let index = start; index < source.length; index++) {\n const char = source[index]\n const next = source[index + 1]\n if (lineComment) {\n if (char === '\\n') lineComment = false\n continue\n }\n if (blockComment) {\n if (char === '*' && next === '/') {\n blockComment = false\n index++\n }\n continue\n }\n if (quote) {\n if (isEscaped) isEscaped = false\n else if (char === '\\\\') isEscaped = true\n else if (char === quote) quote = null\n continue\n }\n if (char === '/' && next === '/') {\n lineComment = true\n index++\n continue\n }\n if (char === '/' && next === '*') {\n blockComment = true\n index++\n continue\n }\n if (char === '\"' || char === \"'\" || char === '`') {\n quote = char\n continue\n }\n if (char === '{') {\n if (objectStart < 0) objectStart = index\n depth++\n } else if (char === '}' && objectStart >= 0) {\n depth--\n if (depth === 0) return source.slice(objectStart, index + 1)\n } else if (objectStart < 0 && !/\\s/.test(char)) {\n return null\n }\n }\n return null\n}\n\nfunction parseStaticSidebarModule(source: string): Record<string, unknown> {\n const bindings = new Map<string, Record<string, unknown>>()\n const normalizedSource = replaceExternalFbContent(source)\n const parseFailures: Array<string> = []\n const assignmentPatterns = [\n /\\bmodule\\.exports\\s*=\\s*/g,\n /\\bexport\\s+default\\s*/g,\n /\\b(?:const|let|var)\\s+[A-Za-z_$][\\w$]*(?:\\s*:\\s*[^=;]+)?\\s*=\\s*/g,\n ]\n const candidates = assignmentPatterns.flatMap((pattern) => [...normalizedSource.matchAll(pattern)])\n .sort((left, right) => (left.index ?? 0) - (right.index ?? 0))\n\n for (const candidate of candidates) {\n const literal = matchingObjectLiteral(normalizedSource, (candidate.index ?? 0) + candidate[0].length)\n if (!literal) continue\n try {\n const substituted = [...bindings].reduce(\n (value, [name, binding]) => value.replace(\n new RegExp(`(:\\\\s*)${name}\\\\b`, 'g'),\n (_match, prefix: string) => `${prefix}${JSON.stringify(binding)}`,\n ),\n literal,\n )\n const parsed = JSON5.parse(substituted) as unknown\n const object = objectValue(parsed)\n if (!object) continue\n const bindingName = candidate[0].match(/\\b(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)/)?.[1]\n if (bindingName) {\n bindings.set(bindingName, object)\n continue\n }\n return object\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n const line = Number(message.match(/at (\\d+):/)?.[1] ?? 0)\n const context = line > 0 ? literal.split('\\n').slice(Math.max(0, line - 2), line + 1).join(' ') : ''\n parseFailures.push(`${message}${context ? ` near ${context}` : ''}`)\n // Try the next assignment. Expressions and function calls are rejected.\n }\n }\n const exportedBinding = normalizedSource.match(/\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\b/)?.[1]\n ?? normalizedSource.match(/\\bmodule\\.exports\\s*=\\s*([A-Za-z_$][\\w$]*)\\b/)?.[1]\n if (exportedBinding && bindings.has(exportedBinding)) return bindings.get(exportedBinding)!\n throw new Error(`Sidebar config is executable or outside the supported data-only syntax.${parseFailures[0] ? ` ${parseFailures[0]}` : ''}`)\n}\n\nfunction replaceExternalFbContent(source: string): string {\n const marker = '...fbContent('\n let result = source\n let searchFrom = 0\n while (true) {\n const start = result.indexOf(marker, searchFrom)\n if (start < 0) return result.replace(/,\\s*,/g, ',')\n const objectStart = result.indexOf('{', start + marker.length)\n if (objectStart < 0) return result\n const objectLiteral = matchingObjectLiteral(result, objectStart)\n if (!objectLiteral) {\n searchFrom = start + marker.length\n continue\n }\n const objectEnd = objectStart + objectLiteral.length\n const close = result.indexOf(')', objectEnd)\n if (close < 0) return result\n const externalMatch = /\\bexternal\\s*:\\s*/g.exec(objectLiteral)\n let replacement = ''\n if (externalMatch) {\n const arrayStart = objectLiteral.indexOf('[', externalMatch.index + externalMatch[0].length)\n if (arrayStart >= 0) {\n const array = matchingArrayLiteral(objectLiteral, arrayStart)\n if (array) replacement = array.slice(1, -1)\n }\n }\n let replaceEnd = close + 1\n if (!replacement) {\n const trailingComma = result.slice(replaceEnd).match(/^\\s*,/)\n if (trailingComma) replaceEnd += trailingComma[0].length\n }\n result = `${result.slice(0, start)}${replacement}${result.slice(replaceEnd)}`\n searchFrom = start + replacement.length\n }\n}\n\nfunction matchingArrayLiteral(source: string, start: number): string | null {\n let depth = 0\n let quote = ''\n let isEscaped = false\n for (let index = start; index < source.length; index++) {\n const character = source[index]\n if (quote) {\n if (isEscaped) isEscaped = false\n else if (character === '\\\\') isEscaped = true\n else if (character === quote) quote = ''\n continue\n }\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character\n continue\n }\n if (character === '[') depth++\n if (character === ']' && --depth === 0) return source.slice(start, index + 1)\n }\n return null\n}\n\nfunction configuredSidebarPath(repositoryRoot: string): string | null {\n for (const filename of ['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']) {\n const path = resolveWithin(repositoryRoot, filename)\n if (!existsSync(path)) continue\n const source = readBoundedText(path)\n // A site can register other docs plugins before the classic preset. Their\n // sidebarPath belongs to a different content root (Docusaurus registers\n // its community plugin before the main docs preset, for example).\n for (const docs of source.matchAll(/\\bdocs\\s*:\\s*/g)) {\n const object = matchingObjectLiteral(source, (docs.index ?? 0) + docs[0].length)\n const candidate = object && staticStringField(object, 'sidebarPath')?.replace(/^\\.\\//, '')\n if (candidate) {\n const resolved = resolveWithin(repositoryRoot, candidate)\n if (existsSync(resolved) && lstatSync(resolved).isFile()) return candidate\n }\n }\n const match = source.match(/\\bsidebarPath\\s*:\\s*(?:require\\.resolve\\(\\s*)?(['\"])([^'\"]+)\\1/)\n if (!match) continue\n const candidate = match[2].replace(/^\\.\\//, '')\n const resolved = resolveWithin(repositoryRoot, candidate)\n if (existsSync(resolved) && lstatSync(resolved).isFile()) return candidate\n }\n return null\n}\n\n/** Read the configured/default sidebar without running the source module. */\nexport function readDocusaurusSidebars(repositoryRoot: string, versionedSidebarPath?: string): DocusaurusSidebars | null {\n // Archived versions carry their own sidebar file. Resolve it within the\n // project and parse it as data; never load source-controlled code.\n const configured = versionedSidebarPath ?? configuredSidebarPath(repositoryRoot)\n const sourcePath = [configured, ...(versionedSidebarPath ? [] : SIDEBAR_FILENAMES)]\n .filter((value): value is string => Boolean(value))\n .find((candidate) => {\n const path = resolveWithin(repositoryRoot, candidate)\n return existsSync(path) && lstatSync(path).isFile()\n })\n if (!sourcePath) return null\n const absolutePath = resolveWithin(repositoryRoot, sourcePath)\n const source = readBoundedText(absolutePath)\n const parsed = extname(sourcePath).toLowerCase() === '.json'\n ? objectValue(JSON5.parse(source))\n : parseStaticSidebarModule(source)\n if (!parsed) throw new Error('Docusaurus sidebar config must export an object.')\n return { config: parsed, sourcePath }\n}\n\nfunction namedExportObjectLiteralText(source: string, name: string): string | null {\n const normalizedSource = replaceExternalFbContent(source)\n const match = new RegExp(`\\\\bexport\\\\s+(?:const|let|var)\\\\s+${name}\\\\b(?:\\\\s*:\\\\s*[^=;]+)?\\\\s*=\\\\s*`).exec(normalizedSource)\n if (!match) return null\n return matchingObjectLiteral(normalizedSource, match.index + match[0].length)\n}\n\n/**\n * Pluck just the `redirects: [...]` array out of a plugin options object's\n * literal text, rather than `JSON5.parse`-ing the whole object — the Oasis\n * shape (a real, reproduced example) has a sibling `createRedirects(...) {\n * ... }` method in the same object literal, which is not valid JSON5 and\n * would otherwise fail the whole object and lose the `redirects` array too.\n */\nfunction redirectEntriesFromObjectLiteralText(objectLiteral: string): Array<{ source: string; destination: string }> {\n const match = /\\bredirects\\s*:\\s*/.exec(objectLiteral)\n if (!match) return []\n const arrayStart = objectLiteral.indexOf('[', match.index + match[0].length)\n if (arrayStart < 0) return []\n const arrayLiteral = matchingArrayLiteral(objectLiteral, arrayStart)\n if (!arrayLiteral) return []\n let parsed: unknown\n try {\n parsed = JSON5.parse(arrayLiteral)\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n const entries: Array<{ source: string; destination: string }> = []\n for (const raw of parsed) {\n const entry = objectValue(raw)\n if (!entry || typeof entry.to !== 'string') continue\n const froms = Array.isArray(entry.from) ? entry.from : [entry.from]\n for (const from of froms) {\n if (typeof from !== 'string') continue\n if (!isRedirectPathSafe(from, entry.to)) continue\n entries.push({ source: from, destination: entry.to })\n }\n }\n return entries\n}\n\n/**\n * Parse a `@docusaurus/plugin-client-redirects` `Options` object: either an\n * object literal written inline in the plugin's config entry, or (Oasis's\n * shape) a named export in a separate module the config imports, e.g.\n * `redirects.ts` exporting `redirectsOptions`. Only a literal `redirects:\n * [{ from, to }]` array is understood — `from` may be a single path or an\n * array of paths, both valid per the plugin's own docs. Its `createRedirects`\n * function computes redirects dynamically and can't be evaluated statically,\n * so its presence is warned about rather than silently ignored.\n */\nexport function readDocusaurusRedirects(\n repositoryRoot: string,\n warnings: Array<MigrationWarning>,\n): Array<{ source: string; destination: string }> {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return []\n const configSource = readBoundedText(configPath)\n const pluginMatch = /['\"]@docusaurus\\/plugin-client-redirects['\"]\\s*,\\s*/.exec(configSource)\n if (!pluginMatch) return []\n const afterPlugin = configSource.slice(pluginMatch.index + pluginMatch[0].length)\n const warnAboutCreateRedirects = (source: string): void => {\n if (!/\\bcreateRedirects\\s*[:(]/.test(source)) return\n warnings.push({\n code: 'unsupported-config',\n message: \"The redirects plugin's createRedirects function computes redirects dynamically and cannot be evaluated during migration; add its redirects manually.\",\n })\n }\n warnAboutCreateRedirects(configSource)\n // Case 1: the plugin's options object is written inline.\n const inlineLiteral = matchingObjectLiteral(configSource, pluginMatch.index + pluginMatch[0].length)\n if (inlineLiteral) return redirectEntriesFromObjectLiteralText(inlineLiteral)\n // Case 2: the options are an identifier imported from another module.\n const identifier = afterPlugin.match(/^([A-Za-z_$][\\w$]*)/)?.[1]\n if (!identifier) return []\n const importMatch = new RegExp(`import\\\\s*\\\\{[^}]*\\\\b${identifier}\\\\b[^}]*\\\\}\\\\s*from\\\\s*(['\"])([^'\"]+)\\\\1`).exec(configSource)\n ?? new RegExp(`import\\\\s+${identifier}\\\\s+from\\\\s*(['\"])([^'\"]+)\\\\1`).exec(configSource)\n const modulePath = importMatch?.[2]\n if (!modulePath || !modulePath.startsWith('.')) return []\n let resolvedPath: string | undefined\n try {\n resolvedPath = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs']\n .map((extension) => resolveWithin(repositoryRoot, `${modulePath.replace(/^\\.\\//, '')}${extension}`))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile())\n } catch {\n return []\n }\n if (!resolvedPath) return []\n const moduleSource = readBoundedText(resolvedPath)\n warnAboutCreateRedirects(moduleSource)\n const literal = namedExportObjectLiteralText(moduleSource, identifier)\n return literal ? redirectEntriesFromObjectLiteralText(literal) : []\n}\n\nfunction readCategoryMetadata(contentRoot: string, directory: string): CategoryMetadata {\n for (const filename of CATEGORY_FILENAMES) {\n const path = resolveWithin(contentRoot, posix.join(directory, filename))\n if (!existsSync(path) || !lstatSync(path).isFile()) continue\n try {\n const raw = readBoundedText(path)\n const parsed = filename.endsWith('.json') ? JSON5.parse(raw) : parseYaml(raw)\n const object = objectValue(parsed)\n if (!object) return {}\n return {\n ...(typeof object.label === 'string' ? { label: object.label } : {}),\n ...(typeof object.position === 'number' ? { position: object.position } : {}),\n ...('link' in object ? { link: object.link } : {}),\n }\n } catch {\n return {}\n }\n }\n return {}\n}\n\nfunction descriptorSort(left: DocusaurusPageDescriptor, right: DocusaurusPageDescriptor): number {\n const leftPosition = left.sidebarPosition ?? Number.MAX_SAFE_INTEGER\n const rightPosition = right.sidebarPosition ?? Number.MAX_SAFE_INTEGER\n if (leftPosition !== rightPosition) return leftPosition - rightPosition\n return left.sourcePath.localeCompare(right.sourcePath, undefined, { numeric: true })\n}\n\nfunction registerDoc(docId: string, context: ProjectionContext): string | null {\n const key = normalizeDocId(docId)\n const descriptor = context.descriptorByDocId.get(key)\n ?? context.descriptors.find((page) => page.navigationId === docusaurusRouteId(key))\n if (!descriptor) {\n context.warnings.push({\n code: 'missing-page',\n message: 'A Docusaurus sidebar document did not resolve to an imported page.',\n source: docId,\n })\n return null\n }\n context.referencedNavigationIds.add(descriptor.navigationId)\n return descriptor.navigationId\n}\n\nfunction generatedIndexPage(\n label: string,\n linkValue: unknown,\n context: ProjectionContext,\n): string | null {\n const link = objectValue(linkValue)\n if (!link) return null\n if (link.type === 'doc' && typeof link.id === 'string') return registerDoc(link.id, context)\n if (link.type !== 'generated-index') return null\n const fallback = `category/${slugifySegment(label)}`\n const unprefixedNavigationId = typeof link.slug === 'string'\n ? routeFromSlug(link.slug, fallback) ?? fallback\n : fallback\n const navigationId = context.routePrefix\n && unprefixedNavigationId !== context.routePrefix\n && !unprefixedNavigationId.startsWith(`${context.routePrefix}/`)\n ? posix.join(context.routePrefix, unprefixedNavigationId)\n : unprefixedNavigationId\n if (!context.generatedIds.has(navigationId)\n && !context.descriptors.some((page) => page.navigationId === navigationId)) {\n const description = typeof link.description === 'string'\n ? link.description\n : `Browse the ${label} documentation.`\n context.generatedPages.push({\n id: storageIdForRoute(navigationId),\n navigationId,\n title: typeof link.title === 'string' ? link.title : label,\n description,\n keywords: Array.isArray(link.keywords)\n ? link.keywords.filter((value): value is string => typeof value === 'string')\n : [],\n body: description,\n source: `${context.sourceUrl}#${context.sidebarSource}`,\n })\n context.generatedIds.add(navigationId)\n }\n context.referencedNavigationIds.add(navigationId)\n return navigationId\n}\n\nconst DOCUSAURUS_HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/\n\nfunction findDocusaurusConfigPath(repositoryRoot: string): string | null {\n return ['docusaurus.config.js', 'docusaurus.config.ts', 'docusaurus.config.mjs']\n .map((filename) => resolveWithin(repositoryRoot, filename))\n .find((candidate) => existsSync(candidate) && lstatSync(candidate).isFile()) ?? null\n}\n\n/**\n * Extract a static `--ifm-color-primary` accent from the classic theme's\n * `customCss` file (Infima's own theming convention: a `:root` block for\n * light mode, an `html[data-theme='dark']` block for dark mode). Its\n * `light`/`dark` blocks are normal, like Fern's (unlike Mintlify's inverted\n * schema `site.colors` otherwise follows), so they're swapped the same way\n * `fernThemeColors` does to give downstream consumers one consistent\n * contract.\n */\nexport function readDocusaurusThemeColor(repositoryRoot: string): { light?: string; dark?: string } | undefined {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return undefined\n const configSource = readBoundedText(configPath)\n const cssRelativePath = configSource.match(/\\bcustomCss\\s*:\\s*(?:\\[\\s*)?(?:require\\.resolve\\(\\s*)?(['\"])([^'\"]+)\\1/)?.[2]\n if (!cssRelativePath) return undefined\n let cssPath: string\n try {\n cssPath = resolveWithin(repositoryRoot, cssRelativePath.replace(/^\\.\\//, ''))\n } catch {\n return undefined\n }\n if (!existsSync(cssPath) || !lstatSync(cssPath).isFile()) return undefined\n const css = readBoundedText(cssPath)\n const pick = (block: string | undefined): string | undefined => {\n const value = block?.match(/--ifm-color-primary\\s*:\\s*([^;]+);/)?.[1]?.trim()\n return value && DOCUSAURUS_HEX_COLOR.test(value) ? value : undefined\n }\n const lightMode = pick(css.match(/:root\\s*\\{([^}]*)\\}/)?.[1])\n const darkMode = pick(css.match(/\\[data-theme=(['\"])dark\\1\\]\\s*\\{([^}]*)\\}/)?.[2])\n const colors: { light?: string; dark?: string } = {}\n if (darkMode) colors.light = darkMode\n if (lightMode) colors.dark = lightMode\n return Object.keys(colors).length > 0 ? colors : undefined\n}\n\nexport interface DocusaurusSiteSettings {\n name?: string\n description?: string\n navbarTitle?: string\n defaultColorMode?: 'light' | 'dark'\n logo?: { light: string; dark?: string; showTitle?: boolean }\n favicon?: string\n /** Docusaurus serves the classic docs plugin below /docs unless configured otherwise. */\n docsRouteBasePath: string\n navbarLinks: Array<{ label: string; href?: string; docId?: string; sidebarId?: string; docsPluginId?: string }>\n footerLinks: NonNullable<MigrationDocsConfig['footer']>['links']\n copyright?: string\n}\n\nfunction propertyStart(source: string, name: string): number {\n // Only property positions count. A bare word in a comment or a value must\n // never become executable configuration during repository migration.\n const pattern = new RegExp(`(?:^|[,{\\\\n])\\\\s*[\"']?${name}[\"']?\\\\s*:\\\\s*`, 'm')\n const match = pattern.exec(source)\n return match ? match.index + match[0].length : -1\n}\n\nfunction staticStringBindings(source: string): Map<string, string> {\n const bindings = new Map<string, string>()\n for (const match of source.matchAll(/\\bconst\\s+([A-Z][A-Z0-9_]*)\\s*=\\s*((?:\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'))/g)) {\n try {\n const value = JSON5.parse(match[2]) as unknown\n if (typeof value === 'string') bindings.set(match[1], value)\n } catch {\n // Executable or malformed declarations cannot become imported links.\n }\n }\n return bindings\n}\n\nfunction staticArrayField(source: string, name: string): string | null {\n const start = propertyStart(source, name)\n return start < 0 ? null : matchingArrayLiteral(source, start)\n}\n\nfunction staticObjectEntries(array: string | null): Array<string> {\n if (!array) return []\n const entries: Array<string> = []\n let afterDelimiter = 1\n let quote = ''\n let lineComment = false\n let blockComment = false\n for (let index = 1; index < array.length - 1; index++) {\n const char = array[index]\n const next = array[index + 1]\n if (lineComment) {\n if (char === '\\n') lineComment = false\n continue\n }\n if (blockComment) {\n if (char === '*' && next === '/') { blockComment = false; index++ }\n continue\n }\n if (quote) {\n if (char === '\\\\') { index++; continue }\n if (char === quote) quote = ''\n continue\n }\n if (char === '/' && next === '/') { lineComment = true; index++; continue }\n if (char === '/' && next === '*') { blockComment = true; index++; continue }\n if (char === '\"' || char === \"'\" || char === '`') { quote = char; continue }\n if (char === ',') { afterDelimiter = index + 1; continue }\n if (char !== '{') continue\n const literal = matchingObjectLiteral(array, index)\n if (!literal) continue\n const lead = array.slice(afterDelimiter, index)\n .replace(/\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*/g, '').trim()\n // `isDev && { ... }` is a conditional entry; never assume it appears in\n // production just because its object literal can be read statically.\n if (!lead) entries.push(literal)\n index += literal.length - 1\n }\n return entries\n}\n\nfunction staticStringField(source: string, name: string, bindings?: Map<string, string>): string | undefined {\n const start = propertyStart(source, name)\n if (start < 0) return undefined\n const quoted = source.slice(start).match(/^(\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*')/)\n if (!quoted) {\n const binding = source.slice(start).match(/^([A-Z][A-Z0-9_]*)\\b/)?.[1]\n return binding ? bindings?.get(binding) : undefined\n }\n try {\n const parsed = JSON5.parse(quoted[1]) as unknown\n return typeof parsed === 'string' ? parsed : undefined\n } catch {\n return undefined\n }\n}\n\n/** Project Docusaurus' static site identity and footer without loading config code. */\nexport function readDocusaurusSiteSettings(repositoryRoot: string): DocusaurusSiteSettings {\n const empty: DocusaurusSiteSettings = { docsRouteBasePath: 'docs', defaultColorMode: 'light', navbarLinks: [], footerLinks: [] }\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return empty\n const source = readBoundedText(configPath)\n const bindings = staticStringBindings(source)\n const presets = staticArrayField(source, 'presets')\n const classicDocs = presets && [...presets.matchAll(/[\"']?docs[\"']?\\s*:\\s*/g)]\n .map((match) => matchingObjectLiteral(presets, (match.index ?? 0) + match[0].length))\n .find((object): object is string => Boolean(object))\n const docsRouteBasePath = classicDocs && staticStringField(classicDocs, 'routeBasePath') || 'docs'\n const themeStart = propertyStart(source, 'themeConfig')\n const theme = themeStart < 0 ? null : matchingObjectLiteral(source, themeStart)\n const colorModeStart = theme ? propertyStart(theme, 'colorMode') : -1\n const colorMode = colorModeStart < 0 ? null : matchingObjectLiteral(theme!, colorModeStart)\n const configuredColorMode = colorMode ? staticStringField(colorMode, 'defaultMode') : undefined\n const defaultColorMode = configuredColorMode === 'dark' ? 'dark' : 'light'\n const navbarStart = theme ? propertyStart(theme, 'navbar') : -1\n const navbar = navbarStart < 0 ? null : matchingObjectLiteral(theme!, navbarStart)\n const logoStart = navbar ? propertyStart(navbar, 'logo') : -1\n const logo = logoStart < 0 ? null : matchingObjectLiteral(navbar!, logoStart)\n const footerStart = theme ? propertyStart(theme, 'footer') : -1\n const footer = footerStart < 0 ? null : matchingObjectLiteral(theme!, footerStart)\n const navbarLinks = navbar ? staticObjectEntries(staticArrayField(navbar, 'items')).flatMap((item) => {\n // A dropdown owns nested links but no single destination. Taking its\n // first child as the parent's href creates duplicate, misleading links.\n if (propertyStart(item, 'items') >= 0 || propertyStart(item, 'dropdownItemsAfter') >= 0) return []\n const docsPluginId = staticStringField(item, 'docsPluginId', bindings)\n const href = staticStringField(item, 'to', bindings)\n ?? staticStringField(item, 'href', bindings)\n const docId = staticStringField(item, 'docId', bindings)\n const sidebarId = staticStringField(item, 'sidebarId', bindings)\n const label = staticStringField(item, 'label', bindings) ?? staticStringField(item, 'aria-label', bindings)\n return label && (href || docId || sidebarId || docsPluginId)\n ? [{ label, ...(href ? { href } : {}), ...(docId ? { docId } : {}),\n ...(sidebarId ? { sidebarId } : {}), ...(docsPluginId ? { docsPluginId } : {}) }]\n : []\n }) : []\n const footerLinks = footer ? staticObjectEntries(staticArrayField(footer, 'links')).flatMap((column) => {\n const heading = staticStringField(column, 'title', bindings)\n if (!heading) return []\n const items = staticObjectEntries(staticArrayField(column, 'items')).flatMap((item) => {\n const href = staticStringField(item, 'to', bindings) ?? staticStringField(item, 'href', bindings)\n const label = staticStringField(item, 'label', bindings)\n return label && href\n ? [{ label, href }]\n : []\n })\n return items.length > 0 ? [{ heading, items }] : []\n }) : []\n // A build-time year expression is the one dynamic Docusaurus copyright\n // pattern that can be represented without evaluating source JavaScript.\n const copyright = footer && propertyStart(footer, 'copyright') >= 0\n ? staticStringField(footer, 'copyright')\n ?? footer.slice(propertyStart(footer, 'copyright')).match(/^`([^`]+)`/)?.[1]\n ?.replace(/\\$\\{new Date\\(\\)\\.getFullYear\\(\\)\\}/g, '{year}')\n : undefined\n return {\n name: staticStringField(source, 'title'),\n description: staticStringField(source, 'tagline'),\n ...(navbar && staticStringField(navbar, 'title') ? { navbarTitle: staticStringField(navbar, 'title') } : {}),\n defaultColorMode,\n docsRouteBasePath,\n ...(logo && staticStringField(logo, 'src') ? {\n logo: {\n light: staticStringField(logo, 'src')!,\n ...(staticStringField(logo, 'srcDark') ? { dark: staticStringField(logo, 'srcDark') } : {}),\n showTitle: Boolean(navbar && staticStringField(navbar, 'title')),\n },\n } : {}),\n ...(staticStringField(source, 'favicon') ? { favicon: staticStringField(source, 'favicon') } : {}),\n navbarLinks,\n footerLinks,\n ...(copyright ? { copyright } : {}),\n }\n}\n\nfunction autogeneratedItems(dirName: string, context: ProjectionContext): Array<string | MigrationNavigationGroup> {\n const normalizedDir = dirName === '.' ? '' : normalizeDocId(dirName)\n const inDirectory = context.descriptors.filter((descriptor) => {\n const source = descriptor.sourcePath.replace(/\\.(?:mdx?)$/i, '')\n return !normalizedDir || source === normalizedDir || source.startsWith(`${normalizedDir}/`)\n })\n const directPages: Array<DocusaurusPageDescriptor> = []\n const childDirectories = new Set<string>()\n for (const descriptor of inDirectory) {\n const source = descriptor.sourcePath.replace(/\\.(?:mdx?)$/i, '')\n const relativePath = normalizedDir ? posix.relative(normalizedDir, source) : source\n const segments = relativePath.split('/').filter(Boolean)\n if (segments.length <= 1) directPages.push(descriptor)\n else childDirectories.add(segments[0])\n }\n\n const pages = directPages.map((descriptor) => ({\n // An index document is the category landing page in Docusaurus. Thally\n // renders it as a child link, so put it before the category's other docs.\n position: descriptor.sidebarPosition ?? (/(?:^|\\/)(?:index|readme)\\.mdx?$/i.test(descriptor.sourcePath)\n ? -1 : Number.MAX_SAFE_INTEGER),\n sortKey: descriptor.sourcePath,\n item: descriptor.navigationId as string | MigrationNavigationGroup,\n }))\n const groups = [...childDirectories].map((segment) => {\n const directory = normalizedDir ? posix.join(normalizedDir, segment) : segment\n const metadata = readCategoryMetadata(context.contentRoot, directory)\n const pages = autogeneratedItems(directory, context)\n // A folder containing only its index document is a direct sidebar doc in\n // Docusaurus. Inventing a category here duplicates the link and moves it\n // after ordered siblings when the folder has no `_category_` metadata.\n if (pages.length === 1 && typeof pages[0] === 'string'\n && !metadata.label && metadata.position === undefined && !metadata.link) {\n const onlyPage = context.descriptors.find((descriptor) => descriptor.navigationId === pages[0])\n if (onlyPage && /(?:^|\\/)(?:index|readme)\\.mdx?$/i.test(onlyPage.sourcePath)) {\n return {\n position: onlyPage.sidebarPosition ?? Number.MAX_SAFE_INTEGER,\n sortKey: segment,\n item: pages[0],\n }\n }\n }\n const landing = generatedIndexPage(metadata.label ?? titleCase(segment), metadata.link, context)\n if (landing && !pages.includes(landing)) pages.unshift(landing)\n return {\n position: metadata.position ?? Number.MAX_SAFE_INTEGER,\n sortKey: segment,\n item: {\n group: metadata.label ?? titleCase(segment),\n pages,\n } satisfies MigrationNavigationGroup,\n }\n })\n // Docusaurus sorts direct docs and child categories in one list. Sorting\n // them separately moves every category below every doc regardless of the\n // authored sidebar_position / _category_.json position.\n return [...pages, ...groups]\n .sort((left, right) => left.position - right.position\n || left.sortKey.localeCompare(right.sortKey, undefined, { numeric: true }))\n .map(({ item }) => {\n if (typeof item === 'string') context.referencedNavigationIds.add(item)\n return item\n })\n}\n\nfunction convertItems(value: unknown, context: ProjectionContext): Array<string | MigrationNavigationGroup> {\n if (typeof value === 'string') {\n const page = registerDoc(value, context)\n return page ? [page] : []\n }\n if (Array.isArray(value)) return value.flatMap((entry) => convertItems(entry, context))\n const object = objectValue(value)\n if (!object) return []\n\n if (object.type === 'doc' || object.type === 'ref') {\n const page = typeof object.id === 'string' ? registerDoc(object.id, context) : null\n return page ? [page] : []\n }\n if (object.type === 'autogenerated') {\n return autogeneratedItems(typeof object.dirName === 'string' ? object.dirName : '.', context)\n }\n if (object.type === 'category') {\n const label = typeof object.label === 'string' ? object.label : 'Documentation'\n const pages = convertItems(object.items, context)\n const landing = generatedIndexPage(label, object.link, context)\n if (landing && !pages.includes(landing)) pages.unshift(landing)\n return pages.length > 0 ? [{ group: label, pages }] : []\n }\n if (object.type === 'link' || object.type === 'html') return []\n\n // Docusaurus category shorthand and sidebar slices are ordinary objects.\n return Object.entries(object).flatMap(([label, items]) => {\n const pages = convertItems(items, context)\n return pages.length > 0 ? [{ group: label, pages }] : []\n })\n}\n\n/** Project explicit and autogenerated Docusaurus sidebars into Thally tabs. */\nexport function projectDocusaurusNavigation(input: {\n sidebars: DocusaurusSidebars | null\n descriptors: Array<DocusaurusPageDescriptor>\n contentRoot: string\n sourceUrl: string\n routePrefix?: string\n}): DocusaurusNavigationResult {\n const warnings: Array<MigrationWarning> = []\n const descriptorByDocId = new Map(input.descriptors.map((page) => [page.docId, page]))\n const context: ProjectionContext = {\n contentRoot: input.contentRoot,\n descriptors: input.descriptors,\n descriptorByDocId,\n generatedPages: [],\n generatedIds: new Set(),\n referencedNavigationIds: new Set(),\n sourceUrl: input.sourceUrl,\n routePrefix: input.routePrefix ?? '',\n sidebarSource: input.sidebars?.sourcePath ?? 'autogenerated sidebar',\n warnings,\n }\n const sidebarEntries: Array<[string, unknown]> = input.sidebars ? Object.entries(input.sidebars.config) : [['docs', [\n { type: 'autogenerated', dirName: '.' },\n ]]]\n const tabs = sidebarEntries.flatMap(([sidebarId, value]) => {\n const converted = convertItems(value, context)\n if (converted.length === 0) return []\n return [{\n tab: sidebarEntries.length === 1 ? 'Documentation' : titleCase(sidebarId),\n // Docusaurus categories are disclosures, including at the sidebar\n // root. Keeping them as Thally root nodes preserves their collapsed\n // state and the authored interleaving of documents and categories.\n pages: converted,\n }]\n })\n\n const unreferenced = input.descriptors\n .filter((page) => !context.referencedNavigationIds.has(page.navigationId))\n .sort(descriptorSort)\n .map((page) => page.navigationId)\n if (unreferenced.length > 0) {\n if (tabs.length === 0) tabs.push({ tab: 'Documentation', pages: [] })\n tabs[0].pages?.push({ group: 'Additional', pages: unreferenced })\n }\n return {\n docsConfig: { tabs },\n generatedPages: context.generatedPages,\n referencedNavigationIds: context.referencedNavigationIds,\n warnings,\n }\n}\n","/**\n * Navigation projection for imported sites. Mintlify's schema is intentionally\n * more expressive than Thally's tab/group model, so complex containers are\n * flattened predictably while preserving page order and nested groups.\n */\n\nimport { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, extname, relative } from 'node:path'\n\nimport { mintlifyLocalizedReference, pageIdFromReference, resolveWithin, trimEdgeSlashes } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationNavigationTab,\n MigrationPage,\n MigrationWarning,\n} from './types.js'\n\ninterface MintlifyPageReference {\n ref: string\n navigationId: string\n locale?: string\n}\n\nconst MAX_MINTLIFY_CONFIG_BYTES = 20_000_000\n\nexport interface MintlifyNavigationResult {\n docsConfig: MigrationDocsConfig\n pageReferences: Array<MintlifyPageReference>\n warnings: Array<MigrationWarning>\n}\n\nexport interface MintlifyProjectionOptions {\n /** Public URL migrations may expose page hrefs including the docs mount path. */\n pathPrefix?: string\n}\n\n/** Preserve Mintlify's implicit `/section` route for section landing pages. */\nexport function addMintlifyDirectoryRedirects(\n config: MigrationDocsConfig,\n pages: Array<MigrationPage>,\n): MigrationDocsConfig {\n const pageIds = new Set(pages.map((page) => page.id))\n const redirects = [...(config.redirects ?? [])]\n const redirectSources = new Set(redirects.map((redirect) => redirect.source.replace(/\\/$/, '') || '/'))\n function hasAuthoredRedirect(source: string): boolean {\n if (redirectSources.has(source)) return true\n return (config.redirects ?? []).some((redirect) => {\n // A trailing catch-all also owns its empty suffix. Do not insert an\n // exact alias that competes with that authored directory behavior.\n const match = redirect.source.match(/^(.*)\\/:[A-Za-z_][A-Za-z0-9_]*\\*\\/?$/)\n return match ? source === match[1] || source.startsWith(`${match[1]}/`) : false\n })\n }\n for (const page of pages) {\n if (!/\\/(?:overview|introduction)$/.test(page.navigationId)) continue\n const parent = page.id.replace(/\\/(?:overview|introduction)$/, '')\n if (!parent || pageIds.has(parent)) continue\n const source = `/${parent}`\n if (hasAuthoredRedirect(source)) continue\n redirects.push({ source, destination: `/${page.id}`, permanent: false })\n redirectSources.add(source)\n }\n\n const navigationOrder: Array<string> = []\n function collectPages(nodes: Array<string | MigrationNavigationGroup>): void {\n for (const node of nodes) {\n if (typeof node === 'string') navigationOrder.push(node)\n else if (!node.hidden) collectPages(node.pages)\n }\n }\n for (const tab of config.tabs) {\n if (!tab.hidden) collectPages([...(tab.pages ?? []), ...(tab.groups ?? [])])\n }\n const pagesByNavigationId = new Map<string, Array<MigrationPage>>()\n for (const page of pages) {\n if (page.hidden) continue\n const variants = pagesByNavigationId.get(page.navigationId) ?? []\n variants.push(page)\n pagesByNavigationId.set(page.navigationId, variants)\n }\n const firstDescendantByDirectory = new Map<string, MigrationPage>()\n for (const navigationId of navigationOrder) {\n for (const page of pagesByNavigationId.get(navigationId) ?? []) {\n const segments = page.id.split('/')\n for (let length = 1; length < segments.length; length++) {\n const directory = segments.slice(0, length).join('/')\n if (!firstDescendantByDirectory.has(directory)) firstDescendantByDirectory.set(directory, page)\n }\n }\n }\n // Mintlify 307s *any* nav-shaped directory path with no page of its own to\n // its first descendant page in navigation order — not only ones an\n // overview/introduction page or an authored redirect already pointed at\n // (e.g. a `product`/`tab`/`group` container path like Upstash's `/redis`,\n // or a plain mid-tree directory like `/vector/sdks/py/example_calls`).\n // `firstDescendantByDirectory` already holds every such directory (built\n // from real page ids in navigation order above), so redirect all of them\n // in one pass; `hasAuthoredRedirect` skips any directory the overview/\n // introduction pass above, or the project's own `redirects:`, already\n // covers, and `pageIds.has(directory)` never overrides a real page.\n for (const [directory, landing] of firstDescendantByDirectory) {\n if (pageIds.has(directory)) continue\n const source = `/${directory}`\n if (hasAuthoredRedirect(source)) continue\n // Match full stored ids, not locale-independent navigation ids: a French\n // directory must never be redirected to an English descendant.\n redirects.push({ source, destination: `/${landing.id}`, permanent: false })\n redirectSources.add(source)\n }\n return redirects.length > 0 ? { ...config, redirects } : config\n}\n\n/**\n * Keep authored page URLs while resolving bare documentation roots to the\n * first visible navigation page. An unrelated `home.mdx` is not evidence that\n * Mintlify served it at `/`; explicit source redirects always take priority.\n */\nexport function addMintlifyHomepageRedirects(\n config: MigrationDocsConfig,\n pages: Array<MigrationPage>,\n): MigrationDocsConfig {\n const defaultPages = new Set(pages\n .filter((page) => !page.locale || page.locale === config.i18n?.defaultLocale)\n .map((page) => page.navigationId))\n function firstPage(nodes: Array<string | MigrationNavigationGroup>): string | undefined {\n for (const node of nodes) {\n if (typeof node === 'string') {\n if (defaultPages.has(node)) return node\n } else if (!node.hidden) {\n const page = firstPage(node.pages)\n if (page) return page\n }\n }\n }\n const homepage = config.tabs.filter((tab) => !tab.hidden)\n .map((tab) => firstPage([...(tab.pages ?? []), ...(tab.groups ?? [])]))\n .find(Boolean)\n if (!homepage || homepage === 'introduction') return config\n const redirects = [...(config.redirects ?? [])]\n const sources = new Set(redirects.map((redirect) => redirect.source.replace(/\\/$/, '') || '/'))\n const roots = ['', ...(config.i18n?.locales ?? [])\n .filter((locale) => locale.code !== config.i18n?.defaultLocale)\n .map((locale) => locale.code)]\n for (const locale of roots) {\n const source = locale ? `/${locale}` : '/'\n if (sources.has(source)) continue\n redirects.push({ source, destination: `${locale ? `/${locale}` : ''}/${homepage}`, permanent: false })\n }\n return { ...config, redirects }\n}\n\nconst LANGUAGE_LABELS: Record<string, string> = {\n ar: 'Arabic',\n de: 'German',\n en: 'English',\n es: 'Spanish',\n fr: 'French',\n hi: 'Hindi',\n it: 'Italian',\n ja: 'Japanese',\n ko: 'Korean',\n nl: 'Dutch',\n pl: 'Polish',\n pt: 'Portuguese',\n ru: 'Russian',\n tr: 'Turkish',\n uk: 'Ukrainian',\n zh: 'Chinese',\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\n/**\n * Some Mintlify sites (e.g. Upstash's docs.json) group `products` under an\n * extra `productGroups: [{ group, products }]` wrapper instead of a bare\n * `products` array directly on the tab. Flatten it into `products` so the\n * existing container handling picks the products up unchanged — otherwise\n * every page and `openapi`/`asyncapi` reference under it is silently\n * invisible to navigation projection and API-spec resolution alike.\n */\nfunction withFlattenedProductGroups(container: Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(container.productGroups)) return container\n const flattened = (container.productGroups as Array<unknown>).flatMap((entry) => {\n const group = objectValue(entry)\n return group && Array.isArray(group.products) ? group.products : []\n })\n if (flattened.length === 0) return container\n return {\n ...container,\n products: [...(Array.isArray(container.products) ? container.products : []), ...flattened],\n }\n}\n\nfunction projectedHref(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const href = value.trim()\n if (!href || /[\\u0000-\\u001f\\u007f]/.test(href)) return undefined\n if (/^(?:javascript|data|vbscript|file):/i.test(href)) return undefined\n const scheme = href.match(/^([a-z][a-z0-9+.-]*):/i)?.[1].toLowerCase()\n if (scheme && !['http', 'https', 'mailto', 'tel'].includes(scheme)) return undefined\n return href\n}\n\nfunction labelFor(value: Record<string, unknown>, fallback: string): string {\n for (const key of ['tab', 'group', 'anchor', 'product', 'dropdown', 'version', 'menu', 'label', 'name', 'title']) {\n if (typeof value[key] === 'string' && value[key]) return String(value[key])\n }\n return fallback\n}\n\nfunction localReference(value: string): string {\n return value.split('#', 1)[0]\n}\n\nfunction jsonPointer(root: unknown, pointer: string): unknown {\n if (!pointer || pointer === '#') return root\n const tokens = pointer.replace(/^#\\/?/, '').split('/').filter(Boolean)\n return tokens.reduce<unknown>((current, token) => {\n if (Array.isArray(current)) {\n const index = Number(token)\n return Number.isSafeInteger(index) && index >= 0 ? current[index] : undefined\n }\n const object = objectValue(current)\n if (!object) return undefined\n return object[token.replace(/~1/g, '/').replace(/~0/g, '~')]\n }, root)\n}\n\nfunction readMintlifyJson(path: string, repositoryRoot: string): unknown {\n if (!existsSync(path) || !lstatSync(path).isFile()) {\n throw new Error(`Mintlify config reference is not a regular file: ${relative(repositoryRoot, path)}`)\n }\n const realPath = realpathSync(path)\n const realRoot = realpathSync(repositoryRoot)\n resolveWithin(realRoot, relative(realRoot, realPath))\n if (lstatSync(realPath).size > MAX_MINTLIFY_CONFIG_BYTES) {\n throw new Error(`Mintlify config reference exceeded ${MAX_MINTLIFY_CONFIG_BYTES / 1_000_000} MB: ${relative(repositoryRoot, path)}`)\n }\n return JSON.parse(readFileSync(realPath, 'utf8')) as unknown\n}\n\nfunction resolveJsonReferences(\n value: unknown,\n currentFile: string,\n repositoryRoot: string,\n stack: Set<string>,\n): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => resolveJsonReferences(entry, currentFile, repositoryRoot, stack))\n }\n const object = objectValue(value)\n if (!object) return value\n if (typeof object.$ref === 'string') {\n const [filePart, pointer = ''] = object.$ref.split('#', 2)\n const referencedFile = filePart\n ? resolveWithin(dirname(currentFile), filePart)\n : currentFile\n const relativePath = relative(repositoryRoot, referencedFile)\n resolveWithin(repositoryRoot, relativePath)\n const stackKey = `${referencedFile}#${pointer}`\n if (stack.has(stackKey)) throw new Error(`Circular Mintlify $ref: ${object.$ref}`)\n stack.add(stackKey)\n const referencedRoot = readMintlifyJson(referencedFile, repositoryRoot)\n const referenced = jsonPointer(referencedRoot, pointer ? `#${pointer}` : '')\n const resolved = resolveJsonReferences(referenced, referencedFile, repositoryRoot, stack)\n stack.delete(stackKey)\n const siblings = Object.fromEntries(\n Object.entries(object)\n .filter(([key]) => key !== '$ref')\n .map(([key, entry]) => [\n key,\n resolveJsonReferences(entry, currentFile, repositoryRoot, stack),\n ]),\n )\n // Mintlify merges sibling keys over object-valued references. Retaining\n // this behavior matters for split navigation files that override one\n // label, link, or visibility flag at the reference site.\n return objectValue(resolved) ? { ...resolved as Record<string, unknown>, ...siblings } : resolved\n }\n return Object.fromEntries(\n Object.entries(object).map(([key, entry]) => [\n key,\n resolveJsonReferences(entry, currentFile, repositoryRoot, stack),\n ]),\n )\n}\n\n/** Read `docs.json`/`mint.json`, including bounded local JSON references. */\nexport function readMintlifyConfig(repositoryRoot: string): Record<string, unknown> | null {\n const configPath = ['docs.json', 'mint.json']\n .map((filename) => resolveWithin(repositoryRoot, filename))\n .find(existsSync)\n if (!configPath) return null\n const raw = readMintlifyJson(configPath, repositoryRoot)\n return resolveJsonReferences(raw, configPath, repositoryRoot, new Set()) as Record<string, unknown>\n}\n\n/** One `openapi`/`asyncapi` value found anywhere in Mintlify's navigation tree. */\nexport interface MintlifyApiSpecReference {\n /** The field's raw value: a repository-relative path, or an `http(s)://` URL. */\n value: string\n kind: 'openapi' | 'asyncapi'\n /** Label of the nearest enclosing tab/anchor/dropdown/product/version/menu, so the resolved spec binds to that tab specifically. Undefined at the navigation root. */\n tabLabel?: string\n /** Set when the source used Mintlify's object form to scope generated pages under a nested directory; Thally can only bind the whole tab, so this is lost and must be warned about. */\n directory?: string\n}\n\n/**\n * Mintlify lets `openapi`/`asyncapi` appear not just at the top-level `api`\n * key but on any navigation container (most commonly a tab:\n * `navigation.tabs[].openapi`, but the same field is honored on an anchor,\n * dropdown, product, version or group too) — Mintlify binds the resulting\n * API reference to whichever tab that container renders under. This walks\n * the whole raw navigation tree (the same shape `convertContainerToTabs`\n * projects) collecting every occurrence, so the caller can resolve and bind\n * each one instead of only ever seeing the single top-level `api` field.\n */\nexport function mintlifyNavigationApiReferences(config: Record<string, unknown>): Array<MintlifyApiSpecReference> {\n const navigation = objectValue(config.navigation) ?? config\n const references: Array<MintlifyApiSpecReference> = []\n const containerKeys = ['tabs', 'anchors', 'products', 'dropdowns', 'versions', 'menus', 'languages'] as const\n const nestedKeys = ['groups', 'pages'] as const\n\n function visit(rawNode: Record<string, unknown>, tabLabel: string | undefined): void {\n const node = withFlattenedProductGroups(rawNode)\n for (const kind of ['openapi', 'asyncapi'] as const) {\n const value = node[kind]\n if (typeof value === 'string' && value.trim()) {\n references.push({ value: value.trim(), kind, tabLabel })\n continue\n }\n // Mintlify also accepts an object form (`{ source, directory }`) to\n // scope a spec's auto-generated operation pages under a nested\n // directory instead of the whole tab. Thally's API reference can't\n // be scoped to a nested path (it always renders under the tab it's\n // bound to), so the spec is still resolved and bound at the tab\n // level — better than vanishing outright — but the caller is told\n // via `directory` so it can warn that the manual scoping was lost.\n const object = objectValue(value)\n if (object && typeof object.source === 'string' && object.source.trim()) {\n references.push({\n value: object.source.trim(),\n kind,\n tabLabel,\n ...(typeof object.directory === 'string' && object.directory.trim()\n ? { directory: object.directory.trim() }\n : {}),\n })\n }\n }\n for (const key of containerKeys) {\n const entries = node[key]\n if (!Array.isArray(entries)) continue\n for (const entry of entries) {\n const object = objectValue(entry)\n if (!object) continue\n // A nested container becomes the new binding tab only at the outer\n // level (Mintlify tabs aren't themselves nested inside other tabs in\n // practice, but anchors/dropdowns can sit inside a tab) — reuse the\n // enclosing tab's label unless this container names its own.\n visit(object, labelFor(object, tabLabel ?? 'Documentation'))\n }\n }\n for (const key of nestedKeys) {\n const entries = node[key]\n if (!Array.isArray(entries)) continue\n for (const entry of entries) {\n if (typeof entry === 'string') continue\n const object = objectValue(entry)\n if (object) visit(object, tabLabel)\n }\n }\n }\n visit(navigation, undefined)\n return references\n}\n\nfunction normalizePageRef(value: string, pathPrefix = ''): string | null {\n if (/^(?:https?:)?\\/\\//i.test(value) || value.startsWith('#')) return null\n let ref = localReference(value).split('?', 1)[0].replace(/^\\/+/, '')\n const prefix = trimEdgeSlashes(pathPrefix)\n if (prefix && (ref === prefix || ref.startsWith(`${prefix}/`))) {\n ref = ref === prefix ? 'introduction' : ref.slice(prefix.length + 1)\n }\n ref = ref.replace(/\\.(?:mdx?|rst|txt)$/i, '')\n // Mintlify routes are case-sensitive and commonly use camelCase filenames\n // (for example `additionalFiles`). Lowercasing here breaks both authored\n // navigation and links even though the source site resolves them correctly.\n return pageIdFromReference(ref, true)\n}\n\ninterface ProjectionContext {\n locale?: string\n defaultPageIds?: ReadonlySet<string>\n pathPrefix?: string\n references: Array<MintlifyPageReference>\n seenReferences: Set<string>\n warnings: Array<MigrationWarning>\n warningKeys: Set<string>\n}\n\nfunction warnOnce(context: ProjectionContext, key: string, message: string): void {\n if (context.warningKeys.has(key)) return\n context.warningKeys.add(key)\n context.warnings.push({ code: 'unsupported-config', message })\n}\n\nfunction iconName(value: unknown): string | undefined {\n if (typeof value === 'string' && value) return value\n const icon = objectValue(value)\n return typeof icon?.name === 'string' && icon.name ? icon.name : undefined\n}\n\nfunction containerPresentation(value: Record<string, unknown>): {\n description?: string\n icon?: string\n} {\n return {\n ...(typeof value.description === 'string' && value.description.trim()\n ? { description: value.description.trim() }\n : {}),\n ...(iconName(value.icon) ? { icon: iconName(value.icon) } : {}),\n }\n}\n\nfunction registerReference(value: string, context: ProjectionContext): string | null {\n const localizedValue = context.locale\n ? mintlifyLocalizedReference(value, context.locale, context.defaultPageIds)\n : value\n const navigationId = normalizePageRef(localizedValue, context.pathPrefix)\n if (!navigationId) return null\n const key = `${context.locale ?? ''}:${value}`\n if (!context.seenReferences.has(key)) {\n context.seenReferences.add(key)\n context.references.push({ ref: value, navigationId, locale: context.locale })\n }\n return navigationId\n}\n\n/**\n * Mintlify lets a `pages` entry name a single OpenAPI operation directly\n * (`\"GET /users\"`) to hand-pick or reorder which operations of an\n * already-`openapi`-scoped ancestor appear, instead of a page file\n * reference. Thally always renders every operation of a bound spec and\n * has no manual-selection equivalent, so these are not migratable pages —\n * treating them as one is what produced a \"did not resolve to a source\n * page\" warning per operation instead of one explanation for the group.\n */\nconst OPENAPI_OPERATION_REF = /^(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\s+\\S/\n\nfunction convertPage(\n value: unknown,\n context: ProjectionContext,\n): string | MigrationNavigationGroup | null {\n if (typeof value === 'string') {\n if (OPENAPI_OPERATION_REF.test(value)) {\n warnOnce(\n context,\n 'openapi-operation-list',\n 'One or more navigation groups hand-pick or reorder individual OpenAPI operations (e.g. \"GET /users\"); '\n + \"Thally always renders every operation of a bound spec and has no manual-selection equivalent, so that \"\n + 'list was dropped. The operations themselves are still available through the bound API reference.',\n )\n return null\n }\n return registerReference(value, context)\n }\n const object = objectValue(value)\n if (!object) return null\n if (typeof object.page === 'string') return registerReference(object.page, context)\n const href = projectedHref(object.href)\n if (href && !object.pages && !object.groups) {\n const page = registerReference(href, context)\n if (page) return page\n warnOnce(\n context,\n 'external-page-link',\n 'External links nested inside a Mintlify sidebar cannot be represented as Thally pages and were omitted.',\n )\n return null\n }\n const pages = Array.isArray(object.pages) ? object.pages : []\n if ('group' in object || pages.length > 0) {\n const children: Array<string | MigrationNavigationGroup> = []\n if (typeof object.root === 'string') {\n const root = registerReference(object.root, context)\n if (root) children.push(root)\n }\n for (const page of pages) {\n const converted = convertPage(page, context)\n if (converted) children.push(converted)\n }\n if (children.length === 0) return null\n return {\n group: labelFor(object, 'Documentation'),\n ...(iconName(object.icon) ? { icon: iconName(object.icon) } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n pages: children,\n }\n }\n return null\n}\n\nfunction convertNavigationValues(\n values: Array<unknown>,\n context: ProjectionContext,\n): Array<string | MigrationNavigationGroup> {\n return values.flatMap<string | MigrationNavigationGroup>((value) => {\n const page = convertPage(value, context)\n return page ? [page] : []\n })\n}\n\ninterface NavigationProjectionTrace {\n rootContainerKind?: 'tabs' | 'anchors' | 'products' | 'dropdowns' | 'versions' | 'menus'\n}\n\nfunction convertContainerToTabs(\n containerValue: unknown,\n context: ProjectionContext,\n fallbackTab: string,\n trace?: NavigationProjectionTrace,\n depth = 0,\n): Array<MigrationNavigationTab> {\n const rawContainer = objectValue(containerValue)\n if (!rawContainer) return []\n const container = withFlattenedProductGroups(rawContainer)\n const containerKeys = ['tabs', 'anchors', 'products', 'dropdowns', 'versions', 'menus'] as const\n for (const key of containerKeys) {\n if (!Array.isArray(container[key])) continue\n const entries = [...container[key] as Array<unknown>]\n if (key === 'versions') {\n entries.sort((left, right) => Number(objectValue(right)?.default === true) - Number(objectValue(left)?.default === true))\n }\n const tabs = entries.flatMap((value, index) => {\n const object = objectValue(value)\n if (!object) return []\n const tab = labelFor(object, `${fallbackTab} ${index + 1}`)\n const href = projectedHref(object.href)\n const hasNestedContainers = containerKeys.some((containerKey) => Array.isArray(object[containerKey]))\n if (href && !object.pages && !object.groups && !hasNestedContainers) {\n return [{\n tab,\n href,\n ...containerPresentation(object),\n ...(object.hidden === true ? { hidden: true } : {}),\n }]\n }\n const nested = convertContainerToTabs(object, context, tab, trace, depth + 1)\n if (nested.length > 0) {\n if (nested.length === 1) {\n return [{\n ...nested[0],\n tab,\n ...containerPresentation(object),\n ...(href ? { href } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n }]\n }\n const presentation = containerPresentation(object)\n return nested.map((item, childIndex) => ({\n ...presentation,\n ...item,\n tab: `${tab}: ${item.tab}`,\n ...(childIndex === 0 && href && !item.href ? { href } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n }))\n }\n return []\n })\n if (tabs.length > 0) {\n if (depth === 0 && trace) trace.rootContainerKind = key\n return tabs\n }\n }\n const rawGroups = Array.isArray(container.groups) ? container.groups : []\n const rawPages = Array.isArray(container.pages) ? container.pages : []\n const hasRootNodes = typeof container.root === 'string' || rawPages.length > 0\n const values = [\n ...(typeof container.root === 'string' ? [container.root] : []),\n ...rawGroups,\n ...rawPages,\n ]\n const children = convertNavigationValues(values, context)\n return children.length > 0\n ? [{\n tab: fallbackTab,\n ...(hasRootNodes\n ? { pages: children }\n : { groups: children as Array<MigrationNavigationGroup> }),\n ...containerPresentation(container),\n ...(projectedHref(container.href) ? { href: projectedHref(container.href) } : {}),\n ...(container.hidden === true ? { hidden: true } : {}),\n }]\n : []\n}\n\nfunction projectedTheme(value: unknown): MigrationDocsConfig['theme'] {\n if (value === 'maple') return 'maple'\n if (['aspen', 'luma', 'sequoia'].includes(String(value))) return 'sharp'\n if (['almond', 'palm'].includes(String(value))) return 'minimal'\n return typeof value === 'string' ? 'default' : undefined\n}\n\nfunction projectedNavbar(value: unknown): MigrationDocsConfig['navbar'] {\n const navbar = objectValue(value)\n if (!navbar) return undefined\n const links = Array.isArray(navbar.links)\n ? navbar.links.flatMap((entry) => {\n const link = objectValue(entry)\n const href = projectedHref(link?.href)\n if (!link || !href) return []\n const label = typeof link.label === 'string' ? link.label : typeof link.name === 'string' ? link.name : ''\n if (!label) return []\n return [{ label, href, ...(link.type === 'github' ? { type: 'github' as const } : {}) }]\n })\n : []\n const primaryValue = objectValue(navbar.primary)\n const primaryHref = projectedHref(primaryValue?.href)\n const primary = primaryValue && primaryHref\n ? {\n label: typeof primaryValue.label === 'string'\n ? primaryValue.label\n : primaryValue.type === 'github' ? 'GitHub' : 'Get started',\n href: primaryHref,\n }\n : undefined\n return links.length > 0 || primary ? { ...(links.length > 0 ? { links } : {}), ...(primary ? { primary } : {}) } : undefined\n}\n\nfunction projectedGlobalNavigationLinks(\n value: unknown,\n): NonNullable<NonNullable<MigrationDocsConfig['navbar']>['links']> {\n const global = objectValue(value)\n if (!global) return []\n const links: Array<{ label: string; href: string }> = []\n const visit = (entry: unknown): void => {\n if (Array.isArray(entry)) {\n entry.forEach(visit)\n return\n }\n const item = objectValue(entry)\n if (!item) return\n const href = projectedHref(item.href)\n if (href) {\n const label = labelFor(item, '')\n if (label) links.push({ label, href })\n }\n for (const key of ['tabs', 'anchors', 'dropdowns', 'products', 'versions', 'languages', 'menus']) {\n if (Array.isArray(item[key])) visit(item[key])\n }\n }\n visit(global)\n return links\n}\n\nfunction projectedFooter(value: unknown): MigrationDocsConfig['footer'] {\n const footer = objectValue(value)\n if (!footer) return undefined\n const socials = objectValue(footer.socials)\n const socialLinks = socials\n ? Object.fromEntries(Object.entries(socials).flatMap(([key, value]) => {\n const href = projectedHref(value)\n return href ? [[key, href]] : []\n }))\n : undefined\n const links = Array.isArray(footer.links)\n ? footer.links.flatMap((entry) => {\n const column = objectValue(entry)\n if (!column || !Array.isArray(column.items)) return []\n const heading = typeof column.heading === 'string'\n ? column.heading\n : typeof column.header === 'string' ? column.header : ''\n const items = column.items.flatMap((item) => {\n const link = objectValue(item)\n const href = projectedHref(link?.href)\n return link && typeof link.label === 'string' && href\n ? [{ label: link.label, href }]\n : []\n })\n return heading && items.length > 0 ? [{ heading, items }] : []\n })\n : []\n return (socialLinks && Object.keys(socialLinks).length > 0) || links.length > 0\n ? { ...(socialLinks && Object.keys(socialLinks).length > 0 ? { socials: socialLinks } : {}), ...(links.length > 0 ? { links } : {}) }\n : undefined\n}\n\nfunction projectedFont(value: unknown): { family: string; weight?: Array<string> } | undefined {\n if (typeof value === 'string' && value) return { family: value }\n const font = objectValue(value)\n if (!font) return undefined\n const family = typeof font.family === 'string'\n ? font.family\n : typeof font.name === 'string' ? font.name : undefined\n if (!family) return undefined\n const weight = Array.isArray(font.weight)\n ? font.weight.map(String)\n : Array.isArray(font.weights) ? font.weights.map(String) : undefined\n return { family, ...(weight && weight.length > 0 ? { weight } : {}) }\n}\n\nfunction projectedCompatibleConfig(config: Record<string, unknown>): Omit<MigrationDocsConfig, 'tabs' | 'i18n' | 'redirects'> {\n const banner = objectValue(config.banner)\n const bannerContent = banner && (typeof banner.content === 'string' || objectValue(banner.content))\n ? banner.content as string | Record<string, string>\n : undefined\n const bannerType = banner && ['info', 'warning', 'critical'].includes(String(banner.type ?? banner.variant))\n ? String(banner.type ?? banner.variant) as 'info' | 'warning' | 'critical'\n : undefined\n const bannerColor = objectValue(banner?.color)\n const bodyFont = projectedFont(objectValue(config.fonts)?.body ?? config.fonts)\n const headingFont = projectedFont(objectValue(config.fonts)?.heading)\n const feedback = objectValue(config.feedback)\n const seo = objectValue(config.seo)\n const iconLibrary = objectValue(config.icons)?.library\n const projectedIconLibrary = ['lucide', 'fontawesome', 'tabler'].includes(String(iconLibrary))\n ? String(iconLibrary) as 'lucide' | 'fontawesome' | 'tabler'\n : undefined\n const navbar = projectedNavbar(config.navbar)\n const globalLinks = projectedGlobalNavigationLinks(objectValue(config.navigation)?.global)\n const navbarLinks = [...new Map(\n [...(navbar?.links ?? []), ...globalLinks].map((link) => [`${link.label}:${link.href}`, link]),\n ).values()]\n const projectedNavigation = navbarLinks.length > 0 || navbar?.primary\n ? { ...(navbarLinks.length > 0 ? { links: navbarLinks } : {}), ...(navbar?.primary ? { primary: navbar.primary } : {}) }\n : undefined\n return {\n ...(projectedTheme(config.theme) ? { theme: projectedTheme(config.theme) } : {}),\n ...(projectedIconLibrary ? { icons: { library: projectedIconLibrary } } : {}),\n ...(bannerContent ? {\n banner: {\n content: bannerContent,\n ...(banner?.dismissible === false ? { dismissible: false } : {}),\n ...(typeof banner?.id === 'string' ? { id: banner.id } : {}),\n ...(typeof banner?.revision === 'string' ? { revision: banner.revision } : {}),\n ...(bannerType ? { type: bannerType } : {}),\n ...(bannerColor ? { color: {\n ...(typeof bannerColor.light === 'string' ? { light: bannerColor.light } : {}),\n ...(typeof bannerColor.dark === 'string' ? { dark: bannerColor.dark } : {}),\n } } : {}),\n },\n } : {}),\n ...(projectedNavigation ? { navbar: projectedNavigation } : {}),\n ...(projectedFooter(config.footer) ? { footer: projectedFooter(config.footer) } : {}),\n ...(bodyFont || headingFont ? { fonts: { ...(bodyFont ? { body: bodyFont } : {}), ...(headingFont ? { heading: headingFont } : {}) } } : {}),\n ...(seo?.indexing === 'all' ? { seo: { indexing: 'all' } } : {}),\n ...(typeof feedback?.thumbsRating === 'boolean' ? { feedback: { thumbsRating: feedback.thumbsRating } } : {}),\n }\n}\n\nconst NEXT_REDIRECT_PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Next.js redirects compile through path-to-regexp and reject a bare `*`\n * segment (Mintlify and Fern's trailing wildcard syntax) with \"Invalid\n * redirects found\", crashing the whole build. Both platforms only document\n * `*` as a trailing catch-all segment, so it is translated to Next's named\n * catch-all (`/:path*`) here; a `*` anywhere else, or a syntax Next can't\n * express, is dropped rather than guessed at. Source text already written as\n * path-to-regexp (e.g. `:path*`) passes through unchanged: only a literal\n * `*` segment is rewritten, and the final `isValidNextRedirectPath` check\n * still accepts it.\n */\nfunction translateRedirectWildcards(\n source: string,\n destination: string,\n): { source: string; destination: string } | null {\n const sourceSegments = source.split('/')\n const destinationSegments = destination.split('/')\n const sourceWildcardIndex = sourceSegments.indexOf('*')\n if (sourceWildcardIndex !== -1 && sourceWildcardIndex !== sourceSegments.length - 1) return null\n if (sourceSegments.slice(0, -1).includes('*') || destinationSegments.slice(0, -1).includes('*')) return null\n\n const translatedSource = [...sourceSegments]\n if (sourceWildcardIndex !== -1) translatedSource[sourceWildcardIndex] = ':path*'\n\n const destinationHasWildcard = destinationSegments.at(-1) === '*'\n if (destinationHasWildcard && sourceWildcardIndex === -1) return null\n const translatedDestination = [...destinationSegments]\n if (destinationHasWildcard) translatedDestination[translatedDestination.length - 1] = ':path*'\n\n const finalSource = translatedSource.join('/')\n const finalDestination = translatedDestination.join('/')\n if (!isValidNextRedirectPath(finalSource) || !isValidNextRedirectPath(finalDestination)) return null\n return { source: finalSource, destination: finalDestination }\n}\n\n/** Conservative structural check for the path-to-regexp syntax Next.js redirects accept. */\nfunction isValidNextRedirectPath(path: string): boolean {\n return path.split('/').every((segment) => {\n if (segment === '' || segment === '*') return segment === ''\n if (!segment.startsWith(':')) return !segment.includes('*') && !segment.includes(':')\n const name = segment.endsWith('*') ? segment.slice(1, -1) : segment.slice(1)\n return NEXT_REDIRECT_PARAM_NAME.test(name)\n })\n}\n\n/**\n * Shared redirect-safety check for Mintlify and Fern: both require a\n * site-relative, `/`-rooted source and destination (Mintlify's own redirect\n * docs give only rooted examples; neither documents an absolute-URL\n * destination), so a protocol-relative or absolute value (`//evil.example`\n * reads as same-scheme cross-origin to a browser and to Next.js) is rejected.\n */\n// Matches every ASCII control character (incl. DEL, \\x7f) and every Unicode\n// whitespace character (`\\s` already covers the line/paragraph separators\n// U+2028/U+2029, along with tab, CR, LF, NBSP, etc).\nconst UNSAFE_REDIRECT_CHARS = /[\\s\\x00-\\x1f\\x7f]/\n\nexport function isRedirectPathSafe(rawSource: string, rawDestination: string): boolean {\n for (const value of [rawSource, rawDestination]) {\n if (!value.startsWith('/')) return false\n if (value.startsWith('//') || value.startsWith('/\\\\')) return false\n if (value.includes('\\\\')) return false\n // A browser strips whitespace/control characters (tab, CR, LF, ...) from\n // a URL before navigating, so a literal tab in `/\\t/evil.example` passes\n // every check above yet reaches the browser as `//evil.example`. Reject\n // any such character anywhere in the raw value.\n if (UNSAFE_REDIRECT_CHARS.test(value)) return false\n // Browsers unescape a leading `%2f%2f`/`%5c` before treating it as `//`/`\\`.\n const lower = value.toLowerCase()\n if (lower.startsWith('/%2f%2f') || lower.startsWith('/%5c')) return false\n }\n return true\n}\n\n/**\n * Translate a redirect's trailing wildcard for Next.js, once its source and\n * destination have already passed {@link isRedirectPathSafe}.\n */\nexport { translateRedirectWildcards }\n\n/**\n * Mintlify's `versions` container authors every version's own page paths\n * with the version identifier as a literal leading segment (`v1.15.22/en/\n * introduction`), including the default version's — the live site still\n * serves that path, but also serves the same page with the segment\n * dropped (`/en/introduction` 307s to the versioned URL). Thally has no\n * multi-version content model of its own (each version becomes its own\n * tab, per existing behavior), so an in-repo link authored the second way\n * has nothing to resolve to. Collecting each `versions` container's\n * default identifier lets the repository scanner add a matching redirect\n * alongside the one it already adds for a page's literal source path.\n */\nexport function mintlifyDefaultVersionPrefixes(config: Record<string, unknown>): Set<string> {\n const navigation = objectValue(config.navigation) ?? config\n const prefixes = new Set<string>()\n function collect(container: Record<string, unknown>): void {\n if (Array.isArray(container.versions)) {\n const entries = container.versions\n .map((value) => objectValue(value))\n .filter((value): value is Record<string, unknown> => value !== null)\n const defaultEntry = entries.find((entry) => entry.default === true) ?? entries[0]\n if (defaultEntry && typeof defaultEntry.version === 'string' && defaultEntry.version.trim()) {\n prefixes.add(defaultEntry.version.trim())\n }\n }\n if (Array.isArray(container.languages)) {\n for (const value of container.languages) {\n const language = objectValue(value)\n if (language) collect(language)\n }\n }\n }\n collect(navigation)\n return prefixes\n}\n\n/**\n * Every version identifier declared across all `versions` containers (not\n * just the default one) — used to label which versions' pages were dropped\n * when a repository exceeds the source-file discovery budget.\n */\nexport function mintlifyAllVersionPrefixes(config: Record<string, unknown>): Set<string> {\n const navigation = objectValue(config.navigation) ?? config\n const prefixes = new Set<string>()\n function collect(container: Record<string, unknown>): void {\n if (Array.isArray(container.versions)) {\n for (const value of container.versions) {\n const entry = objectValue(value)\n if (entry && typeof entry.version === 'string' && entry.version.trim()) prefixes.add(entry.version.trim())\n }\n }\n if (Array.isArray(container.languages)) {\n for (const value of container.languages) {\n const language = objectValue(value)\n if (language) collect(language)\n }\n }\n }\n collect(navigation)\n return prefixes\n}\n\n/** Convert current and legacy Mintlify navigation into Thally's schema. */\nexport function projectMintlifyNavigation(\n config: Record<string, unknown>,\n options: MintlifyProjectionOptions = {},\n): MintlifyNavigationResult {\n const warnings: Array<MigrationWarning> = []\n const references: Array<MintlifyPageReference> = []\n const seenReferences = new Set<string>()\n const warningKeys = new Set<string>()\n const navigation = objectValue(config.navigation) ?? config\n const languages = Array.isArray(navigation.languages)\n ? navigation.languages.flatMap((value): Array<Record<string, unknown>> => {\n const language = objectValue(value)\n if (!language) return []\n try {\n const code = Intl.getCanonicalLocales(String(language.language ?? language.locale ?? 'en'))[0]\n return [{ ...language, language: code }]\n } catch {\n warnings.push({ code: 'unsupported-config', message: 'A navigation language with an invalid locale code was skipped.' })\n return []\n }\n })\n : []\n let tabs: Array<MigrationNavigationTab> = []\n let i18n: MigrationDocsConfig['i18n']\n const localizedNavigation: Record<string, Array<MigrationNavigationTab>> = {}\n const projectionTrace: NavigationProjectionTrace = {}\n\n if (languages.length > 0) {\n const defaultLanguage = languages.find((entry) => entry.default === true) ?? languages[0]\n const defaultLocale = String(defaultLanguage.language)\n const locales = languages.map((entry) => {\n const code = String(entry.language)\n let label: string | undefined = LANGUAGE_LABELS[code]\n try {\n label ??= new Intl.DisplayNames(['en'], { type: 'language' }).of(code) ?? undefined\n } catch {\n // Unknown extension tags remain readable as their normalized code.\n }\n return { code, label: label ?? code.toUpperCase() }\n })\n i18n = { defaultLocale, locales }\n const defaultPageIds = new Set<string>()\n // The default language supplies canonical page identities even when it\n // appears after translations in the authored language picker.\n for (const language of [defaultLanguage, ...languages.filter((entry) => entry !== defaultLanguage)]) {\n const locale = String(language.language)\n const context: ProjectionContext = {\n locale,\n defaultPageIds,\n pathPrefix: options.pathPrefix,\n references,\n seenReferences,\n warnings,\n warningKeys,\n }\n const languageTabs = convertContainerToTabs(\n language,\n context,\n 'Documentation',\n language === defaultLanguage ? projectionTrace : undefined,\n )\n if (language === defaultLanguage) {\n tabs = languageTabs\n for (const reference of references) defaultPageIds.add(reference.navigationId)\n } else if (languageTabs.length > 0) {\n localizedNavigation[locale] = languageTabs\n }\n }\n if (Object.keys(localizedNavigation).length > 0) i18n.navigation = localizedNavigation\n } else {\n const context = { references, seenReferences, warnings, warningKeys, pathPrefix: options.pathPrefix }\n tabs = convertContainerToTabs(navigation, context, 'Documentation', projectionTrace)\n if (tabs.length === 0 && Array.isArray(config.navigation)) {\n const children = convertNavigationValues(config.navigation, context)\n if (children.length > 0) {\n const hasRootPages = children.some((page) => typeof page === 'string')\n tabs = [{\n tab: 'Documentation',\n ...(hasRootPages\n ? { pages: children }\n : { groups: children as Array<MigrationNavigationGroup> }),\n }]\n }\n }\n }\n\n if (tabs.length === 0) {\n warnings.push({\n code: 'unsupported-config',\n message: 'Mintlify navigation could not be projected; generated navigation will be used.',\n })\n }\n const redirects = Array.isArray(config.redirects)\n ? config.redirects.flatMap((value) => {\n const redirect = objectValue(value)\n if (!redirect || typeof redirect.source !== 'string' || typeof redirect.destination !== 'string') return []\n const rawSource = redirect.source.trim()\n const rawDestination = redirect.destination.trim()\n if (!isRedirectPathSafe(rawSource, rawDestination)) return []\n const translated = translateRedirectWildcards(rawSource, rawDestination)\n if (!translated) {\n warnings.push({\n code: 'unsupported-config',\n message: `Redirect from ${rawSource} uses a wildcard Next.js cannot express and was dropped.`,\n })\n return []\n }\n return [{\n source: translated.source,\n destination: translated.destination,\n ...(typeof redirect.permanent === 'boolean' ? { permanent: redirect.permanent } : {}),\n }]\n })\n : []\n return {\n docsConfig: {\n tabs,\n ...(projectionTrace.rootContainerKind === 'dropdowns'\n ? { navigation: { display: 'dropdown' as const } }\n : {}),\n ...projectedCompatibleConfig(config),\n ...(i18n ? { i18n } : {}),\n ...(redirects.length > 0 ? { redirects } : {}),\n },\n pageReferences: references,\n warnings,\n }\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_]/)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\ninterface GeneratedNavigationOptions {\n /** Dedicated docs platforms expose their primary sections as top-level tabs. */\n topLevelTabs?: boolean\n /** Ordered tabs recovered from the source site's rendered navigation. */\n topLevelNavigation?: ReadonlyArray<{\n section: string\n label: string\n pageId: string\n }>\n}\n\nconst TOP_LEVEL_LABELS: Record<string, string> = {\n 'api-reference': 'API Reference',\n cli: 'CLI',\n faqs: 'FAQs',\n introduction: 'Overview',\n 'mcp-server': 'MCP Server',\n sdk: 'SDK',\n}\n\nfunction topLevelLabel(segment: string): string {\n return TOP_LEVEL_LABELS[segment] ?? titleCase(segment)\n}\n\nfunction groupsWithinSection(\n section: string,\n pageIds: Array<string>,\n sectionLabel = topLevelLabel(section),\n): Array<MigrationNavigationGroup> {\n const groups = new Map<string, Array<string>>()\n for (const id of pageIds) {\n const relative = id === 'introduction'\n ? ''\n : id.startsWith(`${section}/`)\n ? id.slice(section.length + 1)\n : id\n const nestedSegment = relative.includes('/') ? relative.split('/', 1)[0] : 'overview'\n const group = groups.get(nestedSegment) ?? []\n group.push(id)\n groups.set(nestedSegment, group)\n }\n return [...groups].map(([segment, pages]) => ({\n group: segment === 'overview' ? sectionLabel : titleCase(segment),\n pages,\n }))\n}\n\nfunction preferredLandingPage(\n section: string,\n pageIds: Array<string>,\n): string | undefined {\n const candidates = [\n section === 'introduction' ? 'introduction' : undefined,\n `${section}/overview`,\n `${section}/introduction`,\n section,\n ]\n return candidates.find((candidate): candidate is string => Boolean(candidate && pageIds.includes(candidate)))\n}\n\n/** Build deterministic fallback navigation from imported default-locale pages. */\nexport function buildNavigationFromPages(\n pages: Array<MigrationPage>,\n options: GeneratedNavigationOptions = {},\n): MigrationDocsConfig {\n const ids = pages.filter((page) => !page.locale || page.locale === 'en').map((page) => page.navigationId)\n const ordered = [...new Set(ids)]\n if (options.topLevelTabs) {\n const sourceNavigation = (options.topLevelNavigation ?? []).flatMap((entry) => {\n const sectionPages = ordered.filter((id) => id === entry.section || id.startsWith(`${entry.section}/`))\n const pageId = ordered.includes(entry.pageId)\n ? entry.pageId\n : preferredLandingPage(entry.section, sectionPages) ?? sectionPages[0]\n return pageId ? [{ ...entry, pageId }] : []\n })\n if (sourceNavigation.length > 1) {\n const claimedIds = new Set<string>()\n const tabs = sourceNavigation.map((entry) => {\n const pageIds = ordered.filter((id) => {\n const matches = id === entry.pageId\n || id === entry.section\n || id.startsWith(`${entry.section}/`)\n if (matches) claimedIds.add(id)\n return matches\n })\n return { entry, pageIds }\n })\n // Mintlify's first tab is the documentation home and owns pages that do\n // not belong to another product tab (for example /create and /deploy).\n tabs[0].pageIds.push(...ordered.filter((id) => !claimedIds.has(id)))\n return {\n tabs: tabs.map(({ entry, pageIds }) => ({\n tab: entry.label,\n href: entry.pageId === 'introduction' ? '/' : `/${entry.pageId}`,\n groups: groupsWithinSection(entry.section, [...new Set(pageIds)], entry.label),\n })),\n }\n }\n const sectionNames = [...new Set(ordered\n .filter((id) => id.includes('/'))\n .map((id) => id.split('/', 1)[0]))]\n if (sectionNames.length > 1) {\n const defaultSection = sectionNames.includes('introduction')\n ? 'introduction'\n : sectionNames[0]\n const sections = new Map<string, Array<string>>()\n for (const id of ordered) {\n const section = id.includes('/') ? id.split('/', 1)[0] : defaultSection\n const bucket = sections.get(section) ?? []\n bucket.push(id)\n sections.set(section, bucket)\n }\n return {\n tabs: [...sections].map(([section, pageIds]) => {\n const label = topLevelLabel(section)\n const landingPage = preferredLandingPage(section, pageIds)\n return {\n tab: label,\n ...(landingPage\n ? { href: landingPage === 'introduction' ? '/' : `/${landingPage}` }\n : {}),\n groups: groupsWithinSection(section, pageIds),\n }\n }),\n }\n }\n }\n const buckets = new Map<string, Array<string>>()\n for (const id of ordered) {\n const segment = id.includes('/') ? id.split('/', 1)[0] : 'overview'\n const bucket = buckets.get(segment) ?? []\n bucket.push(id)\n buckets.set(segment, bucket)\n }\n const groups = [...buckets].map(([segment, pageIds]) => ({\n group: segment === 'overview' ? 'Overview' : titleCase(segment),\n pages: pageIds,\n }))\n return { tabs: [{ tab: 'Documentation', groups }] }\n}\n\n/** Exposed for repository discovery and focused unit tests. */\nexport function isDocumentationExtension(filename: string): boolean {\n return ['.md', '.mdx', '.rst', '.txt'].includes(extname(filename).toLowerCase())\n}\n\n/**\n * A source page can be excluded after navigation is projected (invalid MDX,\n * a client-boundary function prop, a duplicate id). Its reference still sits\n * in the projected tabs/groups at that point, across every tab, group, and\n * locale, since the nav tree and the page list are built from the same\n * source config independently. Drop those dangling references here so\n * `thally check` never reports a nav entry with no backing MDX file, and\n * drop any group left with no pages as a result. Shared by every platform's\n * navigation projection (Mintlify, Fern, Docusaurus).\n */\nexport function pruneMissingNavigationPages(\n config: MigrationDocsConfig,\n availableIds: ReadonlySet<string>,\n): MigrationDocsConfig {\n const pruneNodes = (nodes: Array<string | MigrationNavigationGroup>): Array<string | MigrationNavigationGroup> => {\n const seenSiblings = new Set<string>()\n return nodes.flatMap((node): Array<string | MigrationNavigationGroup> => {\n if (typeof node === 'string') {\n // Distinct source files can resolve to one final frontmatter slug.\n // Showing that route twice in one sidebar group is misleading even\n // though both references passed the existence check.\n if (!availableIds.has(node) || seenSiblings.has(node)) return []\n seenSiblings.add(node)\n return [node]\n }\n const pages = pruneNodes(node.pages)\n return pages.length > 0 ? [{ ...node, pages }] : []\n })\n }\n const tabs = config.tabs.flatMap((tab) => {\n const hadPages = (tab.pages?.length ?? 0) > 0 || (tab.groups?.length ?? 0) > 0\n const pages = tab.pages ? pruneNodes(tab.pages) : undefined\n const groups = tab.groups ? (pruneNodes(tab.groups) as Array<MigrationNavigationGroup>) : undefined\n const hasPages = (pages?.length ?? 0) > 0 || (groups?.length ?? 0) > 0\n // A tab that never referenced pages/groups (href-only, api-only) is untouched.\n if (hadPages && !hasPages) return []\n return [{\n ...tab,\n ...(tab.pages ? { pages } : {}),\n ...(tab.groups ? { groups } : {}),\n }]\n })\n return { ...config, tabs }\n}\n","/**\n * Static Fern (`fern/docs.yml`) repository projection. Fern navigation and\n * generator config are plain YAML data files, so this adapter only ever\n * parses them with `yaml` and never imports or executes JavaScript.\n */\n\nimport { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'\nimport { basename, dirname, extname, relative } from 'node:path'\n\nimport { load } from 'cheerio'\nimport { parse as parseYaml } from 'yaml'\n\nimport { isRedirectPathSafe, translateRedirectWildcards } from './navigation.js'\nimport { resolveWithin, resolveWithinRoot } from './path.js'\nimport type {\n MigrationDocsConfig,\n MigrationNavigationGroup,\n MigrationNavigationTab,\n MigrationWarning,\n} from './types.js'\n\nconst MAX_CONFIG_BYTES = 20_000_000\n\n/** Retain safe Fern announcement links without emitting source-controlled HTML. */\nfunction announcementMarkdown(message: string): string {\n const document = load(message)\n document('script, style, iframe, object, embed, svg, math').remove()\n const escapeText = (value: string): string => value\n .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n .replace(/([\\\\`*_\\[\\]{}()!])/g, '\\\\$1')\n const links = new Map<string, string>()\n document('a').each((index, element) => {\n const marker = `THALLYANNOUNCEMENTLINK${index}TOKEN`\n const label = document(element).text().trim()\n const rawHref = document(element).attr('href')?.trim() ?? ''\n let href: string | undefined\n if (/^https?:\\/\\//i.test(rawHref)) {\n try { href = new URL(rawHref).toString() } catch { /* invalid source link becomes text */ }\n } else if (rawHref.startsWith('/') && !rawHref.startsWith('//') && !/[\\\\<>\\s]/.test(rawHref)) {\n href = rawHref\n }\n const destination = href?.replace(/\\(/g, '%28').replace(/\\)/g, '%29')\n links.set(marker, destination && label ? `[${escapeText(label)}](${destination})` : escapeText(label))\n document(element).replaceWith(marker)\n })\n let text = escapeText(document('body').text())\n for (const [marker, link] of links) text = text.replaceAll(marker, link)\n return text.trim()\n}\n\nexport interface FernPageDescriptor {\n /** Path to the referenced page file, relative to the Fern root. */\n sourcePath: string\n navigationId: string\n /** Fern's sidebar label can intentionally differ from the page title. */\n navTitle?: string\n /** Keep routable pages excluded by Fern's `hidden` navigation flag. */\n hidden?: boolean\n}\n\n/** One `api:` navigation node, resolved to the name/tab Thally needs to bind its spec. */\nexport interface FernApiSection {\n /** The node's own value (a display name or, in multi-API repos, a `fern/apis/<name>` identifier). */\n name: string\n /** True when `name` came from an explicit `api-name` field rather than falling back to the `api:` display title. */\n nameExplicit: boolean\n /** Label of the tab that owns this node, if that tab also has other content and survived projection. */\n tabLabel?: string\n /**\n * Route segments (section slugs) leading to this node, used only to\n * disambiguate two `api:` nodes that land on the same `tabLabel` — a\n * \"Production API Reference\" and \"Testnet API Reference\" section both\n * nested under one tab both want that tab's label; without this, the\n * second one silently overwrites the first tab's binding instead of\n * getting its own tab.\n */\n routeSegments: Array<string>\n}\n\nexport interface FernNavigationResult {\n docsConfig: MigrationDocsConfig\n descriptors: Array<FernPageDescriptor>\n warnings: Array<MigrationWarning>\n /** Every `api:` node found in navigation, in document order. A repo can declare several (e.g. a REST and a WebSocket API in separate tabs). */\n apiSections: Array<FernApiSection>\n /** Fern changelog tabs render their entries as a feed at the bare route. */\n changelogIndexes: Array<{ route: string; entries: Array<string> }>\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => ['api', 'cli', 'sdk', 'ui'].includes(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\nfunction readBoundedYaml(path: string): unknown {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('The Fern config is larger than 20 MB and could not be imported.')\n }\n return parseYaml(readFileSync(path, 'utf8'))\n}\n\n/** Read `fern/docs.yml` without executing anything. */\nexport function readFernConfig(fernRoot: string): { config: Record<string, unknown>; sourcePath: string } | null {\n const sourcePath = 'docs.yml'\n const path = resolveWithin(fernRoot, sourcePath)\n if (!existsSync(path) || !lstatSync(path).isFile()) return null\n const config = objectValue(readBoundedYaml(path))\n if (!config) throw new Error('fern/docs.yml must contain an object.')\n return { config, sourcePath }\n}\n\ninterface WalkContext {\n fernRoot: string\n repositoryRoot: string\n descriptors: Array<FernPageDescriptor>\n seenNavigationIds: Set<string>\n /** Every `api:` node seen so far, in document order; `tabLabel` is filled in once its owning tab finishes walking. */\n apiSections: Array<FernApiSection>\n changelogIndexes: Array<{ route: string; entries: Array<string> }>\n warnings: Array<MigrationWarning>\n warningKeys: Set<string>\n /** External navigation leaves cannot live inside Thally groups; keep them as navbar links. */\n externalLinks: Array<{ label: string; href: string }>\n /** Bare tab/section routes with no page of their own, soft-redirected to their first descendant. */\n bareRouteRedirects: Array<{ source: string; destination: string }>\n /** Slugified segment -> the literal explicit `slug` it was derived from, when the two differ (e.g. `baml-client` -> `baml_client`). */\n segmentAliases: Map<string, string>\n /**\n * Directory, relative to `fernRoot` (posix, no trailing slash, '' at the\n * root), that a page's `path` is actually relative to. A product's own\n * config lives under `fern/products/<name>/`, so its pages resolve there\n * rather than at the Fern root, even though the product's *route* segment\n * is unrelated and handled separately via `parentSegments`.\n */\n pathPrefix: string\n hiddenInherited?: boolean\n /**\n * The navigation id that actually owns a page's content, keyed by\n * `sourcePath` — the first nav location a file is registered at. A file\n * registered again at a second nav location (e.g. a Fern page listed\n * under both a guide section and a `slug: baml_client` reference section)\n * gets its own position-derived id recorded in `descriptors` (so a\n * redirect from it can still be built), but the navigation tree itself\n * points that second location at this id, since `repository.ts` creates\n * exactly one page per physical file and the second id never becomes one.\n */\n sourcePathToNavigationId: Map<string, string>\n}\n\nfunction warnOnce(context: WalkContext, key: string, message: string): void {\n if (context.warningKeys.has(key)) return\n context.warningKeys.add(key)\n context.warnings.push({ code: 'unsupported-config', message })\n}\n\nfunction firstLeafId(nodes: Array<string | MigrationNavigationGroup>): string | undefined {\n for (const node of nodes) {\n if (typeof node === 'string') return node\n const nested = firstLeafId(node.pages)\n if (nested) return nested\n }\n return undefined\n}\n\n/** A tab or section with no page of its own still has a public URL that Fern resolves to its first descendant. */\nfunction addBareRouteRedirect(\n segments: Array<string>,\n pages: Array<string | MigrationNavigationGroup>,\n context: WalkContext,\n): void {\n if (segments.length === 0) return\n const destination = firstLeafId(pages)\n const source = segments.join('/')\n if (destination && destination !== source) {\n context.bareRouteRedirects.push({ source: `/${source}`, destination: `/${destination}` })\n }\n}\n\n/** A literal explicit `slug` value is only trusted as a redirect segment when it's already plain URL-safe text. */\nconst FERN_SEGMENT_ALIAS = /^[\\w.-]+$/\n\n/**\n * Fern's own slugifier treats any non-alphanumeric run (including `.`, which\n * Thally's shared `slugifySegment` deliberately preserves for other\n * platforms) as a separator, so Fern gets its own minimal one here.\n */\nfunction fernBasicSlug(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')\n}\n\n/**\n * Fern derives a default slug from a display name by lowercasing, replacing\n * non-alphanumeric runs with hyphens, dropping parentheses, and splitting\n * camelCase/acronym boundaries (`OpenAI` -> `open-ai`, `SDKs` -> `sd-ks`) —\n * confirmed against buildwithfern.com's own \"Configuring slugs\" doc and a\n * live site's sitemap. Only the label fallback needs this; an authored\n * `slug` is used as literal, already-intended path text.\n */\nfunction fernLabelSlug(label: string): string {\n const decamelized = label\n .replace(/[()]/g, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n return fernBasicSlug(decamelized)\n}\n\n/**\n * A Fern tab, section, or page contributes its slugified label as a URL\n * segment by default (confirmed against a live Fern site's sitemap: nested\n * sections with no `slug` field still nest their descendants by title).\n * `slug` overrides the label; `skip-slug: true` omits the segment entirely.\n *\n * An author-written `slug` is intentional URL text (e.g. BAML's `slug:\n * baml_client`, matching its own `baml_client/` folder name) — Fern serves\n * it literally, underscore and all. `fernBasicSlug` still squashes it into\n * Thally's usual hyphenated route (kept as the canonical route: changing it\n * would be a wider behavior change than this warrants), but when the two\n * differ, the literal form is recorded as a segment alias so\n * `fernUnderscoreAliasRedirects` can add a redirect from the original\n * folder-name-shaped link to the route Thally actually uses.\n */\nfunction segmentFor(value: Record<string, unknown>, label: string, context?: WalkContext): string | null {\n if (value['skip-slug'] === true) return null\n // Fern uses an authored empty slug to put a tab at the site root.\n if (typeof value.slug !== 'string') return fernLabelSlug(label) || null\n const explicit = value.slug.trim()\n if (!explicit) return null\n const slugified = fernBasicSlug(explicit)\n if (context && explicit !== slugified && FERN_SEGMENT_ALIAS.test(explicit)) {\n context.segmentAliases.set(slugified, explicit)\n }\n return slugified || null\n}\n\nfunction uniqueNavigationId(base: string, context: WalkContext): string {\n if (!context.seenNavigationIds.has(base)) return base\n let index = 2\n while (context.seenNavigationIds.has(`${base}-${index}`)) index++\n return `${base}-${index}`\n}\n\nfunction registerPageAt(rawPath: string, base: string, context: WalkContext, navTitle?: string, hidden = false): string {\n let sourcePath: string\n try {\n const absolute = resolveWithinRoot(\n context.pathPrefix ? resolveWithinRoot(context.fernRoot, context.pathPrefix, context.repositoryRoot) : context.fernRoot,\n rawPath.trim(),\n context.repositoryRoot,\n )\n sourcePath = relative(context.fernRoot, absolute).replace(/\\\\/g, '/')\n } catch {\n warnOnce(context, `fern-unsafe-page-${rawPath}`, `Fern page path \"${rawPath}\" escapes the repository and was skipped.`)\n return ''\n }\n const navigationId = uniqueNavigationId(base || 'introduction', context)\n context.seenNavigationIds.add(navigationId)\n const isHidden = hidden || context.hiddenInherited === true\n context.descriptors.push({ sourcePath, navigationId, ...(navTitle ? { navTitle } : {}), ...(isHidden ? { hidden: true } : {}) })\n // `repository.ts` creates exactly one page per physical file, keyed off\n // the first nav location that registers it — a file listed at a second\n // nav location (Fern allows the same page under several sections) must\n // not point the tree at this position's own id, which will never become\n // a page. Point it at the id that actually owns the content instead;\n // `fernUnderscoreAliasRedirects` still adds a redirect from this\n // position's own derived route to that kept id, for any old/external\n // link built from it.\n const kept = context.sourcePathToNavigationId.get(sourcePath)\n if (kept) {\n if (!isHidden) {\n const owner = context.descriptors.find((descriptor) => descriptor.navigationId === kept)\n if (owner) owner.hidden = false\n }\n return kept\n }\n context.sourcePathToNavigationId.set(sourcePath, navigationId)\n return navigationId\n}\n\n/** Expand Fern's folder shorthand from actual Markdown files in document order. */\nfunction registerFolder(\n object: Record<string, unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): MigrationNavigationGroup | null {\n const rawPath = String(object.folder).trim()\n let folder: string\n try {\n folder = resolveWithinRoot(\n context.pathPrefix ? resolveWithinRoot(context.fernRoot, context.pathPrefix, context.repositoryRoot) : context.fernRoot,\n rawPath,\n context.repositoryRoot,\n )\n } catch {\n warnOnce(context, `fern-unsafe-folder-${rawPath}`, `Fern folder \"${rawPath}\" escapes the repository and was skipped.`)\n return null\n }\n if (!existsSync(folder) || !lstatSync(folder).isDirectory()) {\n warnOnce(context, `fern-missing-folder-${rawPath}`, `Fern folder \"${rawPath}\" does not exist and was skipped.`)\n return null\n }\n const label = typeof object.title === 'string' && object.title.trim() ? object.title.trim() : titleCase(basename(folder))\n // Folder titles are navigation labels. Fern keeps the directory name in\n // the route unless a slug override is authored.\n const segment = typeof object.slug === 'string' || object['skip-slug'] === true\n ? segmentFor(object, label, context)\n : fernBasicSlug(basename(folder))\n const segments = segment ? [...parentSegments, segment] : parentSegments\n const visit = (directory: string, routeSegments: Array<string>, depth: number): Array<string | MigrationNavigationGroup> => {\n if (depth > 12 || context.descriptors.length >= 5_000) return []\n const pages: Array<string | MigrationNavigationGroup> = []\n const entries = readdirSync(directory, { withFileTypes: true })\n .filter((entry) => !entry.name.startsWith('.') && !entry.isSymbolicLink())\n .sort((left, right) => Number(left.name !== 'index.mdx' && left.name !== 'index.md')\n - Number(right.name !== 'index.mdx' && right.name !== 'index.md') || left.name.localeCompare(right.name))\n for (const entry of entries) {\n const path = resolveWithin(directory, entry.name)\n if (entry.isDirectory()) {\n const nested = visit(path, [...routeSegments, fernBasicSlug(entry.name)], depth + 1)\n if (nested.length) pages.push({ group: titleCase(entry.name), pages: nested })\n } else if (entry.isFile() && ['.md', '.mdx'].includes(extname(entry.name).toLowerCase())) {\n const stem = basename(entry.name, extname(entry.name))\n const pageSegment = stem.toLowerCase() === 'index' ? null : fernBasicSlug(stem)\n const route = [...routeSegments, ...(pageSegment ? [pageSegment] : [])].join('/')\n const source = lstatSync(path).size <= MAX_CONFIG_BYTES ? readFileSync(path, 'utf8') : ''\n const frontmatter = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/)?.[1] ?? ''\n const hidden = /^hidden:\\s*true\\s*$/m.test(frontmatter)\n const registered = registerPageAt(relative(context.fernRoot, path), route, { ...context, pathPrefix: '' }, undefined, hidden)\n if (registered && !hidden && !context.hiddenInherited) pages.push(registered)\n }\n }\n return pages\n }\n const pages = visit(folder, segments, 0)\n if (!pages.length) return null\n addBareRouteRedirect(segments, pages, context)\n return { group: label, pages }\n}\n\nfunction registerPage(\n object: Record<string, unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): string | null {\n if (typeof object.path !== 'string' || !object.path.trim()) return null\n const label = typeof object.page === 'string' && object.page.trim() ? object.page.trim() : 'Untitled'\n const segment = segmentFor(object, label, context)\n const base = [...parentSegments, segment].filter(Boolean).join('/')\n return registerPageAt(object.path, base, context, label, object.hidden === true) || null\n}\n\n/** A `section`/`page`/`link`/`api`/`changelog` node from `layout` or `contents`. */\nfunction convertNode(\n node: unknown,\n parentSegments: Array<string>,\n context: WalkContext,\n): string | MigrationNavigationGroup | null {\n const object = objectValue(node)\n if (!object) return null\n\n if (typeof object.page === 'string') {\n const page = registerPage(object, parentSegments, context)\n return object.hidden === true || context.hiddenInherited ? null : page\n }\n\n if (typeof object.folder === 'string') {\n const folder = registerFolder(object, parentSegments, object.hidden === true ? { ...context, hiddenInherited: true } : context)\n return object.hidden === true || context.hiddenInherited ? null : folder\n }\n\n if (typeof object.section === 'string') {\n const label = object.section\n const segment = segmentFor(object, label, context)\n const segments = segment ? [...parentSegments, segment] : parentSegments\n const contents = Array.isArray(object.contents) ? object.contents : []\n const pages: Array<string | MigrationNavigationGroup> = []\n // A section can also carry its own `path`, making the section itself a\n // clickable landing page hosted at the section's own segment (not a\n // further-nested page segment).\n const hasOwnPath = typeof object.path === 'string' && object.path.trim().length > 0\n if (hasOwnPath) {\n const registered = registerPageAt(object.path as string, segments.join('/'), context, label, object.hidden === true)\n if (registered) pages.push(registered)\n }\n for (const child of contents) {\n const converted = convertNode(child, segments, object.hidden === true ? { ...context, hiddenInherited: true } : context)\n if (converted) pages.push(converted)\n }\n if (pages.length === 0) return null\n // A section without its own `path` still has a public URL at its segment;\n // Fern resolves that bare route to the section's first descendant page.\n if (!hasOwnPath && segment) addBareRouteRedirect(segments, pages, context)\n if (object.hidden === true || context.hiddenInherited) return null\n return {\n group: label,\n ...(typeof object.icon === 'string' ? { icon: object.icon } : {}),\n ...(object.hidden === true ? { hidden: true } : {}),\n pages,\n }\n }\n\n if (typeof object.link === 'string') {\n const label = object.link.trim()\n const rawHref = typeof object.href === 'string' ? object.href.trim() : ''\n // Fern links may appear within a section, while Thally's group schema\n // accepts page ids only. Only absolute web URLs belong in the navbar;\n // canonicalizing through URL also rejects malformed or deceptive hosts.\n let href: string | undefined\n if (/^https?:\\/\\//i.test(rawHref) && !/[\\\\\\u0000-\\u0020\\u007f]/.test(rawHref)) {\n try {\n const url = new URL(rawHref)\n if (['http:', 'https:'].includes(url.protocol) && !url.username && !url.password) href = url.toString()\n } catch { /* An invalid authored link is reported below. */ }\n }\n if (label && href && object.hidden !== true && !context.hiddenInherited) {\n if (!context.externalLinks.some((link) => link.label === label && link.href === href)) {\n context.externalLinks.push({ label, href })\n }\n } else if (!href && object.hidden !== true && !context.hiddenInherited) {\n warnOnce(context, `fern-link-${rawHref}`, `Fern navigation link \"${label}\" has an unsafe or invalid external URL and was skipped.`)\n }\n return null\n }\n\n if (typeof object.api === 'string') {\n // `api` is the display title shown in the nav; `api-name` (when\n // present) is the actual `fern/apis/<name>/` folder name. A repo with\n // `api: Plant API` / `api-name: plants` has no `apis/Plant API`\n // folder, so preferring `api-name` is required to find the spec. A repo\n // can declare several `api:` nodes (e.g. a REST API and a WebSocket API\n // in separate tabs) — each is tracked and resolved independently rather\n // than only ever importing the first one found.\n // Like a section or page, an `api:` node contributes its own slug to the\n // route unless `skip-slug: true` (confirmed against a live Fern site:\n // VapiAI's `api-reference` tab has one `api:` node with `skip-slug:\n // true` served directly at the tab's own route, and a second `Webhooks`\n // node — no skip-slug — served one level deeper, at\n // \".../api-reference/webhooks\"). This is also this node's own auto-\n // generated operation page prefix, used to rewrite in-content links to\n // those pages onto Thally's route.\n const ownSegment = segmentFor(object, object.api, context)\n context.apiSections.push({\n name: typeof object['api-name'] === 'string' ? object['api-name'] : object.api,\n nameExplicit: typeof object['api-name'] === 'string',\n routeSegments: ownSegment ? [...parentSegments, ownSegment] : parentSegments,\n })\n return null\n }\n\n if (typeof object.changelog === 'string') {\n return registerFolder({ folder: object.changelog, title: 'Changelog', 'skip-slug': true }, parentSegments, context)\n }\n\n return null\n}\n\nfunction convertNodes(\n nodes: Array<unknown>,\n parentSegments: Array<string>,\n context: WalkContext,\n): Array<string | MigrationNavigationGroup> {\n return nodes.flatMap((node) => {\n const converted = convertNode(node, parentSegments, context)\n return converted ? [converted] : []\n })\n}\n\nfunction groupsFromConverted(\n converted: Array<string | MigrationNavigationGroup>,\n): Array<MigrationNavigationGroup> {\n const loosePages = converted.filter((entry): entry is string => typeof entry === 'string')\n const groups = converted.filter((entry): entry is MigrationNavigationGroup => typeof entry !== 'string')\n return loosePages.length > 0 ? [{ group: 'Overview', pages: loosePages }, ...groups] : groups\n}\n\n/**\n * Resolve the default Fern version's navigation when no top-level nav\n * exists. `configDir` is the directory `chosen.path` is conventionally\n * relative to (the Fern root for a top-level docs.yml, or a product's own\n * directory for a product config); `context.repositoryRoot` (the whole\n * repository checkout) is the security boundary. A version file is a\n * legitimate Fern layout even when it lives outside `fern/` (e.g. a sibling\n * `docs/` directory referenced as `../docs/index.yml`), so it may resolve\n * anywhere inside the repository, not just under the Fern root — escapes\n * from the repository itself are still rejected. Once a version file loads,\n * its own `path:` entries are relative to *its* directory, not the Fern\n * root, so `pathPrefix` is shifted there for the rest of this config's walk.\n */\nfunction resolveVersionedNavigation(\n config: Record<string, unknown>,\n configDir: string,\n fernRoot: string,\n context: WalkContext,\n): Record<string, unknown> {\n if (Array.isArray(config.navigation)) return config\n if (Array.isArray(config.products)) {\n warnOnce(context, 'fern-products', 'Nested Fern multi-product docs are not supported; only this docs.yml was imported.')\n return config\n }\n if (!Array.isArray(config.versions)) return config\n const versions = config.versions.flatMap((entry) => {\n const version = objectValue(entry)\n return version ? [version] : []\n })\n const chosen = versions.find((version) => version.default === true) ?? versions[0]\n const skipped = versions.filter((version) => version !== chosen)\n .map((version) => (typeof version.version === 'string' ? version.version : undefined))\n .filter((name): name is string => Boolean(name))\n if (skipped.length > 0) {\n warnOnce(\n context,\n 'fern-versions',\n `Only the default Fern version was imported; other versions were skipped: ${skipped.join(', ')}.`,\n )\n }\n if (!chosen || typeof chosen.path !== 'string') return config\n try {\n const versionPath = resolveWithinRoot(configDir, chosen.path, context.repositoryRoot)\n if (!existsSync(versionPath) || !lstatSync(versionPath).isFile()) {\n warnOnce(context, 'fern-version-not-file', `Fern version file \"${chosen.path}\" is not a regular file and was skipped.`)\n return config\n }\n const versionConfig = objectValue(readBoundedYaml(versionPath))\n if (!versionConfig) return config\n context.pathPrefix = relative(fernRoot, dirname(versionPath)).replace(/\\\\/g, '/')\n return { ...config, navigation: versionConfig.navigation, tabs: versionConfig.tabs ?? config.tabs }\n } catch (error) {\n warnOnce(\n context,\n 'fern-version-read-failed',\n `Fern version file \"${chosen.path}\" could not be read (${error instanceof Error ? error.message : String(error)}) and was skipped.`,\n )\n return config\n }\n}\n\n/**\n * Build tabs for one docs config (the top-level docs.yml, or one product's\n * own config), rooted at `routePrefix`. Shared by the plain top-level path\n * and by `projectFernProducts` so both get identical tabbed/flat-navigation\n * and version-resolution handling.\n */\nfunction buildTabsFromConfig(\n rawConfig: Record<string, unknown>,\n configDir: string,\n fernRoot: string,\n routePrefix: Array<string>,\n fallbackTabLabel: string,\n context: WalkContext,\n): Array<MigrationNavigationTab> {\n const config = resolveVersionedNavigation(rawConfig, configDir, fernRoot, context)\n const tabsMeta = objectValue(config.tabs) ?? {}\n const navigation = config.navigation\n\n const isTabbedNavigation = Array.isArray(navigation)\n && navigation.length > 0\n && navigation.every((entry) => typeof objectValue(entry)?.tab === 'string')\n\n if (isTabbedNavigation) {\n return (navigation as Array<Record<string, unknown>>).flatMap((entry): Array<MigrationNavigationTab> => {\n const id = String(entry.tab)\n const meta = objectValue(tabsMeta[id]) ?? {}\n const label = typeof meta['display-name'] === 'string' ? meta['display-name'] : titleCase(id)\n const tabSegment = segmentFor(meta, label, context)\n const segments = [...routePrefix, ...(tabSegment ? [tabSegment] : [])]\n const layout = Array.isArray(entry.layout) ? entry.layout : []\n const sectionsBefore = context.apiSections.length\n const groups = groupsFromConverted(convertNodes(layout, segments, context))\n for (let index = sectionsBefore; index < context.apiSections.length; index += 1) {\n context.apiSections[index].tabLabel ??= label\n }\n if (groups.length === 0 && typeof meta.href === 'string' && /^https?:\\/\\//i.test(meta.href)) {\n return [{ tab: label, href: meta.href }]\n }\n if (groups.length === 0 && typeof meta.changelog === 'string') {\n // A Fern changelog tab names a directory rather than explicit page\n // nodes. Keep every MDX entry, newest dated filename first.\n const changelog = registerFolder({ folder: meta.changelog, title: label, 'skip-slug': true }, segments, context)\n if (changelog) {\n const indexRoute = segments.join('/')\n const descriptors = new Map(context.descriptors.map((descriptor) => [descriptor.navigationId, descriptor]))\n const visiblePages = changelog.pages.filter((page): page is string => typeof page === 'string')\n .filter((page) => !descriptors.get(page)?.hidden)\n // Fern's feed is ordered by publication date, while a directory\n // listing is alphabetical. An overview file may publish at the tab\n // root via frontmatter `slug`, so recognize it before slug remapping.\n const index = visiblePages.find((page) => {\n const descriptor = descriptors.get(page)\n if (!descriptor) return false\n const stem = basename(descriptor.sourcePath, extname(descriptor.sourcePath))\n return page === indexRoute || stem === 'overview' || stem === 'index'\n })\n const entries = visiblePages.filter((page) => page !== index).sort((left, right) => {\n const date = (page: string): string => descriptors.get(page)?.sourcePath.match(/\\d{4}-\\d{2}-\\d{2}/)?.[0] ?? ''\n return date(right).localeCompare(date(left)) || left.localeCompare(right)\n })\n // Fern renders the entries in the feed, not in its sidebar. Keep\n // each article routable for its permalink while showing only the\n // feed itself in the navigation tree.\n for (const entryId of entries) {\n const descriptor = descriptors.get(entryId)\n if (descriptor) descriptor.hidden = true\n }\n changelog.pages = [index ?? indexRoute]\n context.changelogIndexes.push({ route: indexRoute, entries })\n const latest = index ?? firstLeafId(changelog.pages)\n const bareRouteIndex = context.bareRouteRedirects.findIndex((redirect) => redirect.source === `/${indexRoute}`)\n const indexDescriptor = index ? descriptors.get(index) : undefined\n const indexSource = indexDescriptor && lstatSync(resolveWithinRoot(context.fernRoot, indexDescriptor.sourcePath, context.repositoryRoot)).size <= MAX_CONFIG_BYTES\n ? readFileSync(resolveWithinRoot(context.fernRoot, indexDescriptor.sourcePath, context.repositoryRoot), 'utf8') : ''\n const indexFrontmatter = indexSource.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/)?.[1] ?? ''\n const indexSlug = indexFrontmatter.match(/^slug:\\s*[\"']?([^\\s\"']+)[\"']?\\s*$/m)?.[1]?.replace(/^\\/+|\\/+$/g, '')\n const hasBarePage = index === indexRoute || indexSlug === indexRoute\n if (bareRouteIndex >= 0 && hasBarePage) context.bareRouteRedirects.splice(bareRouteIndex, 1)\n else if (latest && bareRouteIndex >= 0) context.bareRouteRedirects[bareRouteIndex].destination = `/${latest}`\n return [{ tab: label, groups: [changelog] }]\n }\n }\n if (groups.length === 0) return []\n if (segments.length > 0) addBareRouteRedirect(segments, groups, context)\n return [{\n tab: label,\n ...(typeof meta.icon === 'string' ? { icon: meta.icon } : {}),\n groups,\n }]\n })\n }\n if (Array.isArray(navigation)) {\n const sectionsBefore = context.apiSections.length\n const groups = groupsFromConverted(convertNodes(navigation, routePrefix, context))\n for (let index = sectionsBefore; index < context.apiSections.length; index += 1) {\n context.apiSections[index].tabLabel ??= fallbackTabLabel\n }\n if (groups.length > 0) {\n if (routePrefix.length > 0) addBareRouteRedirect(routePrefix, groups, context)\n return [{ tab: fallbackTabLabel, groups }]\n }\n }\n return []\n}\n\n/**\n * Project Fern's `products:` (a docs.yml that fans out into several\n * independently-navigable products, e.g. buildwithfern.com/learn) into one\n * top-level tab per product, each routed under its own `slug`/display-name\n * segment and reading its pages from its own `fern/products/<name>/`\n * directory.\n */\nfunction projectFernProducts(\n rawProducts: Array<unknown>,\n fernRoot: string,\n context: WalkContext,\n): Array<MigrationNavigationTab> {\n return rawProducts.flatMap((entry) => {\n const product = objectValue(entry)\n const rawPath = typeof product?.path === 'string' ? product.path.trim() : ''\n if (!product || !rawPath) return []\n const label = typeof product['display-name'] === 'string' && product['display-name'].trim()\n ? product['display-name'].trim()\n : 'Product'\n let productPath: string\n try {\n productPath = resolveWithin(fernRoot, rawPath)\n } catch {\n warnOnce(context, `fern-product-unsafe-${rawPath}`, `Fern product \"${label}\" path \"${rawPath}\" is unsafe and was skipped.`)\n return []\n }\n if (!existsSync(productPath) || !lstatSync(productPath).isFile()) {\n warnOnce(context, `fern-product-missing-${rawPath}`, `Fern product \"${label}\" path \"${rawPath}\" does not exist and was skipped.`)\n return []\n }\n let productConfig: Record<string, unknown> | null\n try {\n productConfig = objectValue(readBoundedYaml(productPath))\n } catch (error) {\n warnOnce(\n context,\n `fern-product-read-failed-${rawPath}`,\n `Fern product \"${label}\" could not be read (${error instanceof Error ? error.message : String(error)}) and was skipped.`,\n )\n return []\n }\n if (!productConfig) return []\n const productDir = dirname(productPath)\n const routeSegment = segmentFor(product, label, context)\n const priorPrefix = context.pathPrefix\n context.pathPrefix = relative(fernRoot, productDir).replace(/\\\\/g, '/')\n try {\n return buildTabsFromConfig(\n productConfig,\n productDir,\n fernRoot,\n routeSegment ? [routeSegment] : [],\n label,\n context,\n )\n } finally {\n context.pathPrefix = priorPrefix\n }\n })\n}\n\n/** Project a Fern `docs.yml` navigation tree into Thally tabs/groups. */\nexport function projectFernNavigation(input: {\n config: Record<string, unknown>\n fernRoot: string\n /**\n * The whole repository checkout — the security boundary for anything a\n * config file references (e.g. a `versions:` file living outside\n * `fern/`). Defaults to `fernRoot` for callers with no wider repository\n * context (e.g. unit tests), which reproduces the previous fernRoot-only\n * confinement.\n */\n repositoryRoot?: string\n}): FernNavigationResult {\n const context: WalkContext = {\n fernRoot: input.fernRoot,\n repositoryRoot: input.repositoryRoot ?? input.fernRoot,\n descriptors: [],\n seenNavigationIds: new Set(),\n apiSections: [],\n changelogIndexes: [],\n warnings: [],\n warningKeys: new Set(),\n externalLinks: [],\n bareRouteRedirects: [],\n segmentAliases: new Map(),\n pathPrefix: '',\n sourcePathToNavigationId: new Map(),\n }\n const config = input.config\n const hasProducts = Array.isArray(config.products) && config.products.length > 0 && !Array.isArray(config.navigation)\n const tabs = hasProducts\n ? projectFernProducts(config.products as Array<unknown>, input.fernRoot, context)\n : buildTabsFromConfig(config, input.fernRoot, input.fernRoot, [], 'Documentation', context)\n\n if (tabs.length === 0) {\n context.warnings.push({\n code: 'unsupported-config',\n message: 'Fern navigation could not be projected; generated navigation will be used.',\n })\n }\n\n const navbarLinks = Array.isArray(config['navbar-links'])\n ? (config['navbar-links'] as Array<unknown>).flatMap((entry) => {\n const link = objectValue(entry)\n const href = typeof link?.url === 'string'\n ? link.url\n : typeof link?.href === 'string' ? link.href : typeof link?.value === 'string' ? link.value : undefined\n const label = typeof link?.text === 'string'\n ? link.text\n : typeof link?.label === 'string' ? link.label : link?.type === 'github' ? 'GitHub' : undefined\n return href && label ? [{ label, href, ...(link?.type === 'github' ? { type: 'github' as const } : {}) }] : []\n })\n : []\n for (const link of context.externalLinks) {\n if (!navbarLinks.some((existing) => existing.label === link.label && existing.href === link.href)) {\n navbarLinks.push(link)\n }\n }\n const announcement = objectValue(config.announcement)\n const announcementMessage = typeof announcement?.message === 'string'\n ? announcement.message.trim()\n : ''\n // Fern permits HTML announcements; reduce them to escaped text and vetted\n // links before the Markdown-capable Thally banner renders the result.\n const bannerContent = announcementMarkdown(announcementMessage)\n\n const redirects = Array.isArray(config.redirects)\n ? (config.redirects as Array<unknown>).flatMap((value) => {\n const redirect = objectValue(value)\n if (!redirect || typeof redirect.source !== 'string' || typeof redirect.destination !== 'string') return []\n const rawSource = redirect.source.trim()\n const rawDestination = redirect.destination.trim()\n if (!isRedirectPathSafe(rawSource, rawDestination)) return []\n const translated = translateRedirectWildcards(rawSource, rawDestination)\n if (!translated) {\n warnOnce(\n context,\n `fern-redirect-wildcard-${rawSource}`,\n `Redirect from ${rawSource} uses a wildcard Next.js cannot express and was dropped.`,\n )\n return []\n }\n return [{\n source: translated.source,\n destination: translated.destination,\n ...(typeof redirect.permanent === 'boolean' ? { permanent: redirect.permanent } : {}),\n }]\n })\n : []\n\n const authoredSources = new Set(redirects.map((redirect) => redirect.source))\n const knownIds = new Set(context.descriptors.map((descriptor) => descriptor.navigationId))\n // The id that actually owns a descriptor's page content — itself, unless\n // the same source file was registered at an earlier nav location too, in\n // which case `registerPageAt` already pointed the tree at that earlier\n // id and this descriptor's own id never becomes a real page. Every\n // redirect destination must resolve through this, never a descriptor's\n // raw `navigationId`, or it targets a route that doesn't exist.\n const keptNavigationId = (descriptor: FernPageDescriptor): string => (\n context.sourcePathToNavigationId.get(descriptor.sourcePath) ?? descriptor.navigationId\n )\n // A page whose route includes a segment Fern derived from an explicit\n // `slug` that got hyphenated (see `segmentFor`) is also reachable on the\n // live Fern site at its literal, unslugified form (Fern's own routing is\n // file/slug-based and tolerates it) — e.g. BAML's `slug: baml_client`\n // means both `/ref/baml-client/...` (Thally's route) and\n // `/ref/baml_client/...` (in-body links, matching the folder name) are\n // live. Add one redirect per affected page so those in-body links keep\n // resolving instead of 404ing after migration.\n const segmentAliasRedirects = context.segmentAliases.size > 0\n ? context.descriptors.flatMap((descriptor) => {\n const segments = descriptor.navigationId.split('/')\n let changed = false\n const aliased = segments.map((segment) => {\n const literal = context.segmentAliases.get(segment)\n if (!literal) return segment\n changed = true\n return literal\n })\n if (!changed) return []\n const source = `/${aliased.join('/')}`\n const destination = `/${keptNavigationId(descriptor)}`\n if (source === destination || knownIds.has(aliased.join('/'))) return []\n return [{ source, destination }]\n })\n : []\n // A source file registered at more than one nav location (a Fern page\n // listed under both a guide section and a `slug: baml_client` reference\n // section, say) keeps exactly one page, at the first location's route —\n // Fern itself serves the content at every route it's registered under, so\n // every other location's own derived route redirects to the kept one\n // instead of 404ing.\n const duplicateNavRedirects = context.descriptors.flatMap((descriptor) => {\n const kept = keptNavigationId(descriptor)\n if (kept === descriptor.navigationId) return []\n return [{ source: `/${descriptor.navigationId}`, destination: `/${kept}` }]\n })\n const allRedirects = [\n ...redirects,\n ...context.bareRouteRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ...segmentAliasRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ...duplicateNavRedirects.filter((redirect) => !authoredSources.has(redirect.source)),\n ]\n\n // Two `api:` nodes both nested under the same top-level tab (e.g.\n // Paradex's \"Production API Reference\" and \"Testnet API Reference\"\n // sections, both inside a `portal` tab) get the same `tabLabel` from the\n // loop above — Thally's schema allows only one `.api` per tab, so the\n // second would otherwise silently overwrite the first tab's binding.\n // Disambiguate every collision after the fact (the first claimant keeps\n // the plain tab label) using the node's own section route, which is\n // exactly what differs between them.\n const claimedTabLabels = new Set<string>()\n const disambiguatedApiSections = context.apiSections.map((section) => {\n if (!section.tabLabel || !claimedTabLabels.has(section.tabLabel)) {\n if (section.tabLabel) claimedTabLabels.add(section.tabLabel)\n return section\n }\n const distinguishingSegment = section.routeSegments.at(-1)\n let tabLabel = distinguishingSegment ? `${section.tabLabel}: ${titleCase(distinguishingSegment)}` : section.tabLabel\n // The route segment can itself title-case back to the tab's own label\n // (e.g. a section nested under a route segment also called\n // \"api-reference\"), producing a redundant \"API Reference: API\n // Reference\" name, or the segment-based label can still collide with\n // another section's. Either way, fall back to a plain ordinal suffix\n // instead of shipping a confusing or still-colliding tab name.\n if (!tabLabel || tabLabel === `${section.tabLabel}: ${section.tabLabel}` || claimedTabLabels.has(tabLabel)) {\n let ordinal = 2\n let candidate = `${section.tabLabel} (${ordinal})`\n while (claimedTabLabels.has(candidate)) {\n ordinal += 1\n candidate = `${section.tabLabel} (${ordinal})`\n }\n tabLabel = candidate\n }\n claimedTabLabels.add(tabLabel)\n return { ...section, tabLabel }\n })\n\n return {\n docsConfig: {\n tabs,\n ...(bannerContent ? { banner: { content: bannerContent, dismissible: true } } : {}),\n ...(navbarLinks.length > 0 ? { navbar: { links: navbarLinks } } : {}),\n ...(allRedirects.length > 0 ? { redirects: allRedirects } : {}),\n },\n descriptors: context.descriptors,\n warnings: context.warnings,\n apiSections: disambiguatedApiSections,\n changelogIndexes: context.changelogIndexes,\n }\n}\n","/** Render canonical migration bundles into a portable Thally repository tree. */\n\nimport { mergeComponentRegistry } from './components.js'\n\nimport type {\n MigrationBundle,\n MigrationDocsConfig,\n MigrationNavigationGroup,\n RenderedMigrationFile,\n} from './types.js'\n\nfunction yamlString(value: string): string {\n return JSON.stringify(value.replace(/\\s+/g, ' ').trim())\n}\n\nfunction renderPage(bundle: MigrationBundle, page: MigrationBundle['pages'][number]): string {\n return [\n '---',\n `title: ${yamlString(page.title)}`,\n page.navTitle ? `navTitle: ${yamlString(page.navTitle)}` : null,\n `description: ${yamlString(page.description)}`,\n page.descriptionPlacement === 'body' ? 'descriptionPlacement: body' : null,\n page.badge ? `badge: ${yamlString(page.badge)}` : null,\n page.keywords.length > 0 ? `keywords: [${page.keywords.map(yamlString).join(', ')}]` : null,\n page.mode ? `mode: ${yamlString(page.mode)}` : null,\n page.hidden ? 'hidden: true' : null,\n page.noindex ? 'noindex: true' : null,\n page.openapi ? `openapi: ${yamlString(page.openapi)}` : null,\n bundle.sourceKind === 'url' ? `source: ${yamlString(page.source)}` : null,\n '---',\n '',\n page.body,\n '',\n ].filter((line) => line !== null).join('\\n')\n}\n\n/** Merge imported tabs into an existing site without duplicating changelog tabs. */\nexport function mergeMigrationConfig(\n existing: MigrationDocsConfig,\n incoming: MigrationDocsConfig,\n): MigrationDocsConfig {\n const tabs = existing.tabs.filter((tab) => tab.tab.toLowerCase() !== 'changelog')\n const names = new Set(tabs.map((tab) => tab.tab.toLowerCase()))\n const seenPages = new Set<string>()\n function recordPages(pages: Array<string | MigrationNavigationGroup> = []): void {\n for (const page of pages) {\n if (typeof page === 'string') seenPages.add(page)\n else recordPages(page.pages)\n }\n }\n for (const tab of tabs) {\n recordPages(tab.pages)\n recordPages(tab.groups)\n }\n function uniquePages(\n pages: Array<string | MigrationNavigationGroup> = [],\n ): Array<string | MigrationNavigationGroup> {\n return pages.flatMap<string | MigrationNavigationGroup>((page) => {\n if (typeof page === 'string') {\n if (seenPages.has(page)) return []\n seenPages.add(page)\n return [page]\n }\n const children = uniquePages(page.pages)\n return children.length > 0 ? [{ ...page, pages: children }] : []\n })\n }\n function uniqueGroups(\n groups: Array<MigrationNavigationGroup> | undefined,\n ): Array<MigrationNavigationGroup> {\n return uniquePages(groups ?? []) as Array<MigrationNavigationGroup>\n }\n for (const tab of incoming.tabs) {\n if (tab.tab.toLowerCase() === 'changelog') continue\n const uniqueTab = {\n ...tab,\n ...(tab.pages ? { pages: uniquePages(tab.pages) } : {}),\n ...(tab.groups ? { groups: uniqueGroups(tab.groups) } : {}),\n }\n if ((tab.pages || tab.groups)\n && !uniqueTab.pages?.length\n && !uniqueTab.groups?.length\n && !tab.href\n && !tab.api) continue\n if (!names.has(tab.tab.toLowerCase())) {\n tabs.push(uniqueTab)\n names.add(tab.tab.toLowerCase())\n continue\n }\n const target = tabs.find((item) => item.tab.toLowerCase() === tab.tab.toLowerCase())\n if (!target) continue\n const incomingRootNodes = [\n ...(uniqueTab.pages ?? []),\n ...(uniqueTab.groups ?? []),\n ]\n if (uniqueTab.pages?.length) {\n target.pages = [...(target.pages ?? target.groups ?? []), ...incomingRootNodes]\n delete target.groups\n } else if (uniqueTab.groups?.length) {\n if (target.pages) target.pages = [...target.pages, ...uniqueTab.groups]\n else target.groups = [...(target.groups ?? []), ...uniqueTab.groups]\n }\n }\n const changelog = existing.tabs.find((tab) => tab.tab.toLowerCase() === 'changelog')\n ?? incoming.tabs.find((tab) => tab.tab.toLowerCase() === 'changelog')\n if (changelog) tabs.push(changelog)\n const i18n = existing.i18n || incoming.i18n\n ? {\n defaultLocale: existing.i18n?.defaultLocale ?? incoming.i18n?.defaultLocale ?? 'en',\n locales: [...new Map(\n [...(existing.i18n?.locales ?? []), ...(incoming.i18n?.locales ?? [])]\n .map((locale) => [locale.code, locale]),\n ).values()],\n }\n : undefined\n return {\n ...incoming,\n ...existing,\n tabs,\n // Collection presentation belongs to the imported information\n // architecture; starter defaults must not coerce source dropdowns to tabs.\n navigation: incoming.navigation ?? existing.navigation,\n ...(i18n ? { i18n } : {}),\n }\n}\n\n/** Materialize every canonical page, asset, and config as repository file changes. */\nexport function renderMigrationFiles(\n bundle: MigrationBundle,\n options: { existingConfig?: MigrationDocsConfig; existingComponentRegistry?: string } = {},\n): Array<RenderedMigrationFile> {\n const config = options.existingConfig\n ? mergeMigrationConfig(options.existingConfig, bundle.docsConfig)\n : bundle.docsConfig\n return [\n ...bundle.pages.map((page) => ({\n path: `src/content/${page.id}.mdx`,\n content: renderPage(bundle, page),\n })),\n ...bundle.assets.map((asset) => ({ path: `public/${asset.path}`, content: asset.content })),\n ...(bundle.componentFiles ?? []).flatMap((file) => file.path === 'src/mdx/custom-components.tsx'\n && options.existingComponentRegistry !== undefined && typeof file.content === 'string'\n ? mergeComponentRegistry(options.existingComponentRegistry, file.content)\n : [file]),\n { path: 'docs.json', content: `${JSON.stringify(config, null, 2)}\\n` },\n ]\n}\n","/**\n * Public URL adapter for the shared migration engine. Discovery prefers\n * machine-readable Markdown and sitemaps, remains scoped to the submitted docs\n * path, then falls back to bounded navigation crawling and HTML extraction.\n */\n\nimport { load } from 'cheerio'\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport TurndownService from 'turndown'\nimport { unified } from 'unified'\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml'\n\nimport { parseMarkdownPage } from './mdx.js'\nimport { addMintlifyDirectoryRedirects, buildNavigationFromPages, projectMintlifyNavigation } from './navigation.js'\nimport { pageIdFromReference } from './path.js'\nimport type {\n MigrationBundle,\n MigrationFetcher,\n MigrationFetchResponse,\n MigrationNavigationGroup,\n MigrationPage,\n MigrationPlatform,\n MigrationWarning,\n} from './types.js'\n\nconst DEFAULT_MAX_PAGES = 1_000\nconst DEFAULT_MAX_TOTAL_BYTES = 100_000_000\nconst MAX_DISCOVERED_URLS = 5_000\nconst MAX_LOCAL_RESPONSE_BYTES = 2_000_000\nconst MAX_SITEMAP_DOCUMENTS = 25\nconst PORTABLE_MDX_COMPONENTS = new Set([\n 'Accordion', 'AccordionGroup', 'Badge', 'Callout', 'Card', 'CardGroup',\n 'Check', 'CodeBlock', 'CodeGroup', 'Color', 'Column', 'Columns', 'ContentPanel', 'Danger', 'Error', 'Expandable',\n 'Agent', 'AgentPrompt', 'Banner', 'BannerPreview', 'Embed', 'File', 'Folder', 'Frame', 'GitHub', 'Github', 'Hero', 'Human',\n 'Icon', 'Info', 'InlinePanel', 'InlineRequestExample', 'InlineResponseExample',\n 'Latex', 'LegacyView', 'LiteYouTubeEmbed', 'MDX', 'Mermaid', 'Note', 'Panel', 'ParamField', 'Prompt',\n 'PromptAssistant', 'PromptUser',\n 'RequestExample', 'ResponseExample', 'ResponseField', 'Step', 'Steps',\n 'Tab', 'Tabs', 'Terminal', 'TerminalInput', 'TerminalOutput', 'Tile', 'TileGroup',\n 'Tip', 'Tooltip', 'Tree', 'Update', 'Video', 'View', 'Visibility', 'Warning', 'YouTube',\n])\nconst LOCALE_CODES = new Set([\n 'ar', 'cs', 'da', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hi', 'hu', 'id',\n 'it', 'ja', 'ko', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv',\n 'th', 'tr', 'uk', 'vi', 'zh', 'pt-br', 'zh-hans', 'zh-hant',\n])\nconst PORTABLE_URL_PROPS = 'href|src|img|primaryHref|secondaryHref'\nconst PORTABLE_URL_PROP_NAMES = new Set(PORTABLE_URL_PROPS.split('|'))\nconst remoteMarkdownParser = unified().use(remarkParse).use(remarkMdx)\n\ninterface RemoteMarkdownAttributeValue {\n type: string\n value: string\n}\n\ninterface RemoteMarkdownAttribute {\n type: string\n name?: string\n value?: string | null | RemoteMarkdownAttributeValue\n}\n\ninterface RemoteMarkdownNode {\n type: string\n alt?: string | null\n attributes?: Array<RemoteMarkdownAttribute>\n identifier?: string\n url?: string\n value?: string\n children?: Array<RemoteMarkdownNode>\n position?: {\n start: { offset?: number }\n end: { offset?: number }\n }\n}\n\ninterface EmbeddedOpenApiFragment {\n method: string\n path: string\n document: Record<string, unknown>\n}\n\nexport interface UrlMigrationOptions {\n sourceUrl: string\n /** Explicit caller selection; omitted callers retain source auto-detection. */\n platform?: MigrationPlatform\n fetcher?: MigrationFetcher\n maxPages?: number\n concurrency?: number\n maxTotalBytes?: number\n}\n\n/** Validate the transport-level shape of a docs URL; hosted callers add SSRF checks. */\nexport function validateMigrationUrl(value: string): URL {\n let url: URL\n try {\n url = new URL(value)\n } catch {\n throw new Error('Enter a complete documentation URL, including https://.')\n }\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new Error('Documentation imports support only HTTP and HTTPS URLs.')\n }\n if (url.username || url.password) throw new Error('Documentation URLs cannot contain credentials.')\n url.hash = ''\n return url\n}\n\nasync function readResponseBody(response: Response): Promise<string> {\n const contentLength = Number(response.headers.get('content-length') ?? 0)\n if (contentLength > MAX_LOCAL_RESPONSE_BYTES) throw new Error('A documentation response exceeded the 2 MB import limit.')\n if (!response.body) return ''\n const reader = response.body.getReader()\n const chunks: Array<Uint8Array> = []\n let size = 0\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > MAX_LOCAL_RESPONSE_BYTES) {\n await reader.cancel()\n throw new Error('A documentation response exceeded the 2 MB import limit.')\n }\n chunks.push(value)\n }\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(body)\n}\n\n/** Fetch implementation for local CLI usage. Cloud injects its pinned network boundary. */\nexport const defaultMigrationFetcher: MigrationFetcher = async (url, request) => {\n const response = await fetch(url, {\n headers: {\n Accept: request.accept,\n 'User-Agent': 'Thally-Migrate/1.0 (+https://thally.io)',\n },\n redirect: 'follow',\n signal: AbortSignal.timeout(15_000),\n })\n if (!response.ok) throw new Error(`Documentation server returned ${response.status}.`)\n return {\n finalUrl: new URL(response.url),\n body: await readResponseBody(response),\n contentType: response.headers.get('content-type') ?? '',\n headers: Object.fromEntries(response.headers.entries()),\n }\n}\n\nfunction docsScopePath(source: URL): string {\n const path = source.pathname.replace(/\\/+$/, '') || '/'\n if (path === '/') return '/'\n const segments = path.split('/').filter(Boolean)\n return `/${segments.length > 1 ? segments[0] : segments.join('/')}`\n}\n\nfunction machineIndexScopePath(\n source: URL,\n documents: Array<MigrationFetchResponse | null>,\n): string | null {\n const candidates = new Set<string>()\n for (const document of documents) {\n if (!document) continue\n const references = [...headerLinks(document)]\n if (/html/i.test(document.contentType)) {\n const $ = load(document.body)\n references.push(...$('link[href], a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter((href) => /\\/(?:llms(?:-full)?\\.txt|sitemap\\.xml)(?:[?#]|$)/i.test(href)))\n }\n for (const reference of references) {\n try {\n const indexUrl = new URL(reference, document.finalUrl)\n if (indexUrl.origin !== source.origin) continue\n const scope = indexUrl.pathname.replace(/\\/(?:llms(?:-full)?\\.txt|sitemap\\.xml)$/i, '') || '/'\n if (isInScope(source, source, scope)) candidates.add(scope)\n } catch {\n // Malformed discovery hints are ignored just like malformed page links.\n }\n }\n }\n return [...candidates].sort((left, right) => right.length - left.length)[0] ?? null\n}\n\nfunction isInScope(url: URL, source: URL, scopePath: string): boolean {\n if (url.origin !== source.origin || !['http:', 'https:'].includes(url.protocol)) return false\n const path = url.pathname.replace(/\\/+$/, '') || '/'\n if (scopePath === '/') return true\n return path === scopePath || path === `${scopePath}.md` || path.startsWith(`${scopePath}/`)\n}\n\nfunction normalizeCandidate(value: string, base: URL, source: URL, scopePath: string): URL | null {\n try {\n const url = new URL(value, base)\n url.hash = ''\n if (!isInScope(url, source, scopePath)) return null\n if (url.pathname.startsWith('/cdn-cgi/')) return null\n if (/\\/(?:llms(?:-full)?|robots)\\.txt$/i.test(url.pathname)\n || /\\/sitemap\\.xml$/i.test(url.pathname)) return null\n if (/\\.(?:avif|bmp|gif|ico|jpe?g|mp[34]|pdf|png|svg|ya?ml|webm|webp|zip)$/i.test(url.pathname)\n || /\\/(?:openapi|swagger|asyncapi)[^/]*\\.json$/i.test(url.pathname)) return null\n return url\n } catch {\n return null\n }\n}\n\nfunction candidateIdentity(url: URL): string {\n const pathname = url.pathname.replace(/\\.mdx?$/i, '').replace(/\\/+$/, '') || '/'\n return `${url.origin}${pathname}${url.search}`\n}\n\nfunction pageIdForUrl(url: URL, scopePath: string): string | null {\n let path = url.pathname.replace(/\\/+$/, '')\n if (scopePath !== '/') {\n if (path === `${scopePath}.md`) path = ''\n else if (path === scopePath) path = ''\n else if (path.startsWith(`${scopePath}/`)) path = path.slice(scopePath.length + 1)\n }\n return pageIdFromReference(path.replace(/^\\/+/, '') || 'introduction', true)\n}\n\nfunction canonicalLocalizedPageId(id: string): string {\n const [segment, ...rest] = id.split('/')\n if (LOCALE_CODES.has(segment)) return rest.length > 0 ? id : `${segment}/introduction`\n for (const locale of LOCALE_CODES) {\n if (segment !== `${locale}-api-reference`) continue\n return [locale, 'api-reference', ...rest].join('/')\n }\n return id\n}\n\nfunction detectUrlPlatform(document: MigrationFetchResponse): MigrationPlatform {\n const headers = Object.entries(document.headers ?? {})\n .map(([key, value]) => `${key}:${value ?? ''}`)\n .join(' ')\n const value = `${document.body.slice(0, 200_000)} ${headers}`.toLowerCase()\n if (value.includes('__mintlify') || value.includes('/mintlify-assets/')\n || value.includes('x-mintlify-') || value.includes('/_mintlify/')) return 'mintlify'\n if (value.includes('docusaurus') || value.includes('__docusaurus')) return 'docusaurus'\n if (value.includes('gitbook')) return 'gitbook'\n if (value.includes('nextra')) return 'nextra'\n if (value.includes('vitepress')) return 'vitepress'\n if (value.includes('starlight')) return 'starlight'\n return 'generic'\n}\n\nfunction jsonObjectAfterKey(value: string, key: string): Record<string, unknown> | null {\n let cursor = 0\n const marker = `\"${key}\":`\n while (cursor < value.length) {\n const markerIndex = value.indexOf(marker, cursor)\n if (markerIndex < 0) return null\n let start = markerIndex + marker.length\n while (/\\s/.test(value[start] ?? '')) start += 1\n if (value[start] !== '{') {\n cursor = start + 1\n continue\n }\n let depth = 0\n let isQuoted = false\n let isEscaped = false\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (isQuoted) {\n if (isEscaped) isEscaped = false\n else if (character === '\\\\') isEscaped = true\n else if (character === '\"') isQuoted = false\n continue\n }\n if (character === '\"') {\n isQuoted = true\n continue\n }\n if (character === '{') depth += 1\n if (character === '}') {\n depth -= 1\n if (depth !== 0) continue\n try {\n const parsed = JSON.parse(value.slice(start, index + 1)) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : null\n } catch {\n break\n }\n }\n }\n cursor = start + 1\n }\n return null\n}\n\n/**\n * Current Mintlify themes embed the resolved docs config and scoped navigation\n * in React Flight. Reading that data is substantially more faithful than\n * inferring information architecture from whichever responsive nav is visible.\n */\nfunction embeddedMintlifyConfig(body: string): Record<string, unknown> | null {\n const $ = load(body)\n const flightPayloads: Array<string> = []\n $('script').each((_index, element) => {\n const script = $(element).text()\n for (const match of script.matchAll(/self\\.__next_f\\.push\\(\\[1,(\"(?:\\\\.|[^\"\\\\])*\")\\]\\)/g)) {\n try {\n const payload = JSON.parse(match[1])\n if (typeof payload === 'string') flightPayloads.push(payload)\n } catch {\n // Older or customized shells fall back to bounded DOM inference.\n }\n }\n })\n if (flightPayloads.length === 0) return null\n const payload = flightPayloads.join('\\n')\n const docsConfig = jsonObjectAfterKey(payload, 'docsConfig')\n const scopedNavigation = jsonObjectAfterKey(payload, 'scopedNav')\n if (!docsConfig && !scopedNavigation) return null\n return {\n ...(docsConfig ?? {}),\n ...(scopedNavigation ? { navigation: scopedNavigation } : {}),\n }\n}\n\nfunction plainDescription(value: string): string {\n return value\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, '$1')\n .replace(/[`*_>#-]/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 240)\n}\n\nfunction withoutFencedCode(body: string): string {\n let fenceCharacter = ''\n let fenceLength = 0\n return body.split('\\n').map((line) => {\n const match = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (match && !fenceCharacter) {\n fenceCharacter = match[1][0]\n fenceLength = match[1].length\n return ''\n }\n if (match && match[1][0] === fenceCharacter && match[1].length >= fenceLength\n && match[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n return ''\n }\n return fenceCharacter ? '' : line\n }).join('\\n')\n}\n\nfunction eventHandlerPropEnd(value: string, start: number): number | null {\n const opening = value[start]\n if (opening === '\"' || opening === \"'\") {\n for (let index = start + 1; index < value.length; index += 1) {\n if (value[index] === opening && value[index - 1] !== '\\\\') return index + 1\n }\n return null\n }\n if (opening !== '{') {\n const match = value.slice(start).match(/^[^\\s>]+/)\n return match ? start + match[0].length : null\n }\n let depth = 0\n let quote = ''\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (quote) {\n if (character === quote && value[index - 1] !== '\\\\') quote = ''\n continue\n }\n if (character === '\"' || character === \"'\" || character === '`') {\n quote = character\n continue\n }\n if (character === '{') depth += 1\n if (character === '}') {\n depth -= 1\n if (depth === 0) return index + 1\n }\n }\n return null\n}\n\nfunction stripEventHandlerProps(line: string): string {\n const matcher = /\\s+on[A-Z][A-Za-z0-9]*\\s*=\\s*/g\n let cursor = 0\n let result = ''\n for (const match of line.matchAll(matcher)) {\n const start = match.index\n const valueStart = start + match[0].length\n const end = eventHandlerPropEnd(line, valueStart)\n if (end === null) continue\n result += line.slice(cursor, start)\n cursor = end\n }\n return cursor === 0 ? line : `${result}${line.slice(cursor)}`\n}\n\nfunction isSafePortableUrl(value: string): boolean {\n try {\n const parsed = new URL(value, 'https://relative.thally.invalid')\n return ['http:', 'https:', 'mailto:', 'tel:'].includes(parsed.protocol)\n } catch {\n return false\n }\n}\n\nfunction decodeHtmlAttribute(value: string): string {\n const document = load(`<i data-thally-value=\"${value.replace(/\"/g, '"')}\"></i>`)\n return document('i').attr('data-thally-value') ?? ''\n}\n\n/** Escape imported copy for Markdown text and MDX's additional delimiters. */\nfunction escapeMarkdownText(value: string, escapeTableSeparator = false): string {\n let escaped = ''\n for (const character of value) {\n if (character === '\\\\') escaped += '\\\\\\\\'\n else if (character === '[' || character === ']') escaped += `\\\\${character}`\n else if (character === '<') escaped += '<'\n else if (character === '>') escaped += '>'\n else if (character === '{') escaped += '{'\n else if (character === '}') escaped += '}'\n else if (character === '|' && escapeTableSeparator) escaped += '\\\\|'\n else escaped += character\n }\n return escaped\n}\n\nfunction markdownLinkDestination(value: string): string | null {\n try {\n return encodeURI(value)\n .replace(/\\(/g, '%28')\n .replace(/\\)/g, '%29')\n .replace(/&/g, '&')\n } catch {\n return null\n }\n}\n\nfunction htmlOpeningTagEnd(value: string, start: number): number | null {\n let quote = ''\n for (let index = start; index < value.length; index += 1) {\n const character = value[index]\n if (quote) {\n if (character === quote) quote = ''\n continue\n }\n if (character === '\"' || character === \"'\") {\n quote = character\n continue\n }\n if (character === '>') return index + 1\n }\n return null\n}\n\nfunction replacePortableHtmlImages(value: string): string {\n const matcher = /<img\\b/gi\n let cursor = 0\n let output = ''\n for (const match of value.matchAll(matcher)) {\n const start = match.index\n if (start < cursor) continue\n const end = htmlOpeningTagEnd(value, start + match[0].length)\n if (end === null) continue\n const fragment = load(value.slice(start, end))\n const image = fragment('img').first()\n const source = image.attr('src')\n const destination = source && isSafePortableUrl(source) ? markdownLinkDestination(source) : null\n const alternative = escapeMarkdownText(image.attr('alt') ?? '')\n output += value.slice(cursor, start)\n output += destination ? `` : alternative\n cursor = end\n }\n return cursor === 0 ? value : `${output}${value.slice(cursor)}`\n}\n\nfunction replacePortableHtmlAnchors(value: string): string {\n const matcher = /<a\\b/gi\n let cursor = 0\n let output = ''\n for (const match of value.matchAll(matcher)) {\n const start = match.index\n if (start < cursor) continue\n const openingEnd = htmlOpeningTagEnd(value, start + match[0].length)\n if (openingEnd === null) continue\n const closingMatch = /<\\/a\\s*>/gi\n closingMatch.lastIndex = openingEnd\n const closing = closingMatch.exec(value)\n if (!closing) continue\n const end = closing.index + closing[0].length\n const fragment = load(value.slice(start, end))\n const anchor = fragment('a').first()\n const href = anchor.attr('href')\n const label = escapeMarkdownText(anchor.text().replace(/\\s+/g, ' ').trim())\n const destination = href && isSafePortableUrl(href) ? markdownLinkDestination(href) : null\n output += value.slice(cursor, start)\n output += destination ? `[${label}](${destination})` : label\n cursor = end\n }\n return cursor === 0 ? value : `${output}${value.slice(cursor)}`\n}\n\nfunction markdownNodeText(node: RemoteMarkdownNode): string {\n if (node.type === 'text' || node.type === 'inlineCode') return node.value ?? ''\n if (node.type === 'image' || node.type === 'imageReference') return node.alt ?? ''\n return (node.children ?? []).map(markdownNodeText).join('')\n}\n\n/**\n * Remove unsafe Markdown links using the actual Markdown/MDX parse tree. This\n * catches entity-encoded schemes and balanced destinations that regexes cannot\n * classify reliably, while leaving code fences and ordinary prose untouched.\n */\nfunction sanitizeMarkdownUrls(value: string): string | null {\n let root: RemoteMarkdownNode\n try {\n root = remoteMarkdownParser.parse(value) as RemoteMarkdownNode\n } catch {\n return null\n }\n\n let hasUnsafeMdxSyntax = false\n const validateMdxSyntax = (node: RemoteMarkdownNode) => {\n if (node.type === 'mdxTextExpression'\n || node.type === 'mdxFlowExpression'\n || node.type === 'mdxjsEsm') {\n hasUnsafeMdxSyntax = true\n return\n }\n if (node.type === 'mdxJsxTextElement' || node.type === 'mdxJsxFlowElement') {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== 'mdxJsxAttribute' || !attribute.name\n || /^on[A-Z]/.test(attribute.name)) {\n hasUnsafeMdxSyntax = true\n return\n }\n let staticValue: unknown = attribute.value\n if (attribute.value && typeof attribute.value === 'object') {\n if (attribute.value.type !== 'mdxJsxAttributeValueExpression') {\n hasUnsafeMdxSyntax = true\n return\n }\n try {\n staticValue = JSON.parse(attribute.value.value)\n } catch {\n hasUnsafeMdxSyntax = true\n return\n }\n }\n if (PORTABLE_URL_PROP_NAMES.has(attribute.name)\n && (typeof staticValue !== 'string'\n || !isSafePortableUrl(decodeHtmlAttribute(staticValue)))) {\n hasUnsafeMdxSyntax = true\n return\n }\n }\n }\n for (const child of node.children ?? []) validateMdxSyntax(child)\n }\n validateMdxSyntax(root)\n if (hasUnsafeMdxSyntax) return null\n\n const unsafeDefinitions = new Set<string>()\n const visitDefinitions = (node: RemoteMarkdownNode) => {\n if (node.type === 'definition' && node.identifier && node.url\n && !isSafePortableUrl(node.url)) unsafeDefinitions.add(node.identifier.toLowerCase())\n for (const child of node.children ?? []) visitDefinitions(child)\n }\n visitDefinitions(root)\n\n const replacements: Array<{ start: number; end: number; value: string }> = []\n const replaceNode = (node: RemoteMarkdownNode, replacement: string): boolean => {\n const start = node.position?.start.offset\n const end = node.position?.end.offset\n if (start === undefined || end === undefined) return false\n replacements.push({ start, end, value: replacement })\n return true\n }\n const visitUrls = (node: RemoteMarkdownNode) => {\n const hasUnsafeDirectUrl = (node.type === 'link' || node.type === 'image')\n && typeof node.url === 'string'\n && !isSafePortableUrl(node.url)\n const hasUnsafeReference = (node.type === 'linkReference' || node.type === 'imageReference')\n && typeof node.identifier === 'string'\n && unsafeDefinitions.has(node.identifier.toLowerCase())\n if (hasUnsafeDirectUrl || hasUnsafeReference) {\n if (replaceNode(node, escapeMarkdownText(markdownNodeText(node)))) return\n }\n if (node.type === 'definition' && node.identifier\n && unsafeDefinitions.has(node.identifier.toLowerCase())) {\n if (replaceNode(node, '')) return\n }\n for (const child of node.children ?? []) visitUrls(child)\n }\n visitUrls(root)\n\n return replacements\n .sort((left, right) => right.start - left.start)\n .reduce((result, replacement) => (\n `${result.slice(0, replacement.start)}${replacement.value}${result.slice(replacement.end)}`\n ), value)\n}\n\nfunction hasUnsafePortableUrlProp(value: string): boolean {\n const quotedProps = new RegExp(`\\\\b(?:${PORTABLE_URL_PROPS})\\\\s*=\\\\s*(['\"])([^'\"\\\\r\\\\n]*)\\\\1`, 'gi')\n for (const match of value.matchAll(quotedProps)) {\n if (!isSafePortableUrl(decodeHtmlAttribute(match[2]))) return true\n }\n const expressionProps = new RegExp(`\\\\b(?:${PORTABLE_URL_PROPS})\\\\s*=\\\\s*\\\\{\\\\s*(\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\")\\\\s*\\\\}`, 'gi')\n for (const match of value.matchAll(expressionProps)) {\n try {\n if (!isSafePortableUrl(decodeHtmlAttribute(JSON.parse(match[1])))) return true\n } catch {\n return true\n }\n }\n return false\n}\n\nfunction portableHtmlToMarkdown(value: string): string {\n return replacePortableHtmlAnchors(replacePortableHtmlImages(value))\n .replace(/<span\\b[^>]*>|<\\/span>/gi, '')\n .replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_original, level: string, content: string) => {\n return `\\n${'#'.repeat(Number(level))} ${content.trim()}\\n`\n })\n .replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_original, content: string) => `\\n${content.trim()}\\n`)\n .replace(/<br\\s*\\/?\\s*>/gi, '\\n')\n .replace(/<\\/?(?:article|div|main|section)\\b[^>]*>/gi, '')\n}\n\nfunction transformMarkdownProse(body: string, transform: (value: string) => string): string {\n const output: Array<string> = []\n let prose: Array<string> = []\n let fenceCharacter = ''\n let fenceLength = 0\n const flushProse = () => {\n if (prose.length === 0) return\n output.push(transform(prose.join('\\n')))\n prose = []\n }\n for (const line of body.split('\\n')) {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (fence && !fenceCharacter) {\n flushProse()\n fenceCharacter = fence[1][0]\n fenceLength = fence[1].length\n output.push(line)\n continue\n }\n if (fenceCharacter) {\n output.push(line)\n if (fence && fence[1][0] === fenceCharacter && fence[1].length >= fenceLength\n && fence[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n }\n continue\n }\n prose.push(line)\n }\n flushProse()\n return output.join('\\n')\n}\n\nfunction sanitizeRemoteMarkdown(body: string): string | null {\n let fenceCharacter = ''\n let fenceLength = 0\n const portableBody = transformMarkdownProse(body, portableHtmlToMarkdown)\n const sanitized = portableBody.split('\\n').map((line) => {\n const fence = line.match(/^\\s{0,3}(`{3,}|~{3,})(.*)$/)\n if (fence && !fenceCharacter) {\n fenceCharacter = fence[1][0]\n fenceLength = fence[1].length\n return line\n }\n if (fence && fence[1][0] === fenceCharacter && fence[1].length >= fenceLength\n && fence[2].trim() === '') {\n fenceCharacter = ''\n fenceLength = 0\n return line\n }\n if (fenceCharacter) return line\n return portableHtmlToMarkdown(stripEventHandlerProps(line\n // Remove obviously unsafe image destinations before MDX parsing. A data\n // URL can itself contain raw `<svg ...>` syntax that makes an otherwise\n // removable Markdown image fail the MDX grammar before the AST exists.\n .replace(/!\\[([^\\]]*)\\]\\(\\s*([^)]+)\\)/g, (original, alternative: string, destination: string) => (\n isSafePortableUrl(decodeHtmlAttribute(destination.replace(/^<|>$/g, '')))\n ? original\n : escapeMarkdownText(alternative)\n ))))\n }).join('\\n')\n const urlSafeMarkdown = sanitizeMarkdownUrls(sanitized)\n if (urlSafeMarkdown === null) return null\n const executable = withoutFencedCode(urlSafeMarkdown)\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, '')\n .replace(/<(?:https?:\\/\\/|mailto:)[^>]+>/gi, '')\n .replace(/(`+)[\\s\\S]*?\\1/g, '')\n if (/^\\s*(?:import|export)\\s/m.test(executable)) return null\n // A public Markdown endpoint is still attacker-controlled MDX. Preserve\n // known documentation primitives and JSON-literal props, but never compile\n // executable expressions, raw HTML, event handlers, or local components.\n let hasUnsafeExpression = false\n const withoutStaticProps = executable.replace(/=\\{([^{}\\n]*)\\}/g, (original, value: string) => {\n try {\n JSON.parse(value)\n return '=\"\"'\n } catch {\n hasUnsafeExpression = true\n return original\n }\n }).replace(/\\\\[{}]/g, '')\n if (hasUnsafeExpression || /[{}]/.test(withoutStaticProps)\n || /\\bon[A-Z][A-Za-z]*\\s*=/g.test(withoutStaticProps)\n || hasUnsafePortableUrlProp(executable)) return null\n for (const match of withoutStaticProps.matchAll(/<\\/?([A-Za-z][A-Za-z0-9.]*)(?:\\s|>|\\/)/g)) {\n const component = match[1].split('.', 1)[0]\n if (!PORTABLE_MDX_COMPONENTS.has(component)) return null\n }\n return urlSafeMarkdown\n}\n\nfunction migratedHref(\n href: string,\n currentUrl: URL,\n source: URL,\n scopePath: string,\n importedIds: Set<string>,\n sourceHomePageId?: string,\n): string {\n if (/^(?:javascript|data|vbscript):/i.test(href)) return '#'\n if (href.startsWith('#') || /^(?:mailto|tel):/i.test(href)) return href\n try {\n const target = new URL(href, currentUrl)\n if (target.origin !== source.origin) return href\n if (scopePath === '/' && candidateIdentity(target) === candidateIdentity(source)) {\n return `/${target.search}${target.hash}`\n }\n let path = target.pathname\n if (scopePath !== '/' && (path === scopePath || path.startsWith(`${scopePath}/`))) {\n path = path.slice(scopePath.length)\n }\n const id = pageIdFromReference(path.replace(/^\\/+/, '') || 'introduction')\n const localizedId = id ? canonicalLocalizedPageId(id) : id\n const destinationId = localizedId === sourceHomePageId ? 'introduction' : localizedId\n let importedDestinationId = destinationId && importedIds.has(destinationId)\n ? destinationId\n : undefined\n if (destinationId && !importedDestinationId) {\n importedDestinationId = [`${destinationId}/overview`, `${destinationId}/introduction`]\n .find((candidate) => importedIds.has(candidate))\n ?? [...importedIds].find((candidate) => candidate.startsWith(`${destinationId}/`))\n }\n if (importedDestinationId) {\n const destination = importedDestinationId === 'introduction' ? '/' : `/${importedDestinationId}`\n return `${destination}${target.search}${target.hash}`\n }\n // Same-origin marketing and intentionally missing example links remain\n // valid external URLs instead of becoming broken links in the new site.\n return target.toString()\n } catch {\n return href\n }\n}\n\nfunction rewriteInternalLinks(\n body: string,\n currentUrl: URL,\n source: URL,\n scopePath: string,\n importedIds: Set<string>,\n sourceHomePageId?: string,\n): string {\n const markdown = body.replace(/(?<!!)\\[([^\\]]+)\\]\\(([^)\\s]+)(\\s+['\"][^'\"]*['\"])?\\)/g, (\n original,\n label: string,\n href: string,\n title = '',\n ) => {\n const destination = migratedHref(href, currentUrl, source, scopePath, importedIds, sourceHomePageId)\n return destination === href ? original : `[${label}](${destination}${title})`\n })\n return markdown.replace(/\\bhref=(['\"])([^'\"]+)\\1/g, (_original, quote: string, href: string) => {\n const destination = migratedHref(href, currentUrl, source, scopePath, importedIds, sourceHomePageId)\n return `href=${quote}${destination}${quote}`\n })\n}\n\nfunction remoteMarkdownMetadata(body: string): {\n content: string\n title?: string\n description?: string\n sidebarTitle?: string\n tag?: string\n mode?: string\n hidden?: boolean\n noindex?: boolean\n} {\n if (!/^---\\r?\\n/.test(body)) return { content: body }\n const end = body.slice(4, 65_540).search(/\\r?\\n---(?:\\r?\\n|$)/)\n if (end < 0) return { content: body }\n const frontmatter = body.slice(4, end + 4)\n const contentStart = end + 4 + body.slice(end + 4).match(/^\\r?\\n---(?:\\r?\\n|$)/)![0].length\n function scalar(key: string): string | undefined {\n const value = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, 'm'))?.[1].trim()\n if (!value) return undefined\n if (/^['\"].*['\"]$/.test(value)) {\n try {\n const parsed = JSON.parse(value.replace(/^'/, '\"').replace(/'$/, '\"'))\n return typeof parsed === 'string' ? parsed : undefined\n } catch {\n return value.slice(1, -1)\n }\n }\n return value.slice(0, 500)\n }\n return {\n content: body.slice(contentStart),\n title: scalar('title'),\n description: scalar('description'),\n sidebarTitle: scalar('sidebarTitle'),\n tag: scalar('tag'),\n mode: scalar('mode'),\n hidden: scalar('hidden') === 'true' ? true : undefined,\n noindex: scalar('noindex') === 'true' ? true : undefined,\n }\n}\n\nfunction stripMintlifyDocumentationIndex(body: string): string {\n const lines = body.split(/\\r?\\n/)\n if (!/^>\\s*##\\s+Documentation Index\\s*$/i.test(lines[0] ?? '')\n || !/^>.*\\/llms(?:-full)?\\.txt/i.test(lines[1] ?? '')\n || !/^>.*discover all available pages/i.test(lines[2] ?? '')) return body\n let index = 3\n while (index < lines.length && /^>/.test(lines[index])) index += 1\n while (index < lines.length && lines[index].trim() === '') index += 1\n return lines.slice(index).join('\\n')\n}\n\nfunction extractEmbeddedOpenApi(content: string): {\n content: string\n openapi?: string\n fragment?: EmbeddedOpenApiFragment\n} {\n const fencePattern = /^\\s{0,3}(`{3,}|~{3,})(?:yaml|yml|json)\\s+(\\S+\\.(?:yaml|yml|json))\\s+(delete|get|head|options|patch|post|put|trace)\\s+(\\/\\S+)\\s*\\r?\\n([\\s\\S]*?)^\\s{0,3}\\1\\s*$/im\n const match = fencePattern.exec(content)\n if (!match) return { content }\n try {\n const parsed = parseYaml(match[5], { maxAliasCount: 50 })\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { content }\n const document = parsed as Record<string, unknown>\n if (typeof document.openapi !== 'string' && typeof document.swagger !== 'string') return { content }\n const method = match[3].toUpperCase()\n const path = match[4]\n const paths = document.paths\n if (!paths || typeof paths !== 'object' || Array.isArray(paths)) return { content }\n const pathItem = (paths as Record<string, unknown>)[path]\n if (!pathItem || typeof pathItem !== 'object' || Array.isArray(pathItem)\n || !(match[3].toLowerCase() in pathItem)) return { content }\n const before = content.slice(0, match.index).replace(/(?:^|\\n)##\\s+OpenAPI\\s*\\n\\s*$/i, '\\n')\n const after = content.slice(match.index + match[0].length)\n return {\n content: `${before}${after}`.trim(),\n openapi: `${method} ${path}`,\n fragment: {\n method,\n path,\n document,\n },\n }\n } catch {\n return { content }\n }\n}\n\nfunction markdownPage(document: MigrationFetchResponse, id: string, platform: MigrationPlatform): {\n page: MigrationPage | null\n openApiFragment?: EmbeddedOpenApiFragment\n} {\n const parsed = remoteMarkdownMetadata(document.body)\n let content = stripMintlifyDocumentationIndex(parsed.content).trimStart()\n const titleMatch = content.match(/^#\\s+(.+)\\r?\\n/)\n const title = parsed.title ?? titleMatch?.[1] ?? id.split('/').at(-1) ?? 'Introduction'\n if (titleMatch) content = content.slice(titleMatch[0].length).trimStart()\n let description = parsed.description\n if (!description) {\n const quoteMatch = content.match(/^(>[^\\r\\n]*(?:\\r?\\n>[^\\r\\n]*)*)\\r?\\n/)\n if (quoteMatch) {\n description = plainDescription(quoteMatch[1].replace(/^>\\s?/gm, ''))\n content = content.slice(quoteMatch[0].length).trimStart()\n }\n }\n // Re-emit only scalar metadata we parsed ourselves. The shared YAML parser\n // handles trusted repository sources but never receives attacker-controlled\n // aliases from a public URL.\n const embeddedOpenApi = extractEmbeddedOpenApi(content)\n const raw = [\n '---',\n `title: ${JSON.stringify(title)}`,\n ...(description ? [`description: ${JSON.stringify(description)}`] : []),\n ...(parsed.sidebarTitle ? [`sidebarTitle: ${JSON.stringify(parsed.sidebarTitle)}`] : []),\n ...(parsed.tag ? [`tag: ${JSON.stringify(parsed.tag)}`] : []),\n ...(parsed.mode ? [`mode: ${JSON.stringify(parsed.mode)}`] : []),\n ...(parsed.hidden ? ['hidden: true'] : []),\n ...(parsed.noindex ? ['noindex: true'] : []),\n ...(embeddedOpenApi.openapi ? [`openapi: ${JSON.stringify(embeddedOpenApi.openapi)}`] : []),\n '---',\n '',\n embeddedOpenApi.content,\n ].join('\\n')\n return {\n // The crawler knows the source platform (detected or caller-provided)\n // before it ever parses a page; an omitted platform would otherwise\n // apply every platform's textual renames to content of unknown origin.\n page: parseMarkdownPage({ id, raw, source: document.finalUrl.toString(), platform }),\n openApiFragment: embeddedOpenApi.fragment,\n }\n}\n\nfunction mergeRecord(target: Record<string, unknown>, source: unknown): void {\n if (!source || typeof source !== 'object' || Array.isArray(source)) return\n for (const [key, value] of Object.entries(source)) {\n if (['__proto__', 'constructor', 'prototype'].includes(key)) continue\n if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = value\n continue\n }\n const current = target[key]\n if (current && value && typeof current === 'object' && typeof value === 'object'\n && !Array.isArray(current) && !Array.isArray(value)) {\n mergeRecord(current as Record<string, unknown>, value)\n }\n }\n}\n\nfunction mergeEmbeddedOpenApi(fragments: Array<EmbeddedOpenApiFragment>): Uint8Array | null {\n const first = fragments[0]\n if (!first) return null\n const combined: Record<string, unknown> = {\n ...first.document,\n paths: {},\n components: {},\n }\n const combinedPaths = combined.paths as Record<string, unknown>\n const combinedComponents = combined.components as Record<string, unknown>\n const tags = new Map<string, unknown>()\n for (const fragment of fragments) {\n const sourcePaths = fragment.document.paths as Record<string, unknown>\n const sourcePathItem = sourcePaths?.[fragment.path]\n if (!sourcePathItem || typeof sourcePathItem !== 'object' || Array.isArray(sourcePathItem)) continue\n const sourceOperation = (sourcePathItem as Record<string, unknown>)[fragment.method.toLowerCase()]\n if (!sourceOperation || typeof sourceOperation !== 'object' || Array.isArray(sourceOperation)) continue\n const operation = { ...(sourceOperation as Record<string, unknown>) }\n if (!operation.servers && Array.isArray(fragment.document.servers)) operation.servers = fragment.document.servers\n if (!operation.security && Array.isArray(fragment.document.security)) operation.security = fragment.document.security\n const existingPath = combinedPaths[fragment.path]\n const pathItem = existingPath && typeof existingPath === 'object' && !Array.isArray(existingPath)\n ? existingPath as Record<string, unknown>\n : {}\n for (const sharedKey of ['parameters', 'servers', 'summary', 'description']) {\n const sharedValue = (sourcePathItem as Record<string, unknown>)[sharedKey]\n if (sharedValue !== undefined && pathItem[sharedKey] === undefined) pathItem[sharedKey] = sharedValue\n }\n pathItem[fragment.method.toLowerCase()] = operation\n combinedPaths[fragment.path] = pathItem\n mergeRecord(combinedComponents, fragment.document.components)\n for (const tag of Array.isArray(fragment.document.tags) ? fragment.document.tags : []) {\n if (!tag || typeof tag !== 'object' || Array.isArray(tag)) continue\n const name = (tag as Record<string, unknown>).name\n if (typeof name === 'string' && !tags.has(name)) tags.set(name, tag)\n }\n }\n if (Object.keys(combinedPaths).length === 0) return null\n if (Object.keys(combinedComponents).length === 0) delete combined.components\n if (tags.size > 0) combined.tags = [...tags.values()]\n return new TextEncoder().encode(stringifyYaml(combined))\n}\n\nfunction htmlPage(\n document: MigrationFetchResponse,\n id: string,\n): { page: MigrationPage | null; links: Array<string> } {\n const $ = load(document.body)\n const links = $('nav a[href], main a[href], article a[href], [role=\"main\"] a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter(Boolean)\n const title = $('main h1, article h1, h1').first().text().trim()\n || $('meta[property=\"og:title\"]').attr('content')?.trim()\n || $('title').text().split('|')[0].trim()\n const description = $('meta[name=\"description\"]').attr('content')?.trim()\n || $('meta[property=\"og:description\"]').attr('content')?.trim()\n const content = $('main article, article, main, [role=\"main\"]').first()\n const root = content.length ? content : $('body')\n root.find('script,style,noscript,nav,header,footer,aside,form,button,svg,iframe,object,embed,link,meta').remove()\n root.find('.theme-doc-version-badge,.theme-doc-breadcrumbs,.theme-doc-toc-mobile,.table-of-contents,.hash-link').remove()\n root.find('a[href]').each((_index, element) => {\n const href = $(element).attr('href')\n if (!href) return\n try {\n const resolved = new URL(href, document.finalUrl)\n if (['http:', 'https:', 'mailto:', 'tel:'].includes(resolved.protocol)) {\n $(element).attr('href', resolved.toString())\n } else {\n $(element).removeAttr('href')\n }\n } catch {\n $(element).removeAttr('href')\n }\n })\n root.find('img[src]').each((_index, element) => {\n const src = $(element).attr('src')\n if (!src) return\n try {\n const resolved = new URL(src, document.finalUrl)\n if (['http:', 'https:'].includes(resolved.protocol)) {\n $(element).attr('src', resolved.toString())\n } else {\n $(element).removeAttr('src')\n }\n } catch {\n $(element).removeAttr('src')\n }\n })\n const turndown = new TurndownService({ codeBlockStyle: 'fenced', emDelimiter: '_', headingStyle: 'atx' })\n turndown.remove(['script', 'style', 'noscript'])\n turndown.addRule('docusaurus-admonition', {\n filter: (node) => node.nodeName === 'DIV'\n && (node as HTMLElement).classList.contains('theme-admonition'),\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const className = element.className\n const tag = /admonition-(?:danger)/.test(className)\n ? 'Error'\n : /admonition-(?:caution|warning)/.test(className)\n ? 'Warning'\n : /admonition-info/.test(className)\n ? 'Info'\n : 'Note'\n const fragment = load(element.outerHTML)\n const clone = fragment('.theme-admonition').first()\n const title = clone.find('[class*=\"admonitionHeading\"],.admonition-heading').first()\n const titleText = title.text().trim()\n title.remove()\n const markdown = turndown.turndown(clone.html() ?? '').trim()\n return `\\n\\n<${tag}>\\n${titleText ? `**${titleText}**\\n\\n` : ''}${markdown}\\n</${tag}>\\n\\n`\n },\n })\n turndown.addRule('docusaurus-tabs', {\n filter: (node) => node.nodeName === 'DIV'\n && (node as HTMLElement).classList.contains('tabs-container'),\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const fragment = load(element.outerHTML)\n const container = fragment('.tabs-container').first()\n const labels = container.children('ul.tabs').children('li').toArray()\n .map((item) => fragment(item).text().trim() || 'Tab')\n const panels = container.children('div[role=\"tabpanel\"]').toArray()\n if (panels.length === 0) return _content\n const tabs = panels.map((panel, index) => {\n const title = (labels[index] ?? `Tab ${index + 1}`).replace(/\"/g, '"')\n return `<Tab title=\"${title}\">\\n${turndown.turndown(fragment(panel).html() ?? '').trim()}\\n</Tab>`\n })\n return `\\n\\n<Tabs>\\n${tabs.join('\\n\\n')}\\n</Tabs>\\n\\n`\n },\n })\n turndown.addRule('gfm-table', {\n filter: 'table',\n replacement: (_content, node) => {\n const fragment = load((node as HTMLElement).outerHTML)\n const rows = fragment('tr').toArray().map((row) => (\n fragment(row).children('th,td').toArray().map((cell) => escapeMarkdownText(\n fragment(cell).text().replace(/\\s+/g, ' ').trim(),\n true,\n ))\n )).filter((row) => row.length > 0)\n if (rows.length === 0) return ''\n const width = Math.max(...rows.map((row) => row.length))\n const normalized = rows.map((row) => [...row, ...Array<string>(width - row.length).fill('')])\n return `\\n\\n| ${normalized[0].join(' | ')} |\\n| ${Array<string>(width).fill('---').join(' | ')} |\\n${normalized.slice(1).map((row) => `| ${row.join(' | ')} |`).join('\\n')}\\n\\n`\n },\n })\n turndown.addRule('migration-safe-fenced-code', {\n filter: (node) => node.nodeName === 'PRE',\n replacement: (_content, node) => {\n const element = node as HTMLElement\n const fragment = load(element.outerHTML)\n const tokenLines = fragment('.token-line').toArray()\n const code = (tokenLines.length > 0\n ? tokenLines.map((line) => fragment(line).text()).join('\\n')\n : fragment('pre').text()).replace(/\\n$/, '')\n const language = fragment('code').attr('class')?.match(/(?:language-|lang-)([A-Za-z0-9_+-]+)/)?.[1] ?? ''\n const longestFence = Math.max(0, ...[...code.matchAll(/`+/g)].map((match) => match[0].length))\n const fence = '`'.repeat(Math.max(3, longestFence + 1))\n return `\\n\\n${fence}${language}\\n${code}\\n${fence}\\n\\n`\n },\n })\n const escape = turndown.escape.bind(turndown)\n turndown.escape = (text: string) => escape(text).replace(/[<{]/g, (match) => `\\\\${match}`)\n const body = turndown.turndown(root.html() ?? '').trim()\n // Docusaurus can intentionally publish title-only reference/partial pages.\n // Keep those real article routes while still rejecting empty search/app\n // shells that happen to expose a document title.\n if (!title || (body.length < 40 && $('article').length === 0)) return { page: null, links }\n return {\n page: {\n id,\n navigationId: id,\n title,\n description: description || plainDescription(body) || `Documentation imported from ${document.finalUrl.hostname}.`,\n keywords: [],\n body,\n source: document.finalUrl.toString(),\n },\n links,\n }\n}\n\nfunction htmlNavigationLinks(document: MigrationFetchResponse): Array<string> {\n const $ = load(document.body)\n return $('.nav-tabs a[href], nav a[href], aside a[href], [role=\"navigation\"] a[href]')\n .map((_index, element) => $(element).attr('href') ?? '')\n .get()\n .filter(Boolean)\n}\n\ninterface SourceNavigationTab {\n section: string\n label: string\n pageId: string\n}\n\ninterface DocusaurusSidebarItem {\n label: string\n href?: string\n items?: Array<DocusaurusSidebarItem>\n isCategory?: boolean\n}\n\ninterface DocusaurusSidebarSnapshot {\n items: Array<DocusaurusSidebarItem>\n}\n\ninterface DocusaurusDiscovery {\n scopePath: string\n excludedVersionPrefixes: Array<string>\n sidebar: DocusaurusSidebarSnapshot | null\n}\n\nfunction normalizedLinkLabel(value: string): string {\n return value.replace(/\\s+/g, ' ').trim()\n}\n\nfunction readDocusaurusSidebar(document: MigrationFetchResponse): DocusaurusSidebarSnapshot | null {\n if (!/html/i.test(document.contentType)) return null\n const $ = load(document.body)\n const sidebar = $('ul.theme-doc-sidebar-menu').first()\n if (sidebar.length === 0) return null\n\n type CheerioSelector = Exclude<Parameters<ReturnType<typeof load>>[0], undefined>\n function readList(list: CheerioSelector): Array<DocusaurusSidebarItem> {\n return $(list).children('li').toArray().flatMap((item) => {\n const directLink = $(item).children('a.menu__link').first()\n const collapsibleLink = $(item)\n .children('.menu__list-item-collapsible')\n .children('a.menu__link')\n .first()\n const link = directLink.length > 0 ? directLink : collapsibleLink\n const label = normalizedLinkLabel(link.text())\n const href = link.attr('href')\n const nested = $(item).children('ul.menu__list').first()\n const children = nested.length > 0 ? readList(nested.get(0)!) : []\n const isCategory = $(item).hasClass('theme-doc-sidebar-item-category')\n || link.hasClass('menu__link--sublist')\n if (!label && children.length === 0) return []\n return [{\n label: label || 'Documentation',\n ...(href ? { href: new URL(href, document.finalUrl).toString() } : {}),\n ...(children.length > 0 ? { items: children } : {}),\n ...(isCategory ? { isCategory: true } : {}),\n }]\n })\n }\n\n return { items: readList(sidebar.get(0)!) }\n}\n\nfunction docusaurusSidebarHrefs(snapshot: DocusaurusSidebarSnapshot | null): Array<string> {\n const hrefs: Array<string> = []\n const visit = (items: Array<DocusaurusSidebarItem>) => {\n for (const item of items) {\n if (item.href) hrefs.push(item.href)\n if (item.items) visit(item.items)\n }\n }\n if (snapshot) visit(snapshot.items)\n return hrefs\n}\n\nfunction deriveDocusaurusScope(\n source: URL,\n document: MigrationFetchResponse,\n submittedScopePath: string,\n): DocusaurusDiscovery {\n const $ = load(document.body)\n const sidebar = readDocusaurusSidebar(document)\n const internalPaths = docusaurusSidebarHrefs(sidebar).flatMap((href) => {\n try {\n const url = new URL(href)\n return url.origin === source.origin ? [url.pathname.replace(/\\/+$/, '') || '/'] : []\n } catch {\n return []\n }\n })\n const counts = new Map<string, number>()\n for (const path of internalPaths) {\n const segments = path.split('/').filter(Boolean)\n for (let length = 1; length < segments.length; length++) {\n const prefix = `/${segments.slice(0, length).join('/')}`\n counts.set(prefix, (counts.get(prefix) ?? 0) + 1)\n }\n }\n const threshold = Math.max(2, Math.ceil(internalPaths.length * 0.6))\n const scopePath = [...counts]\n .filter(([, count]) => count >= threshold)\n .sort((left, right) => right[0].split('/').length - left[0].split('/').length\n || right[1] - left[1])[0]?.[0]\n ?? submittedScopePath\n\n const excludedVersionPrefixes = $('.dropdown__menu a[href]').toArray().flatMap((element) => {\n const href = $(element).attr('href')\n if (!href) return []\n try {\n const target = new URL(href, document.finalUrl)\n if (target.origin !== source.origin || !isInScope(target, source, scopePath)) return []\n const relativePath = target.pathname.slice(scopePath.length).replace(/^\\/+/, '')\n const version = relativePath.split('/', 1)[0]\n if (!/^(?:legacy|next|v\\d[\\w.-]*)$/i.test(version)) return []\n return [`${scopePath}/${version}`]\n } catch {\n return []\n }\n })\n\n return {\n scopePath,\n excludedVersionPrefixes: [...new Set(excludedVersionPrefixes)],\n sidebar,\n }\n}\n\nfunction docusaurusRouteIdForUrl(url: URL, scopePath: string): string | null {\n let path = url.pathname.replace(/\\/+$/, '')\n if (scopePath === '/') path = path.replace(/^\\/+/, '')\n else if (path === scopePath) path = ''\n else if (path.startsWith(`${scopePath}/`)) path = path.slice(scopePath.length + 1)\n else return null\n const segments = path.split('/').filter(Boolean).map((segment) => {\n let decoded = segment\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n // Preserve malformed source segments as literal route input.\n }\n return decoded\n .replace(/\\.(?:html?|mdx?)$/i, '')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/(^-|-$)/g, '')\n }).filter(Boolean)\n return segments.join('/') || 'introduction'\n}\n\nfunction storageIdForDocusaurusRoute(routeId: string): string {\n return /(?:^|\\/)(?:index|readme)$/i.test(routeId) ? `${routeId}/index` : routeId\n}\n\nfunction docusaurusNavigationFromSnapshots(\n snapshots: Array<DocusaurusSidebarSnapshot>,\n pages: Array<MigrationPage>,\n scopePath: string,\n): ReturnType<typeof buildNavigationFromPages> {\n const imported = new Set(pages.map((page) => page.navigationId))\n const claimed = new Set<string>()\n const uniqueSnapshots = [...new Map(snapshots.map((snapshot) => [\n JSON.stringify(snapshot.items),\n snapshot,\n ])).values()]\n const mergedSnapshots: Array<DocusaurusSidebarSnapshot> = []\n function mergeItems(\n target: Array<DocusaurusSidebarItem>,\n incoming: Array<DocusaurusSidebarItem>,\n ): void {\n for (const item of incoming) {\n const existing = target.find((candidate) => candidate.label === item.label\n && (candidate.items || item.items))\n ?? target.find((candidate) => candidate.label === item.label && candidate.href === item.href)\n if (!existing) {\n target.push(structuredClone(item))\n continue\n }\n if (!existing.href && item.href) existing.href = item.href\n if (item.items) {\n existing.items ??= []\n mergeItems(existing.items, item.items)\n }\n }\n }\n for (const snapshot of uniqueSnapshots) {\n const incomingLabels = new Set(snapshot.items.map((item) => item.label))\n const cluster = mergedSnapshots.find((candidate) => {\n const candidateLabels = new Set(candidate.items.map((item) => item.label))\n const overlap = [...incomingLabels].filter((label) => candidateLabels.has(label)).length\n return overlap >= Math.max(2, Math.ceil(Math.min(incomingLabels.size, candidateLabels.size) * 0.5))\n })\n if (cluster) mergeItems(cluster.items, snapshot.items)\n else mergedSnapshots.push(structuredClone(snapshot))\n }\n const pageIdsFor = (snapshot: DocusaurusSidebarSnapshot): Array<string> => docusaurusSidebarHrefs(snapshot)\n .flatMap((href) => {\n const id = docusaurusRouteIdForUrl(new URL(href), scopePath)\n return id && imported.has(id) ? [id] : []\n })\n mergedSnapshots.sort((left, right) => pageIdsFor(right).length - pageIdsFor(left).length)\n\n const tabs = mergedSnapshots.flatMap((snapshot, snapshotIndex) => {\n function convert(items: Array<DocusaurusSidebarItem>): Array<string | MigrationNavigationGroup> {\n const converted: Array<string | MigrationNavigationGroup> = []\n for (const item of items) {\n const routeId = item.href\n ? docusaurusRouteIdForUrl(new URL(item.href), scopePath)\n : null\n const page = routeId && imported.has(routeId) && !claimed.has(routeId) ? routeId : null\n if (page) claimed.add(page)\n const children = item.items ? convert(item.items) : []\n if (children.length > 0 || item.isCategory) {\n converted.push({ group: item.label, pages: page ? [page, ...children] : children })\n continue\n }\n if (page) converted.push(page)\n }\n return converted\n }\n const converted = convert(snapshot.items)\n const loosePages = converted.filter((item): item is string => typeof item === 'string')\n const groups = converted.filter((item): item is Exclude<typeof item, string> => typeof item !== 'string')\n if (loosePages.length > 0) groups.unshift({ group: 'Overview', pages: loosePages })\n if (groups.length === 0) return []\n const snapshotPageIds = pageIdsFor(snapshot)\n const firstSegments = new Set(snapshotPageIds.map((id) => id.split('/', 1)[0]))\n const tab = snapshotIndex > 0 && firstSegments.size === 1\n ? normalizedLinkLabel([...firstSegments][0].replace(/[-_]/g, ' ')).replace(/\\b\\w/g, (letter) => letter.toUpperCase())\n : 'Documentation'\n return [{ tab, groups }]\n })\n\n const additional = pages\n .map((page) => page.navigationId)\n .filter((id) => !claimed.has(id))\n if (additional.length > 0) {\n if (tabs.length === 0) return buildNavigationFromPages(pages)\n tabs[0].groups?.push({ group: 'Additional', pages: additional })\n }\n return { tabs }\n}\n\nfunction htmlTopLevelNavigation(\n document: MigrationFetchResponse,\n source: URL,\n scopePath: string,\n): Array<SourceNavigationTab> {\n const $ = load(document.body)\n interface NavigationCandidate {\n entries: Array<SourceNavigationTab>\n anchorCount: number\n }\n const collectCandidates = (selector: string): Array<NavigationCandidate> => {\n const candidates: Array<NavigationCandidate> = []\n $(selector).each((_containerIndex, container) => {\n const entries: Array<SourceNavigationTab> = []\n const seenSections = new Set<string>()\n let anchorCount = 0\n $(container).find('a[href]').each((_index, element) => {\n const label = $(element).text().replace(/\\s+/g, ' ').trim()\n const href = $(element).attr('href')\n if (!label || !href) return\n try {\n const target = new URL(href, document.finalUrl)\n if (!isInScope(target, source, scopePath)) return\n anchorCount += 1\n const targetId = canonicalLocalizedPageId(pageIdForUrl(target, scopePath) ?? '')\n const pageId = targetId\n const section = targetId.split('/', 1)[0] || 'introduction'\n if (!pageId || seenSections.has(section)) return\n seenSections.add(section)\n entries.push({ section, label, pageId })\n } catch {\n // Ignore malformed navigation targets; discovery applies the same rule.\n }\n })\n if (entries.length > 1) {\n candidates.push({ entries, anchorCount })\n }\n })\n return candidates\n }\n // Mintlify marks its product-tab strip consistently. Prefer that explicit\n // platform signal; generic nav elements usually describe only the sidebar.\n const tabCandidates = collectCandidates('.nav-tabs')\n const candidates = tabCandidates.length > 0\n ? tabCandidates\n : collectCandidates('nav, [role=\"navigation\"]')\n const entries = candidates.sort((left, right) => {\n const densityDifference = (right.entries.length / right.anchorCount)\n - (left.entries.length / left.anchorCount)\n return densityDifference || right.entries.length - left.entries.length\n })[0]?.entries ?? []\n // A product switcher with dozens of entries is invariably a sidebar or\n // responsive page strip, not authored top-level navigation. Refuse to turn\n // that ambiguity into an unusable header.\n const normalizedLabels = entries.map((entry) => entry.label.trim().toLowerCase())\n if (entries.length > 12 || new Set(normalizedLabels).size !== normalizedLabels.length) return []\n return entries\n}\n\nfunction remapNavigationHome(\n config: MigrationBundle['docsConfig'],\n sourceHomePageId: string | undefined,\n): MigrationBundle['docsConfig'] {\n if (!sourceHomePageId || sourceHomePageId === 'introduction') return config\n const remapPages = (\n pages: Array<string | MigrationNavigationGroup>,\n ): Array<string | MigrationNavigationGroup> => pages.map((page) => typeof page === 'string'\n ? page === sourceHomePageId ? 'introduction' : page\n : { ...page, pages: remapPages(page.pages) })\n const remapGroups = (groups: Array<MigrationNavigationGroup>): Array<MigrationNavigationGroup> => groups.map((group) => ({\n ...group,\n pages: remapPages(group.pages),\n }))\n return {\n ...config,\n tabs: config.tabs.map((tab) => ({\n ...tab,\n ...(tab.href === `/${sourceHomePageId}` ? { href: '/' } : {}),\n ...(tab.pages ? { pages: remapPages(tab.pages) } : {}),\n ...(tab.groups ? { groups: remapGroups(tab.groups) } : {}),\n })),\n }\n}\n\nfunction markdownLinks(body: string): Array<string> {\n return [...body.matchAll(/\\[[^\\]]+\\]\\(([^)\\s]+)(?:\\s+['\"][^'\"]*['\"])?\\)/g)]\n .map((match) => match[1])\n}\n\nfunction sitemapLinks(body: string): Array<string> {\n const $ = load(body, { xmlMode: true })\n return $('url > loc, sitemap > loc').map((_index, element) => $(element).text().trim()).get().filter(Boolean)\n}\n\nfunction robotsSitemaps(body: string): Array<string> {\n return body.split('\\n')\n .map((line) => line.match(/^\\s*Sitemap:\\s*(\\S+)/i)?.[1])\n .filter((value): value is string => Boolean(value))\n}\n\nfunction headerLinks(document: MigrationFetchResponse): Array<string> {\n const links: Array<string> = []\n const llms = document.headers?.['x-llms-txt']\n if (llms) links.push(llms)\n const linkHeader = document.headers?.link ?? ''\n for (const match of linkHeader.matchAll(/<([^>]+)>\\s*;[^,]*(?:rel=[\"']?(?:alternate|llms-txt)[\"']?|type=[\"']text\\/(?:markdown|plain)[\"'])/gi)) {\n links.push(match[1])\n }\n return links\n}\n\nasync function safeFetch(\n fetcher: MigrationFetcher,\n url: URL,\n accept: string,\n): Promise<MigrationFetchResponse | null> {\n try {\n return await fetcher(url, { accept })\n } catch {\n return null\n }\n}\n\n/** Crawl one public docs origin into a canonical, caller-independent bundle. */\nexport async function migrateUrl(options: UrlMigrationOptions): Promise<MigrationBundle> {\n const source = validateMigrationUrl(options.sourceUrl)\n const fetcher = options.fetcher ?? defaultMigrationFetcher\n const maxPages = Math.max(1, Math.min(options.maxPages ?? DEFAULT_MAX_PAGES, 1_000))\n const concurrency = Math.max(1, Math.min(options.concurrency ?? 5, 10))\n const maxTotalBytes = Math.max(1_000_000, Math.min(options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES, 500_000_000))\n const submittedScopePath = docsScopePath(source)\n const initial = await fetcher(source, { accept: 'text/markdown,text/html,application/xhtml+xml;q=0.9' })\n if (!isInScope(initial.finalUrl, source, submittedScopePath)) {\n throw new Error('The documentation URL redirected outside the submitted docs origin or path.')\n }\n const htmlProbe = /html/i.test(initial.contentType)\n ? initial\n : await safeFetch(fetcher, source, 'text/html,application/xhtml+xml')\n // Content negotiation must not let an HTML-only redirect escape the path\n // boundary already validated for the submitted documentation response.\n const scopedHtmlProbe = htmlProbe && isInScope(htmlProbe.finalUrl, source, submittedScopePath)\n ? htmlProbe\n : null\n const platform = options.platform ?? detectUrlPlatform(scopedHtmlProbe ?? initial)\n let docusaurusHtmlProbe = platform === 'docusaurus' ? scopedHtmlProbe : null\n if (docusaurusHtmlProbe && !readDocusaurusSidebar(docusaurusHtmlProbe)) {\n const $ = load(docusaurusHtmlProbe.body)\n const docsHref = $('nav a[href]').toArray().map((element) => ({\n href: $(element).attr('href'),\n label: normalizedLinkLabel($(element).text()),\n })).find((link) => /^docs(?:umentation)?$/i.test(link.label))?.href\n if (docsHref) {\n try {\n const docsUrl = new URL(docsHref, docusaurusHtmlProbe.finalUrl)\n if (docsUrl.origin === source.origin && isInScope(docsUrl, source, submittedScopePath)) {\n const probe = await safeFetch(fetcher, docsUrl, 'text/html,application/xhtml+xml')\n if (probe && probe.finalUrl.origin === source.origin && /html/i.test(probe.contentType)) {\n docusaurusHtmlProbe = probe\n }\n }\n } catch {\n // A malformed navbar link falls back to the submitted path boundary.\n }\n }\n }\n const docusaurusDiscovery = platform === 'docusaurus' && docusaurusHtmlProbe\n ? deriveDocusaurusScope(source, docusaurusHtmlProbe, submittedScopePath)\n : null\n // A Mintlify site may own an entire docs origin or a path below a marketing\n // site. Its llms/sitemap location is the authoritative crawl boundary.\n const scopePath = platform === 'mintlify'\n ? machineIndexScopePath(source, [initial, scopedHtmlProbe]) ?? submittedScopePath\n : docusaurusDiscovery?.scopePath ?? submittedScopePath\n const sourceMintlifyConfig = platform === 'mintlify' && scopedHtmlProbe && /html/i.test(scopedHtmlProbe.contentType)\n ? embeddedMintlifyConfig(scopedHtmlProbe.body)\n : null\n const sourceMintlifyProjection = sourceMintlifyConfig\n ? projectMintlifyNavigation(sourceMintlifyConfig, { pathPrefix: scopePath })\n : null\n const hasStructuredMintlifyNavigation = Boolean(\n sourceMintlifyProjection?.docsConfig.tabs.length\n && sourceMintlifyProjection.pageReferences.length,\n )\n const sourceTopLevelNavigation = platform === 'mintlify' && !hasStructuredMintlifyNavigation\n && scopedHtmlProbe && /html/i.test(scopedHtmlProbe.contentType)\n ? htmlTopLevelNavigation(scopedHtmlProbe, source, scopePath)\n : undefined\n // The submitted URL can be any page. Mintlify's first authored product tab,\n // rather than the submitted page, defines which source page becomes `/`.\n // Older single-section themes do not expose a tab strip, so they retain the\n // legacy dedicated-origin fallback when no authored home can be recovered.\n const sourceHomePageId = sourceMintlifyProjection?.pageReferences[0]?.navigationId\n ?? sourceTopLevelNavigation?.[0]?.pageId\n ?? (platform === 'mintlify' && scopePath === '/'\n ? canonicalLocalizedPageId(pageIdForUrl(source, scopePath) ?? '') || undefined\n : undefined)\n const cache = new Map([[source.toString(), initial]])\n if (docusaurusHtmlProbe) cache.set(docusaurusHtmlProbe.finalUrl.toString(), docusaurusHtmlProbe)\n const queue: Array<URL> = [source]\n const queued = new Set([candidateIdentity(source)])\n const warnings: Array<MigrationWarning> = []\n const fetchedSitemaps = new Set<string>()\n const docusaurusSidebars: Array<DocusaurusSidebarSnapshot> = docusaurusDiscovery?.sidebar\n ? [docusaurusDiscovery.sidebar]\n : []\n const docusaurusRedirects: Array<{ source: string; destination: string }> = []\n\n function enqueue(value: string, base: URL): void {\n if (queued.size >= MAX_DISCOVERED_URLS) return\n const url = normalizeCandidate(value, base, source, scopePath)\n if (!url || queued.has(candidateIdentity(url))) return\n if (platform === 'docusaurus' && url.pathname.replace(/\\/+$/, '') === `${scopePath}/search`) return\n if (docusaurusDiscovery?.excludedVersionPrefixes.some((prefix) => {\n const path = url.pathname.replace(/\\/+$/, '')\n return path === prefix || path.startsWith(`${prefix}/`)\n })) return\n queued.add(candidateIdentity(url))\n queue.push(url)\n }\n\n for (const reference of sourceMintlifyProjection?.pageReferences ?? []) {\n let href = reference.ref\n if (scopePath !== '/' && href.startsWith('/')\n && href !== scopePath && !href.startsWith(`${scopePath}/`)) {\n href = `${scopePath}${href}`\n }\n enqueue(href, source)\n }\n\n // Mintlify renders the authored navigation into the HTML shell. Seed the\n // queue from that order before machine indexes add completeness fallbacks.\n const navigationProbe = docusaurusHtmlProbe ?? scopedHtmlProbe\n if (navigationProbe && /html/i.test(navigationProbe.contentType)) {\n for (const link of htmlNavigationLinks(navigationProbe)) enqueue(link, navigationProbe.finalUrl)\n }\n\n async function discoverDocumentLinks(document: MigrationFetchResponse, depth = 0): Promise<void> {\n const links = sitemapLinks(document.body)\n for (const link of links) {\n let url: URL\n try {\n url = new URL(link, document.finalUrl)\n } catch {\n continue\n }\n if (depth < 2 && /\\.xml(?:$|\\?)/i.test(url.pathname)) {\n if (url.origin !== source.origin || fetchedSitemaps.size >= MAX_SITEMAP_DOCUMENTS\n || fetchedSitemaps.has(url.toString())) continue\n fetchedSitemaps.add(url.toString())\n const nested = await safeFetch(fetcher, url, 'application/xml,text/xml')\n if (nested && nested.finalUrl.origin === source.origin) await discoverDocumentLinks(nested, depth + 1)\n } else {\n enqueue(link, document.finalUrl)\n }\n }\n }\n\n for (const link of headerLinks(initial)) {\n let url: URL\n try {\n url = new URL(link, initial.finalUrl)\n } catch {\n continue\n }\n if (url.origin !== source.origin) continue\n const document = await safeFetch(fetcher, url, 'text/plain,text/markdown')\n if (!document || document.finalUrl.origin !== source.origin) continue\n for (const candidate of markdownLinks(document.body)) enqueue(candidate, document.finalUrl)\n }\n\n const pathRoot = scopePath === '/' ? source.origin : `${source.origin}${scopePath}`\n const discoveryUrls = [\n new URL('/llms.txt', source.origin),\n new URL(`${pathRoot.replace(source.origin, '')}/llms.txt`, source.origin),\n new URL('/robots.txt', source.origin),\n new URL('/sitemap.xml', source.origin),\n new URL(`${pathRoot.replace(source.origin, '')}/sitemap.xml`, source.origin),\n ]\n const uniqueDiscovery = [...new Map(discoveryUrls.map((url) => [url.toString(), url])).values()]\n for (const url of uniqueDiscovery) {\n const document = await safeFetch(fetcher, url, 'text/plain,application/xml,text/xml;q=0.9')\n if (!document || document.finalUrl.origin !== source.origin) continue\n const isRobots = url.pathname.endsWith('robots.txt')\n const isSitemap = url.pathname.endsWith('sitemap.xml') || document.contentType.includes('xml')\n if (isRobots) {\n for (const link of robotsSitemaps(document.body)) {\n let sitemapUrl: URL\n try {\n sitemapUrl = new URL(link, document.finalUrl)\n } catch {\n continue\n }\n if (sitemapUrl.origin !== source.origin || fetchedSitemaps.size >= MAX_SITEMAP_DOCUMENTS\n || fetchedSitemaps.has(sitemapUrl.toString())) continue\n fetchedSitemaps.add(sitemapUrl.toString())\n const sitemap = await safeFetch(fetcher, sitemapUrl, 'application/xml,text/xml')\n if (sitemap && sitemap.finalUrl.origin === source.origin) await discoverDocumentLinks(sitemap)\n }\n } else if (isSitemap) {\n await discoverDocumentLinks(document)\n } else {\n for (const link of markdownLinks(document.body)) enqueue(link, document.finalUrl)\n }\n }\n\n const pages: Array<MigrationPage> = []\n const openApiFragments: Array<EmbeddedOpenApiFragment> = []\n const seenIds = new Set<string>()\n const seenSources = new Set<string>()\n const visited = new Set<string>()\n let importedBytes = 0\n let isByteBudgetExhausted = false\n while (queue.length > 0 && pages.length < maxPages && !isByteBudgetExhausted) {\n const batch: Array<URL> = []\n while (queue.length > 0 && batch.length < Math.min(concurrency, maxPages - pages.length)) {\n const candidate = queue.shift()\n if (!candidate || visited.has(candidate.toString())) continue\n visited.add(candidate.toString())\n batch.push(candidate)\n }\n if (batch.length === 0) continue\n const results = await Promise.all(batch.map(async (candidate) => {\n let document = cache.get(candidate.toString())\n ?? await safeFetch(fetcher, candidate, 'text/markdown,text/html,application/xhtml+xml;q=0.9')\n if (!document) {\n return { candidate, page: null, links: [] as Array<string>, failure: true }\n }\n if (!isInScope(document.finalUrl, source, scopePath)) {\n return { candidate, page: null, links: [] as Array<string>, failure: false }\n }\n const isMarkdown = /(?:markdown|text\\/plain)/i.test(document.contentType)\n || /\\.mdx?$/i.test(document.finalUrl.pathname)\n if (!isMarkdown && !/\\.mdx?$/i.test(candidate.pathname)) {\n const markdownUrl = new URL(candidate)\n markdownUrl.pathname = `${markdownUrl.pathname.replace(/\\/$/, '')}.md`\n const markdownDocument = await safeFetch(fetcher, markdownUrl, 'text/markdown,text/plain')\n if (markdownDocument && isInScope(markdownDocument.finalUrl, source, scopePath)\n && /(?:markdown|text\\/plain)/i.test(markdownDocument.contentType)) {\n document = markdownDocument\n }\n }\n const isResolvedMarkdown = /(?:markdown|text\\/plain)/i.test(document.contentType)\n || /\\.mdx?$/i.test(document.finalUrl.pathname)\n const sanitizedMarkdown = isResolvedMarkdown ? sanitizeRemoteMarkdown(document.body) : null\n if (isResolvedMarkdown && sanitizedMarkdown === null) {\n const htmlUrl = new URL(candidate)\n htmlUrl.pathname = htmlUrl.pathname.replace(/\\.mdx?$/i, '') || '/'\n const htmlDocument = await safeFetch(fetcher, htmlUrl, 'text/html,application/xhtml+xml')\n if (htmlDocument && isInScope(htmlDocument.finalUrl, source, scopePath)\n && /html/i.test(htmlDocument.contentType)) {\n document = htmlDocument\n } else {\n // Never recover by compiling the rejected MDX. A source that does\n // not expose a safe rendered representation is skipped instead.\n return { candidate, page: null, links: [] as Array<string>, failure: false }\n }\n } else if (sanitizedMarkdown !== null) {\n document = { ...document, body: sanitizedMarkdown }\n }\n const responseBytes = Buffer.byteLength(document.body, 'utf8')\n if (importedBytes + responseBytes > maxTotalBytes) {\n isByteBudgetExhausted = true\n return { candidate, page: null, links: [] as Array<string>, failure: false, budgetExceeded: true }\n }\n importedBytes += responseBytes\n const discoveredNavigationId = platform === 'docusaurus'\n ? docusaurusRouteIdForUrl(document.finalUrl, scopePath)\n ?? docusaurusRouteIdForUrl(candidate, scopePath)\n : pageIdForUrl(document.finalUrl, scopePath)\n ?? pageIdForUrl(candidate, scopePath)\n const navigationId = discoveredNavigationId\n && canonicalLocalizedPageId(discoveredNavigationId) === sourceHomePageId\n ? 'introduction'\n : discoveredNavigationId\n if (!navigationId) return { candidate, page: null, links: [] as Array<string>, failure: false }\n const id = platform === 'docusaurus'\n ? storageIdForDocusaurusRoute(navigationId)\n : navigationId\n if (/(?:markdown|text\\/plain)/i.test(document.contentType) || /\\.mdx?$/i.test(document.finalUrl.pathname)) {\n const markdown = markdownPage(document, id, platform)\n if (markdown.page) markdown.page.navigationId = navigationId\n return {\n candidate,\n page: markdown.page,\n openApiFragment: markdown.openApiFragment,\n links: markdownLinks(document.body),\n base: document.finalUrl,\n failure: false,\n }\n }\n const extracted = htmlPage(document, id)\n if (extracted.page) extracted.page.navigationId = navigationId\n const sidebar = platform === 'docusaurus' ? readDocusaurusSidebar(document) : null\n return { candidate, page: extracted.page, links: extracted.links, base: document.finalUrl, sidebar, failure: false }\n }))\n for (const result of results) {\n if (result.failure) {\n warnings.push({ code: 'fetch-failed', message: 'A discovered documentation page could not be fetched.', source: result.candidate.toString() })\n continue\n }\n if (result.budgetExceeded) continue\n if (result.page && platform !== 'docusaurus') {\n result.page.id = canonicalLocalizedPageId(result.page.id)\n result.page.navigationId = canonicalLocalizedPageId(result.page.navigationId)\n }\n const sourceIdentity = result.page\n ? candidateIdentity(new URL(result.page.source))\n : null\n if (result.page && sourceIdentity && !seenSources.has(sourceIdentity)\n && !seenIds.has(result.page.id) && pages.length < maxPages) {\n pages.push(result.page)\n if ('openApiFragment' in result && result.openApiFragment) {\n openApiFragments.push(result.openApiFragment)\n }\n seenIds.add(result.page.id)\n seenSources.add(sourceIdentity)\n }\n if (platform === 'docusaurus' && result.page) {\n const candidateRoute = docusaurusRouteIdForUrl(result.candidate, scopePath)\n if (candidateRoute && candidateRoute !== result.page.navigationId) {\n docusaurusRedirects.push({\n source: candidateRoute === 'introduction' ? '/' : `/${candidateRoute}`,\n destination: result.page.navigationId === 'introduction' ? '/' : `/${result.page.navigationId}`,\n })\n }\n }\n if ('sidebar' in result && result.sidebar) docusaurusSidebars.push(result.sidebar)\n for (const link of result.links) enqueue(link, result.base ?? result.candidate)\n }\n }\n\n if (pages.length === 0) throw new Error('No readable documentation pages were found at that URL.')\n for (const page of pages) {\n const [locale, ...navigationSegments] = page.id.split('/')\n if (LOCALE_CODES.has(locale)) {\n if (navigationSegments.length === 0) page.id = `${locale}/introduction`\n page.locale = locale\n page.navigationId = navigationSegments.join('/') || 'introduction'\n }\n }\n const importedIds = new Set(pages.map((page) => page.navigationId))\n for (const page of pages) {\n page.body = rewriteInternalLinks(\n page.body,\n new URL(page.source),\n source,\n scopePath,\n importedIds,\n sourceHomePageId,\n )\n }\n if (isByteBudgetExhausted) {\n warnings.push({ code: 'limit-reached', message: `Import stopped after reaching the ${Math.round(maxTotalBytes / 1_000_000)} MB content budget.` })\n } else if (queue.length > 0 || queued.size >= MAX_DISCOVERED_URLS) {\n warnings.push({ code: 'limit-reached', message: `Import stopped after ${pages.length} pages; narrow the URL or raise the caller limit to import more.` })\n }\n const topLevelNavigation = sourceTopLevelNavigation?.map((entry) => ({\n ...entry,\n pageId: entry.pageId === sourceHomePageId ? 'introduction' : entry.pageId,\n }))\n let docsConfig = platform === 'docusaurus'\n ? docusaurusNavigationFromSnapshots(docusaurusSidebars, pages, scopePath)\n : hasStructuredMintlifyNavigation && sourceMintlifyProjection\n ? remapNavigationHome(sourceMintlifyProjection.docsConfig, sourceHomePageId)\n : buildNavigationFromPages(pages, {\n topLevelTabs: platform === 'mintlify',\n topLevelNavigation,\n })\n if (sourceMintlifyProjection) warnings.push(...sourceMintlifyProjection.warnings)\n if (docusaurusRedirects.length > 0) {\n docsConfig.redirects = [...new Map(docusaurusRedirects.map((redirect) => [\n `${redirect.source}:${redirect.destination}`,\n redirect,\n ])).values()]\n }\n const openApiAsset = mergeEmbeddedOpenApi(openApiFragments)\n if (openApiAsset) {\n const operationPageIds = new Set(pages.filter((page) => page.openapi).map((page) => page.navigationId))\n const containsOperation = (\n navigationPages: Array<string | MigrationNavigationGroup> = [],\n ): boolean => navigationPages.some((page) => typeof page === 'string'\n ? operationPageIds.has(page)\n : containsOperation(page.pages))\n const apiTab = docsConfig.tabs.find((tab) => (\n containsOperation(tab.pages) || containsOperation(tab.groups)\n )) ?? docsConfig.tabs[0]\n if (apiTab) {\n // Migrated operation pages preserve the source URLs and sidebar order.\n // The spec is still configured for operation rendering, but its derived\n // `/api/*` navigation would duplicate every imported endpoint.\n apiTab.api = { source: '/openapi.yaml', navigation: false }\n }\n }\n const locales = [...new Set(pages.map((page) => page.locale).filter((value): value is string => Boolean(value)))]\n if (locales.length > 0) {\n docsConfig.i18n = {\n defaultLocale: 'en',\n locales: [\n { code: 'en', label: 'English' },\n ...locales.filter((locale) => locale !== 'en').map((locale) => ({ code: locale, label: locale.toUpperCase() })),\n ],\n }\n }\n if (platform === 'mintlify') docsConfig = addMintlifyDirectoryRedirects(docsConfig, pages)\n return {\n sourceUrl: source.toString(),\n sourceKind: 'url',\n platform,\n pages,\n assets: openApiAsset ? [{ path: 'openapi.yaml', content: openApiAsset }] : [],\n docsConfig,\n ...(sourceMintlifyConfig ? {\n site: {\n ...(typeof sourceMintlifyConfig.name === 'string' ? { name: sourceMintlifyConfig.name } : {}),\n ...(typeof sourceMintlifyConfig.description === 'string' ? { description: sourceMintlifyConfig.description } : {}),\n },\n } : {}),\n warnings,\n stats: {\n discovered: visited.size,\n imported: pages.length,\n skipped: Math.max(0, visited.size - pages.length),\n },\n }\n}\n","/**\n * Resolve repository-authored remote OpenAPI references before materializing a\n * site. The local downloader pins a publicly resolved address for each HTTPS\n * hop; hosted callers may inject their own DNS-pinned fetch boundary.\n */\nimport { createHash } from 'node:crypto'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { isIP } from 'node:net'\n\nimport { parse as parseYaml } from 'yaml'\n\nimport type { MigrationBundle, MigrationFetcher } from './types.js'\n\nconst MAX_SPEC_BYTES = 25_000_000\nconst MAX_REDIRECTS = 3\n\nfunction isPublicAddress(address: string, family: number): boolean {\n if (family === 4) {\n const parts = address.split('.').map(Number)\n if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false\n const [a, b] = parts\n return !(a === 0 || a === 10 || a === 127 || a >= 224\n || (a === 100 && b >= 64 && b <= 127)\n || (a === 169 && b === 254)\n || (a === 172 && b >= 16 && b <= 31)\n || (a === 192 && (b === 0 || b === 168))\n || (a === 198 && (b === 18 || b === 19))\n || (a === 203 && b === 0)\n || (a === 198 && b === 51))\n }\n // Global unicast only. This excludes loopback, link-local, unique-local,\n // mapped IPv4, multicast, and every host-local address family.\n return family === 6 && /^[23][0-9a-f]{0,3}:/i.test(address)\n && !/^2001:db8:/i.test(address)\n}\n\nfunction validatedSpecUrl(value: string): URL {\n const url = new URL(value)\n if (url.protocol !== 'https:' || url.username || url.password || isIP(url.hostname)) {\n throw new Error('Remote OpenAPI references must use an HTTPS domain without credentials or an IP literal.')\n }\n url.hash = ''\n return url\n}\n\nasync function getPinnedAddress(url: URL): Promise<{ address: string; family: 4 | 6 }> {\n const addresses = await lookup(url.hostname, { all: true })\n if (addresses.length === 0 || addresses.some((candidate) => !isPublicAddress(candidate.address, candidate.family))) {\n throw new Error('The OpenAPI host did not resolve exclusively to public addresses.')\n }\n return addresses[0] as { address: string; family: 4 | 6 }\n}\n\ninterface SpecResponse {\n status: number\n location?: string\n body: Buffer\n}\n\nasync function requestPinnedSpec(url: URL): Promise<SpecResponse> {\n const pinned = await getPinnedAddress(url)\n return new Promise((resolve, reject) => {\n const req = request(url, {\n headers: { Accept: 'application/json, application/yaml, text/yaml, */*', 'User-Agent': 'Thally-Migrate/1.0 (+https://thally.io)' },\n signal: AbortSignal.timeout(30_000),\n // Node's dual-stack connector asks lookup for `all: true`; that\n // callback must receive address records, not a single address string.\n lookup: (_hostname, options, callback) => {\n if (typeof options === 'object' && options.all) callback(null, [pinned])\n else callback(null, pinned.address, pinned.family)\n },\n }, (response) => {\n const status = response.statusCode ?? 0\n if (status >= 300 && status < 400) {\n response.resume()\n resolve({ status, location: response.headers.location, body: Buffer.alloc(0) })\n return\n }\n if (status < 200 || status >= 300) {\n response.resume()\n reject(new Error(`OpenAPI server returned ${status}.`))\n return\n }\n const statedBytes = Number(response.headers['content-length'] ?? 0)\n if (statedBytes > MAX_SPEC_BYTES) {\n response.destroy()\n reject(new Error('Remote OpenAPI spec exceeds the 25 MB import limit.'))\n return\n }\n const chunks: Array<Buffer> = []\n let bytes = 0\n response.on('data', (chunk: Buffer) => {\n bytes += chunk.length\n if (bytes > MAX_SPEC_BYTES) {\n response.destroy(new Error('Remote OpenAPI spec exceeds the 25 MB import limit.'))\n return\n }\n chunks.push(chunk)\n })\n response.on('end', () => resolve({ status, body: Buffer.concat(chunks) }))\n response.on('error', reject)\n })\n req.on('error', reject)\n req.end()\n })\n}\n\nasync function downloadSpec(value: string, fetcher?: MigrationFetcher): Promise<Buffer> {\n let url = validatedSpecUrl(value)\n if (fetcher) {\n const response = await fetcher(url, { accept: 'application/json, application/yaml, text/yaml' })\n validatedSpecUrl(response.finalUrl.toString())\n const body = Buffer.from(response.body)\n if (body.length > MAX_SPEC_BYTES) throw new Error('Remote OpenAPI spec exceeds the 25 MB import limit.')\n return body\n }\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n const response = await requestPinnedSpec(url)\n if (response.status >= 300 && response.status < 400) {\n if (!response.location || hop === MAX_REDIRECTS) throw new Error('Remote OpenAPI spec redirected too many times.')\n url = validatedSpecUrl(new URL(response.location, url).toString())\n continue\n }\n return response.body\n }\n throw new Error('Remote OpenAPI spec redirected too many times.')\n}\n\ninterface OpenApiOperation {\n method: string\n path: string\n tag: string\n summary: string\n}\n\nfunction parseOpenApi(content: Buffer, extension: string): Array<OpenApiOperation> {\n const text = content.toString('utf8')\n // A remote endpoint may serve YAML from a path without a .yaml suffix.\n const parsed = extension === 'yaml' || !text.trimStart().startsWith('{')\n ? parseYaml(text) as unknown\n : JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('OpenAPI spec is not an object.')\n const document = parsed as Record<string, unknown>\n if (typeof document.openapi !== 'string' || !/^3\\./.test(document.openapi)) {\n throw new Error('Remote specification is not OpenAPI 3.x.')\n }\n if (!document.paths || typeof document.paths !== 'object' || Array.isArray(document.paths)) {\n throw new Error('Remote OpenAPI spec has no paths object.')\n }\n const paths = Object.entries(document.paths as Record<string, unknown>)\n if (paths.length > 5_000) throw new Error('Remote OpenAPI spec has too many paths to import.')\n const operations: Array<OpenApiOperation> = []\n for (const [path, value] of paths) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) continue\n for (const [method, raw] of Object.entries(value as Record<string, unknown>)) {\n if (!/^(get|post|put|patch|delete|head|options|trace)$/i.test(method)\n || !raw || typeof raw !== 'object' || Array.isArray(raw)) continue\n const operation = raw as Record<string, unknown>\n const tags = Array.isArray(operation.tags) ? operation.tags : []\n operations.push({\n method: method.toLowerCase(),\n path,\n tag: typeof tags[0] === 'string' ? tags[0] : 'API Reference',\n summary: typeof operation.summary === 'string' ? operation.summary : String(operation.operationId ?? ''),\n })\n }\n }\n return operations\n}\n\nfunction slug(value: string): string {\n return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n}\n\nfunction operationTarget(operation: OpenApiOperation): string {\n const path = operation.path.split('/').filter(Boolean)\n .map((part) => part.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9-]/g, '-').replace(/-+/g, '-').toLowerCase())\n return `/api/default/${[...path, operation.method].join('/')}`\n}\n\n/**\n * Attach safely downloaded specs to the exact authored API tabs. Source links\n * to Mintlify's tag/summary routes receive redirects only when an operation\n * can be identified uniquely; guessing would silently route to wrong APIs.\n */\nexport async function hydrateRemoteApiSpecs(bundle: MigrationBundle, fetcher?: MigrationFetcher): Promise<MigrationBundle> {\n if (!bundle.remoteApiSpecs?.length) return bundle\n const assets = [...bundle.assets]\n const tabs = bundle.docsConfig.tabs.map((tab) => ({ ...tab }))\n const redirects = [...(bundle.docsConfig.redirects ?? [])]\n const warnings = [...bundle.warnings]\n const authoredLinks = new Set<string>()\n for (const page of bundle.pages) {\n // Scan path-shaped tokens once, then inspect segments without nested\n // regex quantifiers. Authored pages may be arbitrarily long or hostile.\n for (const match of page.body.matchAll(/\\/[a-z0-9_/-]+/gi)) {\n const segments = match[0].split('/').filter(Boolean)\n if (segments.length < 3) continue\n const section = segments[0].toLowerCase()\n if (section.includes('api') || section.includes('reference')) authoredLinks.add(match[0])\n }\n }\n for (const reference of bundle.remoteApiSpecs) {\n for (let index = warnings.length - 1; index >= 0; index--) {\n if (warnings[index].source === reference.url && warnings[index].message.includes('requires a network download')) warnings.splice(index, 1)\n }\n try {\n const url = validatedSpecUrl(reference.url)\n const extension = /\\.ya?ml$/i.test(url.pathname) ? 'yaml' : 'json'\n const body = await downloadSpec(reference.url, fetcher)\n const operations = parseOpenApi(body, extension)\n const filename = `openapi-${createHash('sha256').update(reference.url).digest('hex').slice(0, 12)}.${extension}`\n assets.push({ path: filename, content: body })\n const tab = reference.tabLabel\n ? tabs.find((candidate) => candidate.tab === reference.tabLabel)\n : tabs.find((candidate) => candidate.tab.toLowerCase().includes('api'))\n if (tab) tab.api = { source: `/${filename}` }\n else tabs.push({ tab: reference.tabLabel ?? 'API Reference', api: { source: `/${filename}` } })\n\n const routes = new Map<string, string | null>()\n for (const operation of operations) {\n const key = `${slug(operation.tag)}/${slug(operation.summary)}`\n if (routes.has(key)) routes.set(key, null)\n else routes.set(key, operationTarget(operation))\n }\n const existingSources = new Set(redirects.map((redirect) => redirect.source))\n for (const source of authoredLinks) {\n const parts = source.split('/').filter(Boolean)\n const key = parts.slice(-2).join('/')\n const destination = routes.get(key)\n if (!destination || existingSources.has(source)) continue\n redirects.push({ source, destination, permanent: false })\n existingSources.add(source)\n }\n } catch (error) {\n warnings.push({\n code: 'fetch-failed',\n source: reference.url,\n message: `Remote OpenAPI spec could not be imported: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n return {\n ...bundle,\n assets,\n docsConfig: { ...bundle.docsConfig, tabs, ...(redirects.length > 0 ? { redirects } : {}) },\n warnings,\n }\n}\n"],"mappings":";AAUA,SAAS,eAAAA,oBAAmB;AAC5B,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA,cAAAC;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,qBAAqB;AAC9B,SAAS,YAAAC,WAAU,WAAAC,UAAS,WAAAC,UAAS,cAAAC,aAAY,YAAAC,WAAU,WAAW,aAAa,OAAAC,YAAW;AAE9F,SAAS,SAASC,kBAAiB;AACnC,YAAYC,SAAQ;;;ACvBpB,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,oBAAoB;AACpD,SAAS,UAAU,SAAS,SAAS,YAAAC,WAAU,WAAAC,gBAAe;AAC9D,OAAO,aAAa;AACpB,OAAO,oBAAoB;AAC3B,OAAOC,gBAAe;AACtB,OAAOC,kBAAiB;AACxB,OAAOC,SAAQ;AACf,SAAS,WAAAC,gBAAe;;;ACFxB,SAAS,SAAS,iBAAiB;AAenC,SAAS,wBAAwB,QAAyC;AACxE,QAAM,OAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,CAAC,uBAAuB,KAAK,IAAI,EAAG;AACxC,QAAI;AACF,YAAM,aAAa,UAAU,IAAI;AACjC,UAAI,cAAc,OAAO,eAAe,YAAY,CAAC,MAAM,QAAQ,UAAU,GAAG;AAC9E,eAAO,OAAO,MAAM,UAAU;AAAA,MAChC;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;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,QAAO,IAAI,KAAK,gBAAgB,SAAS,CAAC;AAAA,MACjD;AACA,YAAM,kBAAkB,IAAI,IAAI,UAAU,IAAI,CAAC,aAAa,SAAS,MAAM,CAAC;AAC5E,iBAAW,UAAU,eAAe;AAClC,cAAM,QAAQ,OAAO,MAAM,GAAG,EAAE,OAAO,OAAO;AAC9C,cAAM,MAAM,MAAM,MAAM,EAAE,EAAE,KAAK,GAAG;AACpC,cAAM,cAAc,OAAO,IAAI,GAAG;AAClC,YAAI,CAAC,eAAe,gBAAgB,IAAI,MAAM,EAAG;AACjD,kBAAU,KAAK,EAAE,QAAQ,aAAa,WAAW,MAAM,CAAC;AACxD,wBAAgB,IAAI,MAAM;AAAA,MAC5B;AAAA,IACF,SAAS,OAAO;AACd,eAAS,KAAK;AAAA,QACZ,MAAM;AAAA,QACN,QAAQ,UAAU;AAAA,QAClB,SAAS,8CAA8C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC/G,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,YAAY,EAAE,GAAG,OAAO,YAAY,MAAM,GAAI,UAAU,SAAS,IAAI,EAAE,UAAU,IAAI,CAAC,EAAG;AAAA,IACzF;AAAA,EACF;AACF;","names":["compileSync","existsSync","lstatSync","readFileSync","readdirSync","realpathSync","basename","dirname","extname","isAbsolute","relative","sep","parseYaml","ts","relative","resolve","remarkMdx","remarkParse","ts","unified","root","normalized","closing","ts","unified","remarkParse","remarkMdx","imports","declaredNames","resolve","relative","renameToProp","nextPath","inspect","node","stripDroppedSpreads","bind","root","source","existsSync","lstatSync","readFileSync","extname","posix","parseYaml","existsSync","lstatSync","readFileSync","dirname","extname","relative","existsSync","lstatSync","relative","readFileSync","dirname","value","relative","extname","objectValue","titleCase","slug","posix","lstatSync","readFileSync","existsSync","candidate","resolved","extname","parseYaml","pages","existsSync","lstatSync","readFileSync","basename","dirname","extname","relative","parseYaml","MAX_CONFIG_BYTES","objectValue","titleCase","lstatSync","parseYaml","readFileSync","existsSync","warnOnce","relative","basename","pages","extname","dirname","existsSync","lstatSync","readFileSync","readdirSync","basename","relative","dirname","resolve","extname","realpathSync","sep","compileSync","parseYaml","statement","imports","hash","index","slug","isAbsolute","discovered","declaredNames","assetPaths","load","remarkMdx","remarkParse","unified","parseYaml","unified","remarkParse","remarkMdx","request","load","value","payload","parseYaml","title","converted","candidates","entries","createHash","parseYaml","resolve"]}
|