@thallylabs/migrate 0.2.6 → 0.2.7
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 +156 -7
- package/dist/index.d.ts +99 -8
- package/dist/index.js +4107 -1561
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/repository.ts","../src/components.ts","../src/frontmatter.ts","../src/path.ts","../src/docusaurus.ts","../src/mdx.ts","../src/navigation.ts","../src/render.ts","../src/url.ts"],"sourcesContent":["/**\n * Repository adapter for the shared migration engine. Traversal is bounded,\n * symbolic links are ignored, and Git is always invoked with an argument array\n * so source-controlled branch names can never become shell commands.\n */\n\nimport { spawn } from 'node:child_process'\nimport {\n existsSync,\n lstatSync,\n readFileSync,\n readdirSync,\n} from 'node:fs'\nimport { basename, dirname, extname, relative, resolve as resolvePath } from 'node:path'\n\nimport { createComponentMigrator } from './components.js'\n\nimport {\n projectDocusaurusNavigation,\n readDocusaurusSidebars,\n rewriteDocusaurusLinks,\n resolveDocusaurusPageIdentity,\n type DocusaurusPageDescriptor,\n type DocusaurusSidebars,\n} from './docusaurus.js'\nimport { parseMarkdownPage } from './mdx.js'\nimport {\n addMintlifyDirectoryRedirects,\n addMintlifyHomepageRedirects,\n buildNavigationFromPages,\n isDocumentationExtension,\n projectMintlifyNavigation,\n readMintlifyConfig,\n} from './navigation.js'\nimport {\n normalizeAssetPath,\n mintlifyLocalizedReference,\n pageIdFromReference,\n resolveWithin,\n trimEdgeSlashes,\n trimTrailingSlashes,\n} from './path.js'\nimport type {\n MigrationAsset,\n MigrationBundle,\n MigrationDocsConfig,\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\nconst IGNORED_DIRECTORIES = new Set([\n '.git', '.github', '.next', '.turbo', '.vercel', '.vscode',\n 'node_modules', 'dist', 'build', 'coverage',\n])\nconst ASSET_DIRECTORIES = new Set(['assets', 'images', 'img', 'media', 'public', 'static'])\nconst ASSET_EXTENSIONS = new Set([\n '.avif', '.bmp', '.gif', '.ico', '.jpeg', '.jpg', '.mp3', '.mp4',\n '.pdf', '.png', '.svg', '.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'])\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 Static assets are shared across docs-plugin instances. */\n docusaurusSkipAssets?: boolean\n}\n\ninterface DocusaurusPluginRoot {\n docsDir: string\n routePrefix: 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\nfunction findMintlifyProjectRoot(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 (hasMintlifyConfig(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 (hasMintlifyConfig(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() || IGNORED_DIRECTORIES.has(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): 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 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)) 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() || IGNORED_DIRECTORIES.has(entry.name)) continue\n queue.push({\n directory: resolveWithin(current.directory, entry.name),\n depth: current.depth + 1,\n })\n }\n }\n return null\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\nfunction primaryDocusaurusDocsDirectory(projectRoot: string): string {\n const source = readDocusaurusConfigSource(projectRoot)\n const configured = source.match(/\\bdocs\\s*:\\s*\\{[\\s\\S]{0,4000}?\\bpath\\s*:\\s*(['\"])([^'\"]+)\\1/)?.[2]\n return trimTrailingSlashes(configured?.replace(/^\\.\\//, '') ?? '') || 'docs'\n}\n\nfunction additionalDocusaurusPluginRoots(\n repositoryDir: string,\n projectRoot: string,\n): Array<DocusaurusPluginRoot> {\n const source = readDocusaurusConfigSource(projectRoot)\n const projectRelative = relative(repositoryDir, projectRoot).replace(/\\\\/g, '/')\n const plugins: Array<DocusaurusPluginRoot> = []\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 const docsDir = [projectRelative, localPath].filter(Boolean).join('/')\n const absolute = resolveWithin(repositoryDir, docsDir)\n if (!existsSync(absolute) || !lstatSync(absolute).isDirectory()) continue\n plugins.push({ docsDir, routePrefix })\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\n/** Clone a repository without a shell; callers own and remove `targetDir`. */\nexport async function cloneGitHubRepository(\n source: GitHubRepositorySource,\n targetDir: string,\n): Promise<void> {\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 await new Promise<void>((resolve, reject) => {\n const child = spawn('git', args, { stdio: ['ignore', 'ignore', 'pipe'] })\n let stderr = ''\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', reject)\n child.on('close', (code) => {\n if (code === 0) resolve()\n else reject(new Error(`Failed to clone ${source.owner}/${source.repo}: ${stderr.trim() || `git exited ${code}`}`))\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 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 (IGNORED_DIRECTORIES.has(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\nfunction scanFiles(root: string): Array<ScannedFile> {\n const files: Array<ScannedFile> = []\n function visit(directory: string): void {\n if (files.length >= MAX_SOURCE_FILES) return\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (files.length >= MAX_SOURCE_FILES) return\n if (IGNORED_DIRECTORIES.has(entry.name) || entry.isSymbolicLink()) continue\n const path = resolveWithin(directory, entry.name)\n if (entry.isDirectory()) visit(path)\n else if (entry.isFile()) files.push({ absolutePath: path, relativePath: relative(root, path).replace(/\\\\/g, '/') })\n }\n }\n visit(root)\n return files\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())) ?? null\n}\n\nfunction findConfiguredMintlifyOpenApi(\n config: Record<string, unknown> | null,\n files: Array<ScannedFile>,\n): ScannedFile | null {\n const api = config?.api && typeof config.api === 'object' && !Array.isArray(config.api)\n ? config.api as Record<string, unknown>\n : null\n const configured = typeof api?.openapi === 'string'\n ? [api.openapi]\n : Array.isArray(api?.openapi) ? api.openapi.filter((value): value is string => typeof value === 'string') : []\n for (const reference of configured) {\n if (/^(?:https?:)?\\/\\//i.test(reference)) continue\n const key = reference.split(/[?#]/, 1)[0].replace(/^\\/+/, '').replace(/\\\\/g, '/')\n const match = files.find((file) => file.relativePath === key)\n if (match) return match\n }\n return null\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): string {\n const properties = staticSnippetProperties(attributes)\n if (properties.size === 0) return 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 return properties.get(name) ?? original\n })\n }).join('\\n')\n}\n\nfunction resolveSnippetPath(\n sourcePath: string,\n currentFile: string,\n repositoryRoot: string,\n siteRoot: string,\n): string {\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 const matcher = /^import\\s+(?:\\{\\s*default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}?\\s+from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?(?:\\s*\\/\\/.*)?$/gm\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(matcher)) {\n try {\n const candidate = resolveSnippetPath(match[2], file.absolutePath, repositoryRoot, siteRoot)\n if (existsSync(candidate) && lstatSync(candidate).isFile()) {\n aliases.set(match[1], 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): 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 : resolveWithin(dirname(currentFile), decodedPath)\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 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\nfunction rewriteRepositoryAssetLinks(body: string, currentFile: string, siteRoot: string): 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)\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)\n return rewritten ? `${property}=${quote}${rewritten}${quote}` : original\n })\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 const snippets = new Map<string, string>()\n const withoutImports = raw.replace(\n /^import\\s+(?:\\{\\s*default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}?\\s+from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?(?:\\s*\\/\\/.*)?$/gm,\n (_statement, componentName: string, sourcePath: 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 snippets.set(componentName, nested)\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 // 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 for (const [componentName, candidate] of globalAliases) {\n if (snippets.has(componentName) || !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 snippets.set(componentName, nested)\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) => {\n return interpolateSnippet(snippet, attributes)\n })\n }\n return result\n}\n\nfunction injectOpenApi(config: MigrationDocsConfig, filename: string): MigrationDocsConfig {\n const tabs = config.tabs.map((tab) => ({ ...tab }))\n const apiTab = tabs.find((tab) => tab.tab.toLowerCase().includes('api'))\n if (apiTab) apiTab.api = { source: `/${filename}`, navigation: false }\n else tabs.push({ tab: 'API Reference', api: { source: `/${filename}` } })\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 mintlifyProjectRoot = platform === 'mintlify'\n ? findMintlifyProjectRoot(repositoryDir, options.docsDir)\n : null\n const docusaurusProjectRoot = platform === 'docusaurus'\n ? findDocusaurusProjectRoot(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 return platform === 'mintlify' ? '' : detectRepositoryDocsDir(repositoryDir)\n })()\n const warnings: Array<MigrationWarning> = []\n const componentRoot = mintlifyProjectRoot ?? repositoryDir\n const componentMigrator = platform === 'mintlify'\n ? createComponentMigrator(componentRoot, warnings, componentSourceIdentity(options.sourceUrl, repositoryDir, componentRoot))\n : undefined\n let docsConfig: MigrationDocsConfig = { tabs: [] }\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\n if (platform === 'mintlify') {\n try {\n const config = readMintlifyConfig(mintlifyProjectRoot ?? repositoryDir)\n if (config) {\n mintlifyConfig = 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 === 'docusaurus') {\n try {\n docusaurusSidebars = options.docusaurusSkipSidebar || !docusaurusProjectRoot\n ? null\n : readDocusaurusSidebars(docusaurusProjectRoot)\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 files = scanFiles(contentRoot)\n const pages: Array<MigrationPage> = []\n const assets: Array<MigrationAsset> = []\n const docusaurusDescriptors: Array<DocusaurusPageDescriptor> = []\n const seenPageIds = new Set<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 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 ?? repositoryDir,\n snippetAliases,\n )\n if (componentMigrator) raw = componentMigrator.transform(raw, file.absolutePath)\n let docusaurusDescriptor: Omit<DocusaurusPageDescriptor, 'title'> | undefined\n const page = parseMarkdownPage({\n id,\n navigationId,\n ...(locale ? { locale } : {}),\n raw,\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 })\n if (!page) {\n skipped++\n continue\n }\n if (platform === 'mintlify' && mintlifyProjectRoot) {\n page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, mintlifyProjectRoot)\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 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 }\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 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).map((file) => ({\n ...file,\n relativePath: `${directory}/${file.relativePath}`,\n }))\n })\n : []\n let totalAssetBytes = 0\n for (const file of [...files, ...repositoryAssets]) {\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)) continue\n const size = lstatSync(file.absolutePath).size\n if (size > MAX_ASSET_BYTES || totalAssetBytes + size > MAX_TOTAL_ASSET_BYTES) {\n warnings.push({ code: 'limit-reached', message: 'An asset was skipped because the migration asset budget was exhausted.', source: file.relativePath })\n continue\n }\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 assets.push({ path: assetPath, content: readFileSync(file.absolutePath) })\n totalAssetBytes += size\n }\n\n if (files.length >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Repository discovery stopped at ${MAX_SOURCE_FILES} files.` })\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 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 for (const page of pages) {\n const descriptor = descriptorByNavigationId.get(page.navigationId)\n if (descriptor) page.body = rewriteDocusaurusLinks(page.body, descriptor, docusaurusDescriptors)\n }\n }\n if (docsConfig.tabs.length === 0) docsConfig = buildNavigationFromPages(pages)\n const openApi = findConfiguredMintlifyOpenApi(mintlifyConfig, files) ?? findOpenApi(files)\n if (openApi) {\n const filename = basename(openApi.relativePath)\n if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: readFileSync(openApi.absolutePath) })\n }\n docsConfig = injectOpenApi(docsConfig, filename)\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 }\n\n if (platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipPlugins) {\n for (const plugin of additionalDocusaurusPluginRoots(repositoryDir, docusaurusProjectRoot)) {\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: true,\n docusaurusSkipAssets: true,\n })\n for (const page of pluginBundle.pages) {\n if (seenPageIds.has(page.id)) continue\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.routePrefix\n .split(/[-_/]/)\n .filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\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 (pages.length === 0) throw new Error('No importable Markdown or MDX pages were found in the repository.')\n return {\n sourceUrl: options.sourceUrl,\n sourceKind: 'repository',\n platform,\n pages,\n assets,\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 },\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 { dirname, extname, relative, resolve } from 'node:path'\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 { 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<{ name?: string; type: string; value?: string | { value?: string } | null }>\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\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'])\nconst SHARED_IMPORTS = new Set(['react', 'react/jsx-runtime', 'react/jsx-dev-runtime'])\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\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\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 return [\n references.has('React') && !bindings.has('React') ? \"import * as React from 'react';\" : '',\n hooks.length ? `import { ${hooks.join(', ')} } from 'react';` : '',\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/** Create one bounded component graph and registry for a repository migration. */\nexport function createComponentMigrator(siteRoot: string, warnings: Array<MigrationWarning>, sourceIdentity: string): {\n transform: (raw: string, currentFile: string) => string\n files: () => Array<RenderedMigrationFile>\n} {\n const root = resolve(siteRoot)\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(root, path)\n resolveWithin(root, local)\n let current = root\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 resolveDependency(specifier: string, importer: string): string {\n if (specifier.includes('\\\\') || specifier.includes('\\0') || /[?#]/.test(specifier)) throw new Error('unsupported component dependency path')\n const candidate = specifier.startsWith('/')\n ? resolveWithin(root, specifier.slice(1))\n : resolveWithin(root, relative(root, resolve(dirname(importer), specifier)))\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 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 return `${destinationRoot}/source/${relative(root, 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 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 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): void {\n const specifier = literal.text\n if (SHARED_IMPORTS.has(specifier)) return\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n throw new Error(`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)) dependency(node.moduleSpecifier)\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 staged.set(destination, { path: destination, content: `'use client';\\n\\n${implicitReactImports(ast)}\\n${applyReplacements(text, edits)}` })\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 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 content = parseFrontmatter(raw).content\n const frontmatter = raw.slice(0, raw.length - content.length)\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 return raw\n }\n const aliases = new Map<string, string>()\n const edits: Array<Replacement> = []\n const declarations: Array<{ start: number; end: number; source: string }> = []\n const moduleImports: 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 for (const node of tree.children ?? []) {\n if (node.type !== 'mdxjsEsm' || 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 specifier = ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : ''\n if (!specifier.startsWith('.') && !specifier.startsWith('/')) {\n if (SHARED_IMPORTS.has(specifier)) {\n moduleImports.push(statement.getText(ast))\n sharedImportEdits.push({ start: node.position.start.offset + statement.getStart(ast), end: node.position.start.offset + statement.end, value: '' })\n } else {\n hasUnsupportedImports = true\n warn(`MDX import ${specifier} requires manual package installation or registration; the import was preserved.`, currentFile)\n }\n continue\n }\n if (/\\.mdx?$/.test(specifier)) continue\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 if (bindings.some((binding) => !/^[A-Z]/.test(binding.local))) {\n warn('MDX imports containing non-component values require manual migration; the import was preserved.', currentFile)\n hasUnsupportedImports = true\n continue\n }\n if (hasExpressionReference(new Set(bindings.map((binding) => binding.local)))) {\n warn('Imported components used in MDX expressions, component props, or member tags require manual migration; the import was preserved.', currentFile)\n hasUnsupportedImports = true\n continue\n }\n try {\n const path = copyGraph(resolveDependency(specifier, currentFile))\n for (const binding of bindings) {\n const name = register(path, binding.imported)\n aliases.set(binding.local, name)\n moduleImports.push(`import { ${binding.imported} as ${binding.local} } from ${JSON.stringify(portableSpecifier(`./${relative(destinationRoot, path).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 hasUnsupportedImports = true\n warn(`Custom component was preserved for manual migration: ${error instanceof Error ? error.message : 'unsupported dependency'}.`, currentFile)\n }\n }\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 = false\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)) 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 \"'use client';\", '', ...moduleImports, '', declarationSource, '',\n ...extracted.map(({ name, jsx }) => `export function ${name}() {\\n return (${jsx});\\n}`), '',\n ].join('\\n')\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 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 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 return frontmatter + applyReplacements(content, edits)\n }\n\n function files(): Array<RenderedMigrationFile> {\n if (!registrations.size) return []\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 }), '', 'export const customComponents: MDXComponents = {',\n ...entries.map(([name]) => ` ${name},`), '}', '',\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}\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 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}\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 const baseSegments = /^(?:index|readme)$/i.test(last) ? rawSegments.slice(0, -1) : rawSegments\n if (!/^(?:index|readme)$/i.test(last)) {\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 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 if (isAbsolute(candidate) || candidate.includes('\\0')) {\n throw new Error(`Unsafe migration path: ${candidate}`)\n }\n const target = resolve(root, candidate)\n const fromRoot = relative(resolve(root), 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 { 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 = 1_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\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.\n */\nexport function rewriteDocusaurusLinks(\n body: string,\n current: DocusaurusPageDescriptor,\n descriptors: Array<DocusaurusPageDescriptor>,\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 rewriteTarget(target: string): string {\n if (!target || target.startsWith('#') || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(target)) 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 const candidates = path.startsWith('/')\n ? [sourceReferenceKey(path), sourceReferenceKey(path).replace(/^docs\\//, '')]\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) return target\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*(`{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 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\nfunction readBoundedText(path: string): string {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('Docusaurus sidebar config exceeded the 1 MB static-parser limit.')\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 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): DocusaurusSidebars | null {\n const configured = configuredSidebarPath(repositoryRoot)\n const sourcePath = [configured, ...SIDEBAR_FILENAMES]\n .filter((value): value is string => Boolean(value))\n .find((candidate) => existsSync(resolveWithin(repositoryRoot, candidate)))\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 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\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 items: Array<string | MigrationNavigationGroup> = directPages\n .sort(descriptorSort)\n .map((descriptor) => {\n context.referencedNavigationIds.add(descriptor.navigationId)\n return descriptor.navigationId\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 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 segment,\n group: {\n group: metadata.label ?? titleCase(segment),\n pages,\n } satisfies MigrationNavigationGroup,\n }\n }).sort((left, right) => left.position - right.position\n || left.segment.localeCompare(right.segment, undefined, { numeric: true }))\n items.push(...groups.map((entry) => entry.group))\n return items\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 const loosePages = converted.filter((entry): entry is string => typeof entry === 'string')\n const groups = converted.filter((entry): entry is MigrationNavigationGroup => typeof entry !== 'string')\n if (loosePages.length > 0) groups.unshift({ group: 'Overview', pages: loosePages })\n if (groups.length === 0) return []\n return [{\n tab: sidebarEntries.length === 1 ? 'Documentation' : titleCase(sidebarId),\n groups,\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', groups: [] })\n tabs[0].groups?.push({ group: 'Additional', pages: unreferenced })\n }\n return {\n docsConfig: { tabs },\n generatedPages: context.generatedPages,\n referencedNavigationIds: context.referencedNavigationIds,\n warnings,\n }\n}\n","/** Markdown/MDX normalization that preserves every component Thally supports. */\n\nimport remarkMdx from 'remark-mdx'\nimport remarkParse from 'remark-parse'\nimport { unified } from 'unified'\n\nimport { parseFrontmatter } from './frontmatter.js'\nimport type { MigrationPage } 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(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 }> = []\n let codeFence: string | null = null\n\n return lines.map((line) => {\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 return line\n }\n if (codeFence) return line\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 })\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 }).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 isGlobalDocusaurusImport(line: string): boolean {\n const trimmed = line.trim().replace(/;$/, '').trimEnd()\n if (!trimmed.startsWith('import ')) return false\n const separator = trimmed.indexOf(' from ', 'import '.length)\n if (separator < 0) return false\n const component = trimmed.slice('import '.length, separator).trim()\n if (!GLOBAL_DOCUSARUS_COMPONENTS.has(component)) return false\n const source = trimmed.slice(separator + ' from '.length)\n if (source.length < 3) return false\n const quote = source[0]\n if ((quote !== \"'\" && quote !== '\"') || source.at(-1) !== quote) return false\n const moduleName = source.slice(1, -1)\n return moduleName.startsWith('@theme/') || moduleName.startsWith('@docusaurus/')\n}\n\n/** Normalize only syntax Thally cannot render; supported source JSX stays intact. */\nexport function normalizeMdx(body: string): string {\n // Docusaurus injects these theme components globally. Thally also exposes\n // its equivalents globally, so source-only imports must not survive.\n const withoutGlobalImports = body\n .split('\\n')\n .filter((line) => !isGlobalDocusaurusImport(line))\n .join('\\n')\n return normalizeDocusaurusAdmonitions(withoutGlobalImports)\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 .replace(/<(?:DocCardList|TOCInline)\\b[^>]*\\/>/g, '')\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}\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 /** 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 const body = normalizeMdx(parsed.content).trim()\n const keywords = Array.isArray(parsed.data.keywords)\n ? parsed.data.keywords.filter((value): value is string => typeof value === 'string')\n : []\n const title = typeof parsed.data.title === 'string' && parsed.data.title.trim()\n ? parsed.data.title.trim()\n : titleFromId(identity.navigationId)\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 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 }\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 = 2_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 for (const redirect of config.redirects ?? []) {\n // An authored redirect is evidence that a directory itself was a public\n // route, even when its landing page has no overview/introduction filename.\n // Resolve only that destination, using source navigation order rather than\n // filesystem order. Required parameters and arbitrary patterns stay intact.\n const destination = redirect.destination.split(/[?#]/, 1)[0]\n .replace(/\\/:[A-Za-z_][A-Za-z0-9_]*\\*\\/?$/, '')\n if (!destination.startsWith('/') || destination.startsWith('//') || /[:*()[\\]{}]/.test(destination)) continue\n const directory = trimEdgeSlashes(destination)\n if (!directory || pageIds.has(directory)) continue\n const source = `/${directory}`\n if (hasAuthoredRedirect(source)) continue\n const landing = firstDescendantByDirectory.get(directory)\n if (!landing) 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\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\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\nfunction convertPage(\n value: unknown,\n context: ProjectionContext,\n): string | MigrationNavigationGroup | null {\n if (typeof value === 'string') return registerReference(value, context)\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 container = objectValue(containerValue)\n if (!container) return []\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\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 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 }\n }\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 source = redirect.source.trim()\n const destination = redirect.destination.trim()\n if (!source.startsWith('/') || !destination.startsWith('/')\n || source.startsWith('//') || destination.startsWith('//')) return []\n return [{\n source,\n 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","/** 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.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): {\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 page: parseMarkdownPage({ id, raw, source: document.finalUrl.toString() }),\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)\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"],"mappings":";AAMA,SAAS,aAAa;AACtB;AAAA,EACE,cAAAA;AAAA,EACA,aAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,WAAAC,UAAS,WAAAC,UAAS,YAAAC,WAAU,WAAW,mBAAmB;;;ACP7E,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,oBAAoB;AACpD,SAAS,SAAS,SAAS,YAA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;AAAA,QAC/B,GAAG,QAAQ,OAAO,CAAC,WAAW,WAAW,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,QAAQ,OAAO,OAAO,YAAY,EAAE,EAAE;AAAA,MAChH;AAAA,IACF;AAAA,EACF;AACA,MAAI,aAAa,WAAY,cAAa,8BAA8B,YAAY,KAAK;AACzF,SAAO;AAAA,IACL,WAAW,OAAO,SAAS;AAAA,IAC3B,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA,QAAQ,eAAe,CAAC,EAAE,MAAM,gBAAgB,SAAS,aAAa,CAAC,IAAI,CAAC;AAAA,IAC5E;AAAA,IACA,GAAI,uBAAuB;AAAA,MACzB,MAAM;AAAA,QACJ,GAAI,OAAO,qBAAqB,SAAS,WAAW,EAAE,MAAM,qBAAqB,KAAK,IAAI,CAAC;AAAA,QAC3F,GAAI,OAAO,qBAAqB,gBAAgB,WAAW,EAAE,aAAa,qBAAqB,YAAY,IAAI,CAAC;AAAA,MAClH;AAAA,IACF,IAAI,CAAC;AAAA,IACL;AAAA,IACA,OAAO;AAAA,MACL,YAAY,QAAQ;AAAA,MACpB,UAAU,MAAM;AAAA,MAChB,SAAS,KAAK,IAAI,GAAG,QAAQ,OAAO,MAAM,MAAM;AAAA,IAClD;AAAA,EACF;AACF;","names":["existsSync","lstatSync","readFileSync","dirname","extname","relative","relative","resolve","resolve","relative","inspect","node","bind","existsSync","lstatSync","readFileSync","extname","parseYaml","lstatSync","readFileSync","existsSync","extname","parseYaml","remarkMdx","remarkParse","unified","unified","remarkParse","remarkMdx","existsSync","lstatSync","readFileSync","dirname","extname","relative","objectValue","existsSync","lstatSync","relative","readFileSync","dirname","value","titleCase","extname","existsSync","lstatSync","readFileSync","dirname","relative","resolve","extname","remarkMdx","remarkParse","unified","parseYaml","unified","remarkParse","remarkMdx","value","payload","parseYaml","title","converted","candidates","entries"]}
|
|
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"],"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 existsSync,\n lstatSync,\n readFileSync,\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, relative, resolve as resolvePath, sep } from 'node:path'\n\nimport { parse as parseYaml } from 'yaml'\n\nimport { createComponentMigrator, declarationsReferenceBrowserGlobal, hasAnyFunctionValuedProp, propsTargetExtractedClientComponent } from './components.js'\n\nimport {\n projectDocusaurusNavigation,\n readDocusaurusBrandAssetPaths,\n readDocusaurusRedirects,\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, protectMathBlocks, replaceLinkWithAnchor, replaceUnknownComponents } from './mdx.js'\nimport {\n addMintlifyDirectoryRedirects,\n addMintlifyHomepageRedirects,\n buildNavigationFromPages,\n isDocumentationExtension,\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', '.mp3', '.mp4',\n '.pdf', '.png', '.svg', '.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 = /^import\\s+(?:\\{\\s*(?:default\\s+as\\s+)?([A-Z][A-Za-z0-9_]*)\\s*\\}|([A-Z][A-Za-z0-9_]*))\\s+from\\s+['\"]([^'\"]+\\.mdx?)['\"]\\s*;?(?:\\s*\\/\\/.*)?$/gm\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 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\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\nfunction primaryDocusaurusDocsDirectory(projectRoot: string): string {\n const source = readDocusaurusConfigSource(projectRoot)\n const configured = source.match(/\\bdocs\\s*:\\s*\\{[\\s\\S]{0,4000}?\\bpath\\s*:\\s*(['\"])([^'\"]+)\\1/)?.[2]\n return trimTrailingSlashes(configured?.replace(/^\\.\\//, '') ?? '') || 'docs'\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 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 */\nfunction scanFiles(root: string, confinementRoot: string = root, warnings?: Array<MigrationWarning>): Array<ScannedFile> {\n const files: Array<ScannedFile> = []\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 >= MAX_SOURCE_FILES) 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 >= MAX_SOURCE_FILES) 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 return files\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\n/**\n * Mintlify's `logo`/`favicon` config value is a plain path, or an object\n * with `light`/`dark` (and sometimes `href`, which is a link, not an asset)\n * variants. The referenced files are already copied to `public/` by the\n * ordinary asset scan (they live under the docs tree); only wiring them into\n * the rendered site's actual branding is unsupported (see the warning this\n * feeds — `SiteConfig` has no static logo/favicon field at all, unlike\n * `brand`/`brandPreset`, which the color pipeline above already wires), so\n * this only names them for that warning.\n */\nfunction mintlifyBrandAssetPaths(value: unknown): Array<string> {\n if (typeof value === 'string') return [value]\n if (!value || typeof value !== 'object') return []\n const source = value as Record<string, unknown>\n return (['light', 'dark'] as const)\n .map((key) => source[key])\n .filter((entry): entry is string => typeof entry === 'string')\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())) ?? null\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}\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): 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 warnings.push({\n code: 'unsupported-config',\n message: `The remote OpenAPI spec \"${reference.value}\"${tabSuffix} was not downloaded. Download it manually, add it to public/, and set its API source in docs.json to the local path.`,\n })\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 specs.push({ filename: basename(match.relativePath), content: readFileSync(match.absolutePath), tabLabel: reference.tabLabel })\n }\n return specs\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 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): string {\n const properties = staticSnippetProperties(attributes)\n if (properties.size === 0) return 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 return properties.get(name) ?? original\n })\n }).join('\\n')\n}\n\nfunction resolveSnippetPath(\n sourcePath: string,\n currentFile: string,\n repositoryRoot: string,\n siteRoot: string,\n): string {\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 : resolveWithin(dirname(currentFile), decodedPath)\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 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(/^\\/+/, '')\n const suffix = suffixIndex >= 0 ? target.slice(suffixIndex) : ''\n const renamed = renames.get(path)\n return renamed ? `/${renamed}${suffix}` : 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\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 const snippets = new Map<string, string>()\n const withoutImports = raw.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 snippets.set(componentName, nested)\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 // 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 snippets.set(componentName, nested)\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) => {\n return interpolateSnippet(snippet, attributes)\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 return 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(config: MigrationDocsConfig, specs: Array<{ filename: string; tabLabel?: string }>): 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) apiTab.api = { source: `/${spec.filename}`, navigation: false }\n else tabs = [...tabs, { tab: spec.tabLabel ?? 'API Reference', api: { source: `/${spec.filename}` } }]\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 // Only the current, default-locale docs are imported (`configuredDocsDir`,\n // below, never points inside these). Thally has no versions concept and\n // Docusaurus' own i18n content lives in a separate tree this adapter does\n // not project, so both are reported rather than silently dropped.\n if (platform === 'docusaurus' && docusaurusProjectRoot) {\n for (const [directory, label] of [\n ['versioned_docs', 'versioned docs'],\n ['versioned_sidebars', 'versioned sidebars'],\n ] as const) {\n const path = resolveWithin(docusaurusProjectRoot, directory)\n if (!existsSync(path) || !lstatSync(path).isDirectory()) continue\n const versions = readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)\n if (versions.length) warnings.push({\n code: 'unsupported-config',\n message: `Docusaurus ${label} were skipped; only current docs were imported. Skipped: ${versions.join(', ')}.`,\n source: directory,\n })\n }\n const i18nPath = resolveWithin(docusaurusProjectRoot, 'i18n')\n if (existsSync(i18nPath) && lstatSync(i18nPath).isDirectory()) {\n const locales = readdirSync(i18nPath, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)\n if (locales.length) warnings.push({\n code: 'unsupported-config',\n message: `Docusaurus localized content was skipped; only the default locale was imported. Skipped locales: ${locales.join(', ')}.`,\n source: 'i18n',\n })\n }\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 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 fernApiSections: Array<FernApiSection> = []\n\n if (platform === 'mintlify') {\n try {\n const config = readMintlifyConfig(mintlifyProjectRoot ?? repositoryDir)\n if (config) {\n mintlifyConfig = 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 const projected = projectFernNavigation({ config: fernConfig.config, fernRoot: fernProjectRoot })\n docsConfig = projected.docsConfig\n warnings.push(...projected.warnings)\n fernApiSections = projected.apiSections\n for (const [index, descriptor] of projected.descriptors.entries()) {\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 }\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)\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 const files = mintignoreMatcher\n ? scanFiles(contentRoot, repositoryDir, warnings).filter((file) => !mintignoreMatcher.ignores(file.relativePath))\n : scanFiles(contentRoot, repositoryDir, warnings)\n const pages: Array<MigrationPage> = []\n const assets: Array<MigrationAsset> = []\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 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 (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 // raw `$$\\begin{align*}...\\end{align*}$$` crashes that parser outright\n // (see `protectMathBlocks`), which is what excluded these pages\n // before this ran.\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 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 (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 page.body = rewriteRepositoryAssetLinks(page.body, file.absolutePath, fernProjectRoot, (assetPath) => {\n addAssetReference(assetPath, file.relativePath)\n })\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 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 }\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 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]) {\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)) 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: referencingPages\n ? `Asset was skipped because the migration asset budget was exhausted, but it is referenced by: ${[...referencingPages].join(', ')}.`\n : 'An asset was skipped because the migration asset budget was exhausted.',\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 if (files.length >= MAX_SOURCE_FILES) {\n warnings.push({ code: 'limit-reached', message: `Repository discovery stopped at ${MAX_SOURCE_FILES} files.` })\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 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 for (const page of pages) {\n const descriptor = descriptorByNavigationId.get(page.navigationId)\n if (descriptor) page.body = rewriteDocusaurusLinks(page.body, descriptor, docusaurusDescriptors)\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 (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 }> = fernApiSections.length > 0\n ? fernApiSections\n : [{ nameExplicit: false }]\n const resolvedSpecs: Array<{ filename: string; tabLabel?: 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 if (!assets.some((asset) => asset.path === filename)) {\n assets.push({ path: filename, content: readFileSync(spec.absolutePath) })\n }\n resolvedSpecs.push({ filename, tabLabel: section.tabLabel })\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) docsConfig = injectOpenApiSpecs(docsConfig, resolvedSpecs)\n } else if (platform === 'mintlify') {\n const resolvedSpecs = resolveMintlifyApiSpecs(mintlifyConfig, files, warnings)\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)\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 }\n\n if (platform === 'docusaurus' && docusaurusProjectRoot && !options.docusaurusSkipPlugins) {\n for (const plugin of additionalDocusaurusPluginRoots(repositoryDir, docusaurusProjectRoot, warnings)) {\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: true,\n docusaurusSkipAssets: true,\n docusaurusSkipRedirects: true,\n })\n for (const page of pluginBundle.pages) {\n if (seenPageIds.has(page.id)) continue\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.routePrefix\n .split(/[-_/]/)\n .filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\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 // 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 docsConfig = pruneMissingNavigationPages(docsConfig, new Set(pages.map((page) => page.navigationId)))\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 themeColors = mintlifyConfig\n ? mintlifyThemeColors(mintlifyConfig.colors)\n : fernRawConfig\n ? fernThemeColors(fernRawConfig.colors)\n : isTopLevelDocusaurus ? readDocusaurusThemeColor(docusaurusProjectRoot!) : undefined\n // Thally's `SiteConfig` has no static logo/favicon field (unlike\n // `brand`/`brandPreset`, which the color pipeline above already wires):\n // branding is admin-managed at runtime. The referenced files are still\n // copied to `public/` by the ordinary asset scan, so name them and point\n // at where to wire them up manually instead of leaving the loss silent.\n // Fern already emits its own version of this warning (`fern.ts`).\n const brandAssetPaths = mintlifyConfig\n ? [...mintlifyBrandAssetPaths(mintlifyConfig.logo), ...mintlifyBrandAssetPaths(mintlifyConfig.favicon)]\n : isTopLevelDocusaurus ? readDocusaurusBrandAssetPaths(docusaurusProjectRoot!) : []\n if (brandAssetPaths.length > 0) {\n warnings.push({\n code: 'unsupported-config',\n message: `The site's logo/favicon (${brandAssetPaths.join(', ')}) were copied into public/ but are not wired into the migrated site's branding, which Thally manages from the admin dashboard rather than a static config field; set them there after the site is deployed.`,\n })\n }\n return {\n sourceUrl: options.sourceUrl,\n sourceKind: 'repository',\n platform,\n pages,\n assets,\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 } : 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 { isFunctionInitializer, normalizeHtmlComments } 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/** 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 return [\n references.has('React') && !bindings.has('React') ? \"import * as React from 'react';\" : '',\n hooks.length ? `import { ${hooks.join(', ')} } from 'react';` : '',\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 */\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 const content = 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 return raw\n }\n const aliases = new Map<string, string>()\n const unsupportedImports = new Map<string, 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 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 // 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 moduleImports.push(statement.getText(ast))\n 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)) continue\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 value: bindings.map((binding) => `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 if (bindings.some((binding) => !/^[A-Z]/.test(binding.local))) {\n warn('MDX imports containing non-component values require manual migration; 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 path = copyGraph(resolveDependency(specifier, currentFile))\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 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 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 value: bindings.map((binding) => `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 // 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 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 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 realImportsBlock = realPageImports.length ? `${[...new Set(realPageImports)].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}\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 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}\n","/** Markdown/MDX normalization that preserves every component Thally supports. */\n\nimport type * as acorn from 'acorn'\nimport { compileSync } from '@mdx-js/mdx'\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(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 }> = []\n let codeFence: string | null = null\n\n return lines.map((line) => {\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 return line\n }\n if (codeFence) return line\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 })\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 }).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 isGlobalDocusaurusImport(line: string): boolean {\n const trimmed = line.trim().replace(/;$/, '').trimEnd()\n if (!trimmed.startsWith('import ')) return false\n const separator = trimmed.indexOf(' from ', 'import '.length)\n if (separator < 0) return false\n const component = trimmed.slice('import '.length, separator).trim()\n if (!GLOBAL_DOCUSARUS_COMPONENTS.has(component)) return false\n const source = trimmed.slice(separator + ' from '.length)\n if (source.length < 3) return false\n const quote = source[0]\n if ((quote !== \"'\" && quote !== '\"') || source.at(-1) !== quote) return false\n const moduleName = source.slice(1, -1)\n return moduleName.startsWith('@theme/') || moduleName.startsWith('@docusaurus/')\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/**\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 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/** 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 if (BARE_IDENTIFIER_PATH.test(value) && !JS_LITERAL_KEYWORDS.has(value)\n && !declared.has(root) && !safeBuiltinPath && start !== undefined && end !== undefined) {\n edits.push({ start, end, value: `\\\\{${value}\\\\}` })\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*(`{3,}|~{3,})/)\n if (codeFence) {\n fenceBuffer.push(line)\n if (fenceMatch && fenceMatch[1][0] === codeFence) {\n lines.push(stash(fenceBuffer.join('\\n')))\n codeFence = null\n fenceBuffer = []\n }\n continue\n }\n if (fenceMatch) {\n codeFence = fenceMatch[1][0]\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 */\nfunction replaceOutsideCode(body: string, transform: (whole: string) => string): string {\n const { masked, unmask } = maskCode(body)\n return unmask(transform(masked))\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 * the stack order only holds up when both passes run over the whole body in\n * document order, which `replaceOutsideCode` provides.\n */\nfunction normalizeFernCallouts(body: string): string {\n return replaceOutsideCode(body, (whole) => {\n const openTags: Array<string> = []\n return whole\n .replace(/<Callout\\s+intent=(?:\"([^\"]*)\"|'([^']*)')([^>]*?)(\\/?)>/g, (_match, doubleQuoted: string, singleQuoted: string, rest: string, selfClose: string) => {\n const intent = (doubleQuoted ?? singleQuoted ?? '').toLowerCase()\n const tag = intent === 'warning'\n ? 'Warning'\n : intent === 'success' || intent === 'tip'\n ? 'Tip'\n : intent === 'error' || intent === 'danger' ? 'Error' : 'Note'\n if (!selfClose) openTags.push(tag)\n return `<${tag}${rest}${selfClose}>`\n })\n // Only rewrite closes paired with a Fern `<Callout intent=\"...\">` we\n // actually opened; a bare Mintlify `<Callout>...</Callout>` (no\n // `intent`) never pushed a tag, so its closing tag must stay as-is.\n .replace(/<\\/Callout>/g, (match) => openTags.length ? `</${openTags.pop()}>` : match)\n })\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 return body.replace(/<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*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 `<Tabs${cleanedAttributes}>${rewrittenInner}</Tabs>`\n })\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/** Normalize only syntax Thally cannot render; supported source JSX stays intact. */\nexport function normalizeMdx(body: string, platform?: MigrationPlatform): 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 let rewritten = normalizeDocusaurusAdmonitions(runFern ? normalizeFernCallouts(body) : body)\n if (runDocusaurus) {\n // Docusaurus injects these theme components globally. Thally also\n // exposes its equivalents globally, so source-only imports must not survive.\n const withoutGlobalImports = rewritten\n .split('\\n')\n .filter((line) => !isGlobalDocusaurusImport(line))\n .join('\\n')\n rewritten = normalizeDocusaurusTabBlocks(normalizeDocusaurusTabs(withoutGlobalImports))\n }\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 .replace(/<(?:DocCardList|TOCInline)\\b[^>]*\\/>/g, '')\n }\n if (runMintlify) {\n result = 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 return provideScopedGlobalReferences(rewritten)\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 const 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 title = typeof parsed.data.title === 'string' && parsed.data.title.trim()\n ? parsed.data.title.trim()\n : titleFromId(identity.navigationId)\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 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 }\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 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 = 1_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\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.\n */\nexport function rewriteDocusaurusLinks(\n body: string,\n current: DocusaurusPageDescriptor,\n descriptors: Array<DocusaurusPageDescriptor>,\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 rewriteTarget(target: string): string {\n if (!target || target.startsWith('#') || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(target)) 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 const candidates = path.startsWith('/')\n ? [sourceReferenceKey(path), sourceReferenceKey(path).replace(/^docs\\//, '')]\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) return target\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*(`{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 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\nfunction readBoundedText(path: string): string {\n if (lstatSync(path).size > MAX_CONFIG_BYTES) {\n throw new Error('Docusaurus sidebar config exceeded the 1 MB static-parser limit.')\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 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): DocusaurusSidebars | null {\n const configured = configuredSidebarPath(repositoryRoot)\n const sourcePath = [configured, ...SIDEBAR_FILENAMES]\n .filter((value): value is string => Boolean(value))\n .find((candidate) => existsSync(resolveWithin(repositoryRoot, candidate)))\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\n/**\n * Name the source config's top-level `favicon` and `themeConfig.navbar.logo`\n * (`src`/`srcDark`) paths, so migration can warn about them by name. The\n * files themselves are already copied to `public/` by the ordinary\n * `static/`/`public/` asset scan (`repository.ts`) — Thally's `SiteConfig`\n * just has no static field to point at them (branding is admin-managed at\n * runtime, unlike the `brand`/`brandPreset` color pipeline above).\n */\nexport function readDocusaurusBrandAssetPaths(repositoryRoot: string): Array<string> {\n const configPath = findDocusaurusConfigPath(repositoryRoot)\n if (!configPath) return []\n const configSource = readBoundedText(configPath)\n const favicon = configSource.match(/\\bfavicon\\s*:\\s*(['\"])([^'\"]+)\\1/)?.[2]\n const logoBlock = configSource.match(/\\blogo\\s*:\\s*\\{([^}]*)\\}/)?.[1]\n const logo = logoBlock?.match(/\\bsrc\\s*:\\s*(['\"])([^'\"]+)\\1/)?.[2]\n const logoDark = logoBlock?.match(/\\bsrcDark\\s*:\\s*(['\"])([^'\"]+)\\1/)?.[2]\n return [favicon, logo, logoDark].filter((path): path is string => typeof path === 'string')\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 items: Array<string | MigrationNavigationGroup> = directPages\n .sort(descriptorSort)\n .map((descriptor) => {\n context.referencedNavigationIds.add(descriptor.navigationId)\n return descriptor.navigationId\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 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 segment,\n group: {\n group: metadata.label ?? titleCase(segment),\n pages,\n } satisfies MigrationNavigationGroup,\n }\n }).sort((left, right) => left.position - right.position\n || left.segment.localeCompare(right.segment, undefined, { numeric: true }))\n items.push(...groups.map((entry) => entry.group))\n return items\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 const loosePages = converted.filter((entry): entry is string => typeof entry === 'string')\n const groups = converted.filter((entry): entry is MigrationNavigationGroup => typeof entry !== 'string')\n if (loosePages.length > 0) groups.unshift({ group: 'Overview', pages: loosePages })\n if (groups.length === 0) return []\n return [{\n tab: sidebarEntries.length === 1 ? 'Documentation' : titleCase(sidebarId),\n groups,\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', groups: [] })\n tabs[0].groups?.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 = 2_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 for (const redirect of config.redirects ?? []) {\n // An authored redirect is evidence that a directory itself was a public\n // route, even when its landing page has no overview/introduction filename.\n // Resolve only that destination, using source navigation order rather than\n // filesystem order. Required parameters and arbitrary patterns stay intact.\n const destination = redirect.destination.split(/[?#]/, 1)[0]\n .replace(/\\/:[A-Za-z_][A-Za-z0-9_]*\\*\\/?$/, '')\n if (!destination.startsWith('/') || destination.startsWith('//') || /[:*()[\\]{}]/.test(destination)) continue\n const directory = trimEdgeSlashes(destination)\n if (!directory || pageIds.has(directory)) continue\n const source = `/${directory}`\n if (hasAuthoredRedirect(source)) continue\n const landing = firstDescendantByDirectory.get(directory)\n if (!landing) 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\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}\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(node: Record<string, unknown>, tabLabel: string | undefined): void {\n if (typeof node.openapi === 'string' && node.openapi.trim()) {\n references.push({ value: node.openapi.trim(), kind: 'openapi', tabLabel })\n }\n if (typeof node.asyncapi === 'string' && node.asyncapi.trim()) {\n references.push({ value: node.asyncapi.trim(), kind: 'asyncapi', tabLabel })\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\nfunction convertPage(\n value: unknown,\n context: ProjectionContext,\n): string | MigrationNavigationGroup | null {\n if (typeof value === 'string') return registerReference(value, context)\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 container = objectValue(containerValue)\n if (!container) return []\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/** 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 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 }\n }\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 nodes.flatMap((node): Array<string | MigrationNavigationGroup> => {\n if (typeof node === 'string') return availableIds.has(node) ? [node] : []\n const pages = pruneNodes(node.pages)\n return pages.length > 0 ? [{ ...node, pages }] : []\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 } from 'node:fs'\nimport { dirname, relative } from 'node:path'\n\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 = 2_000_000\n\nexport interface FernPageDescriptor {\n /** Path to the referenced page file, relative to the Fern root. */\n sourcePath: string\n navigationId: string\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}\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('Fern config exceeded the 2 MB static-parser limit.')\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 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 warnings: Array<MigrationWarning>\n warningKeys: Set<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 /**\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 const explicit = typeof value.slug === 'string' ? value.slug.trim() : ''\n if (!explicit) return fernLabelSlug(label) || 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): string {\n const relativePath = rawPath.trim().replace(/^\\.\\//, '')\n const sourcePath = context.pathPrefix ? `${context.pathPrefix}/${relativePath}` : relativePath\n const navigationId = uniqueNavigationId(base || 'introduction', context)\n context.seenNavigationIds.add(navigationId)\n context.descriptors.push({ sourcePath, navigationId })\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) return kept\n context.sourcePathToNavigationId.set(sourcePath, navigationId)\n return navigationId\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)\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') return registerPage(object, parentSegments, context)\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 pages.push(registerPageAt(object.path as string, segments.join('/'), context))\n }\n for (const child of contents) {\n const converted = convertNode(child, segments, 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 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 warnOnce(\n context,\n 'fern-link',\n 'Fern navigation \"link\" entries are external and cannot be nested inside a Thally group; add them to the navbar manually.',\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 context.apiSections.push({\n name: typeof object['api-name'] === 'string' ? object['api-name'] : object.api,\n nameExplicit: typeof object['api-name'] === 'string',\n routeSegments: parentSegments,\n })\n return null\n }\n\n if (typeof object.changelog === 'string') {\n warnOnce(context, 'fern-changelog', 'Fern changelog sections are not supported and were omitted.')\n return null\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); `fernRoot` remains the security boundary.\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, fernRoot)\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 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) => {\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) 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}): FernNavigationResult {\n const context: WalkContext = {\n descriptors: [],\n seenNavigationIds: new Set(),\n apiSections: [],\n warnings: [],\n warningKeys: new Set(),\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\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 // `title`/`colors.accent-primary` are mapped by the repository adapter into\n // `MigrationBundle.site`; logo/favicon files live under `public/brand/` by\n // fixed filename rather than a docs.json-style config field, so they can\n // only be flagged for manual follow-up here.\n if (config.logo || config.favicon) {\n warnOnce(\n context,\n 'fern-branding',\n 'Fern logo and favicon were not migrated; add them to public/brand/ (default-logo-light.svg, default-logo-dark.svg, default-favicon-light.svg, default-favicon-dark.svg).',\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 const tabLabel = distinguishingSegment ? `${section.tabLabel}: ${titleCase(distinguishingSegment)}` : section.tabLabel\n claimedTabLabels.add(tabLabel)\n return { ...section, tabLabel }\n })\n\n return {\n docsConfig: {\n tabs,\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 }\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.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"],"mappings":";AAUA,SAAS,eAAAA,oBAAmB;AAC5B,SAAS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B,KAAK,IAAI,CAAC;AAAA,QAC3F,GAAI,OAAO,qBAAqB,gBAAgB,WAAW,EAAE,aAAa,qBAAqB,YAAY,IAAI,CAAC;AAAA,MAClH;AAAA,IACF,IAAI,CAAC;AAAA,IACL;AAAA,IACA,OAAO;AAAA,MACL,YAAY,QAAQ;AAAA,MACpB,UAAU,MAAM;AAAA,MAChB,SAAS,KAAK,IAAI,GAAG,QAAQ,OAAO,MAAM,MAAM;AAAA,IAClD;AAAA,EACF;AACF;","names":["compileSync","existsSync","lstatSync","readFileSync","realpathSync","basename","dirname","extname","relative","sep","parseYaml","relative","resolve","remarkMdx","remarkParse","unified","root","unified","remarkParse","remarkMdx","imports","resolve","relative","renameToProp","nextPath","inspect","node","bind","existsSync","lstatSync","readFileSync","extname","parseYaml","existsSync","lstatSync","readFileSync","dirname","extname","relative","existsSync","lstatSync","relative","readFileSync","dirname","value","relative","extname","objectValue","titleCase","lstatSync","readFileSync","existsSync","extname","parseYaml","existsSync","lstatSync","readFileSync","dirname","relative","parseYaml","MAX_CONFIG_BYTES","objectValue","titleCase","lstatSync","parseYaml","readFileSync","existsSync","warnOnce","dirname","relative","existsSync","lstatSync","readFileSync","basename","relative","dirname","resolve","extname","realpathSync","sep","compileSync","parseYaml","remarkMdx","remarkParse","unified","parseYaml","unified","remarkParse","remarkMdx","value","payload","parseYaml","title","converted","candidates","entries"]}
|