project-doc-site.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /**
  2. * Build-time projection from canonical repository Markdown into VitePress.
  3. *
  4. * The generated tree is disposable: sources stay in their owning `docs/`
  5. * tier, while this adapter rewrites cross-source links for the public site.
  6. */
  7. import {
  8. copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync,
  9. } from 'node:fs'
  10. import { basename, dirname, extname, posix, relative, resolve, sep } from 'node:path'
  11. import { fromMarkdown } from 'mdast-util-from-markdown'
  12. import { gfmFromMarkdown } from 'mdast-util-gfm'
  13. import { gfm } from 'micromark-extension-gfm'
  14. import type { Nodes } from 'mdast'
  15. import { docsPages, type DocsLocale, type DocsPage } from '../website/docs.ts'
  16. const REPOSITORY_URL = 'https://github.com/deepseek-ai/deepseek-harness'
  17. const root = resolve(import.meta.dirname, '..')
  18. const generatedRoot = resolve(root, 'website/.generated')
  19. interface Replacement {
  20. start: number
  21. end: number
  22. value: string
  23. }
  24. interface DestinationRange {
  25. start: number
  26. end: number
  27. }
  28. type RewritableNode = Extract<Nodes, { type: 'link' | 'image' | 'definition' }>
  29. /** Inputs for rewriting one canonical Markdown page. */
  30. export interface RewriteMarkdownOptions {
  31. locale: DocsLocale
  32. sourcePath: string
  33. route: string
  34. pages: DocsPage[]
  35. repoRoot: string
  36. repositoryRef: string
  37. /**
  38. * Place one referenced image beside the projected page and return the URL to
  39. * reach it from that page. A GitHub raw URL cannot serve this repository —
  40. * `raw.githubusercontent.com` answers 404 for a private one, and no reader of
  41. * the site is authenticated to it — so an image travels into the generated
  42. * tree and Vite bundles it like any other site asset. Omitted by callers that
  43. * only rewrite text, which then leave images pointing at the repository.
  44. */
  45. placeImage?: (absPath: string) => string
  46. }
  47. function repoPath(absPath: string, repoRoot: string): string {
  48. return relative(repoRoot, absPath).split(sep).join('/')
  49. }
  50. function isExternalOrSiteAbsolute(url: string): boolean {
  51. return url.startsWith('#')
  52. || url.startsWith('//')
  53. || url.startsWith('/')
  54. || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  55. }
  56. function skipWhitespace(source: string, start: number): number {
  57. let index = start
  58. while (/\s/.test(source[index] ?? '')) index += 1
  59. return index
  60. }
  61. function labelEnd(source: string): number {
  62. const first = source.indexOf('[')
  63. if (first === -1) return -1
  64. let depth = 0
  65. for (let index = first; index < source.length; index += 1) {
  66. const char = source[index]
  67. if (char === '\\') {
  68. index += 1
  69. } else if (char === '[') {
  70. depth += 1
  71. } else if (char === ']') {
  72. depth -= 1
  73. if (depth === 0) return index
  74. }
  75. }
  76. return -1
  77. }
  78. function destinationRange(rawNode: string, type: 'link' | 'image' | 'definition'): DestinationRange {
  79. const endOfLabel = labelEnd(rawNode)
  80. if (endOfLabel === -1) {
  81. throw new Error(`project-doc-site: cannot locate label end in ${JSON.stringify(rawNode)}.`)
  82. }
  83. let start: number
  84. if (type === 'definition') {
  85. const colon = rawNode.indexOf(':', endOfLabel + 1)
  86. if (colon === -1) {
  87. throw new Error(`project-doc-site: cannot locate definition separator in ${JSON.stringify(rawNode)}.`)
  88. }
  89. start = skipWhitespace(rawNode, colon + 1)
  90. } else {
  91. if (rawNode[endOfLabel + 1] !== '(') {
  92. throw new Error(`project-doc-site: cannot locate inline destination in ${JSON.stringify(rawNode)}.`)
  93. }
  94. start = skipWhitespace(rawNode, endOfLabel + 2)
  95. }
  96. if (rawNode[start] === '<') {
  97. for (let index = start + 1; index < rawNode.length; index += 1) {
  98. if (rawNode[index] === '\\') index += 1
  99. else if (rawNode[index] === '>') return { start: start + 1, end: index }
  100. }
  101. throw new Error(`project-doc-site: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}.`)
  102. }
  103. let depth = 0
  104. for (let index = start; index < rawNode.length; index += 1) {
  105. const char = rawNode[index]
  106. if (char === '\\') {
  107. index += 1
  108. } else if (char === '(') {
  109. depth += 1
  110. } else if (char === ')') {
  111. if (depth === 0) return { start, end: index }
  112. depth -= 1
  113. } else if (/\s/.test(char ?? '') && depth === 0) {
  114. return { start, end: index }
  115. }
  116. }
  117. return { start, end: rawNode.length }
  118. }
  119. // `#fragment` suffixes pass through verbatim. Generated cordis-surface
  120. // headings carry explicit `<a id>` anchors with the GitHub slug, so those
  121. // fragments resolve on the published site too; hand-written headings rely on
  122. // VitePress's own slugger, which differs from GitHub's for punctuation-heavy
  123. // text — hand-authored cross-page fragments should prefer plain-text headings
  124. // or explicit anchors.
  125. function splitTarget(url: string): { path: string; suffix: string } {
  126. const boundary = url.search(/[?#]/)
  127. if (boundary === -1) return { path: url, suffix: '' }
  128. return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
  129. }
  130. function decodePath(path: string): string {
  131. try {
  132. return decodeURIComponent(path)
  133. } catch {
  134. throw new Error(`project-doc-site: malformed percent escape in ${JSON.stringify(path)}.`)
  135. }
  136. }
  137. function routeTarget(fromRoute: string, toRoute: string, suffix: string): string {
  138. const target = posix.relative(posix.dirname(fromRoute), toRoute)
  139. return `${target.startsWith('.') ? target : `./${target}`}${suffix}`
  140. }
  141. function sourceMap(pages: DocsPage[]): Map<string, Map<DocsLocale, DocsPage>> {
  142. const map = new Map<string, Map<DocsLocale, DocsPage>>()
  143. for (const page of pages) {
  144. for (const source of [page.source, ...(page.sourceAliases ?? [])]) {
  145. const localized = map.get(source) ?? new Map<DocsLocale, DocsPage>()
  146. if (localized.has(page.locale)) {
  147. throw new Error(`project-doc-site: duplicate source or alias ${JSON.stringify(source)} for locale ${JSON.stringify(page.locale)}.`)
  148. }
  149. localized.set(page.locale, page)
  150. map.set(source, localized)
  151. }
  152. }
  153. return map
  154. }
  155. function counterpartSource(source: string): string {
  156. return source.endsWith('.zh.md')
  157. ? source.replace(/\.zh\.md$/, '.md')
  158. : source.replace(/\.md$/, '.zh.md')
  159. }
  160. function resolveRepositoryTarget(sourceAbs: string, rawPath: string, repoRoot: string): { absPath: string; line?: number } {
  161. const decoded = decodePath(rawPath)
  162. let absPath = resolve(dirname(sourceAbs), decoded)
  163. if (existsSync(absPath)) return { absPath }
  164. const lineMatch = decoded.match(/:(\d+)$/)
  165. if (lineMatch !== null) {
  166. const lineText = lineMatch[1]
  167. if (lineText === undefined) throw new Error('project-doc-site: line suffix matched without a line number.')
  168. absPath = resolve(dirname(sourceAbs), decoded.slice(0, -lineMatch[0].length))
  169. if (existsSync(absPath)) return { absPath, line: Number.parseInt(lineText, 10) }
  170. }
  171. if (extname(decoded) === '') {
  172. const markdown = resolve(dirname(sourceAbs), `${decoded}.md`)
  173. if (existsSync(markdown)) return { absPath: markdown }
  174. const index = resolve(dirname(sourceAbs), decoded, 'index.md')
  175. if (existsSync(index)) return { absPath: index }
  176. }
  177. throw new Error(`project-doc-site: ${repoPath(sourceAbs, repoRoot)} links to missing path ${JSON.stringify(rawPath)}.`)
  178. }
  179. function githubTarget(
  180. absPath: string,
  181. line: number | undefined,
  182. suffix: string,
  183. repositoryRef: string,
  184. repoRoot: string,
  185. image: boolean,
  186. ): string {
  187. const path = repoPath(absPath, repoRoot)
  188. if (image) return `https://raw.githubusercontent.com/deepseek-ai/deepseek-harness/${repositoryRef}/${path}${suffix}`
  189. const kind = lstatSync(absPath).isDirectory() ? 'tree' : 'blob'
  190. const lineSuffix = line === undefined ? suffix : `#L${line}`
  191. return `${REPOSITORY_URL}/${kind}/${repositoryRef}/${path}${lineSuffix}`
  192. }
  193. /**
  194. * Rewrite repository-relative links without reserializing Markdown.
  195. *
  196. * @param source Markdown text from the canonical file.
  197. * @param options Source, route, manifest, and repository context.
  198. * @returns Markdown whose published links resolve inside the site or to GitHub.
  199. */
  200. export function rewriteMarkdown(source: string, options: RewriteMarkdownOptions): string {
  201. const sourceAbs = resolve(options.repoRoot, options.sourcePath)
  202. const published = sourceMap(options.pages)
  203. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  204. const replacements: Replacement[] = []
  205. const rewrite = (node: RewritableNode): void => {
  206. if (isExternalOrSiteAbsolute(node.url)) return
  207. const { path, suffix } = splitTarget(node.url)
  208. if (path === '') return
  209. const { absPath, line } = resolveRepositoryTarget(sourceAbs, path, options.repoRoot)
  210. const targetPath = repoPath(absPath, options.repoRoot)
  211. const isLanguageSwitcher = targetPath === counterpartSource(options.sourcePath)
  212. const targetLocale: DocsLocale = isLanguageSwitcher
  213. ? options.locale === 'root' ? 'en' : 'root'
  214. : options.locale
  215. const page = published.get(targetPath)?.get(targetLocale)
  216. const nextUrl = page !== undefined
  217. ? routeTarget(options.route, page.route, suffix)
  218. : node.type === 'image' && options.placeImage !== undefined
  219. // The suffix rides along exactly as the GitHub branch keeps it: an SVG
  220. // view fragment or a Vite query changes what the reference means.
  221. ? `${options.placeImage(absPath)}${suffix}`
  222. : githubTarget(absPath, line, suffix, options.repositoryRef, options.repoRoot, node.type === 'image')
  223. const start = node.position?.start.offset
  224. const end = node.position?.end.offset
  225. if (start === undefined || end === undefined) {
  226. throw new Error(`project-doc-site: link ${JSON.stringify(node.url)} has no source offsets.`)
  227. }
  228. const rawNode = source.slice(start, end)
  229. const rawDestination = destinationRange(rawNode, node.type)
  230. replacements.push({
  231. start: start + rawDestination.start,
  232. end: start + rawDestination.end,
  233. value: nextUrl,
  234. })
  235. }
  236. const visit = (node: Nodes): void => {
  237. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) rewrite(node)
  238. if ('children' in node) {
  239. for (const child of node.children) visit(child)
  240. }
  241. }
  242. visit(tree)
  243. let projected = source
  244. for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
  245. projected = projected.slice(0, replacement.start) + replacement.value + projected.slice(replacement.end)
  246. }
  247. return projected
  248. }
  249. /**
  250. * Record the canonical edit target in VitePress frontmatter.
  251. *
  252. * @param markdown Projected Markdown content.
  253. * @param page Publication manifest entry for the content.
  254. * @returns Markdown with projection-owned frontmatter fields.
  255. */
  256. export function addProjectionFrontmatter(markdown: string, page: Pick<DocsPage, 'source' | 'outline'>): string {
  257. const fields = [
  258. `editSource: ${JSON.stringify(page.source)}`,
  259. ...(page.outline === undefined ? [] : [`outline: ${JSON.stringify(page.outline)}`]),
  260. ].join('\n')
  261. if (markdown.startsWith('---\n')) return markdown.replace('---\n', `---\n${fields}\n`)
  262. return `---\n${fields}\n---\n\n${markdown}`
  263. }
  264. /** The switcher line a canonical page carries so its GitHub reader can reach the other language. */
  265. const LANGUAGE_SWITCHER = /^(?:English \| \[中文\]\([^)]*\)|\[English\]\([^)]*\) \| 中文)$/
  266. /** The repository badge a canonical page carries for its GitHub reader. */
  267. const REPOSITORY_BADGE = /^\[!\[[^\]]*\]\(https:\/\/img\.shields\.io\/[^)]*\)\]\([^)]*\)$/
  268. /**
  269. * Drop the lines that address a canonical page's GitHub reader.
  270. *
  271. * The site carries a locale switcher in its navigation bar and links the
  272. * repository from every page, so projecting these lines would repeat both — the
  273. * switcher as the first element under each heading.
  274. *
  275. * @param markdown Rewritten canonical Markdown content.
  276. * @returns The content without the switcher line or the repository badge.
  277. */
  278. function withoutRepositoryChrome(markdown: string): string {
  279. const lines = markdown.split('\n')
  280. const switcher = lines.findIndex(line => LANGUAGE_SWITCHER.test(line))
  281. // Only the switcher introducing the page qualifies; further down the same
  282. // text is prose or a sample rather than the page's own header.
  283. if (switcher !== -1 && switcher < 8) {
  284. lines.splice(switcher, lines[switcher + 1] === '' ? 2 : 1)
  285. }
  286. const badge = lines.findLastIndex(line => REPOSITORY_BADGE.test(line))
  287. if (badge !== -1) {
  288. lines.splice(lines[badge - 1] === '' ? badge - 1 : badge, lines[badge - 1] === '' ? 2 : 1)
  289. }
  290. return lines.join('\n')
  291. }
  292. /**
  293. * Select the Markdown rendered for one published page.
  294. *
  295. * @param markdown Rewritten canonical Markdown content.
  296. * @param page Publication manifest entry for the content.
  297. * @returns Full Markdown for ordinary pages or frontmatter-only Markdown for a locale home page.
  298. */
  299. export function projectedPageContent(markdown: string, page: DocsPage): string {
  300. if (page.sidebar !== null) return withoutRepositoryChrome(markdown)
  301. if (!markdown.startsWith('---\n')) {
  302. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} must start with YAML frontmatter.`)
  303. }
  304. const closingDelimiter = '\n---\n'
  305. const closing = markdown.indexOf(closingDelimiter, 4)
  306. if (closing === -1) {
  307. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} has unclosed YAML frontmatter.`)
  308. }
  309. return markdown.slice(0, closing + closingDelimiter.length)
  310. }
  311. /**
  312. * The repository file one image reference resolves to, or `undefined` when the
  313. * target is not a local file this build may publish.
  314. * @param absPath - resolved image target.
  315. * @param repoRoot - repository root every published image must stay inside.
  316. * @returns the file's real path, or `undefined` when it must not be copied.
  317. *
  318. * Only a regular file whose real path stays inside the repository qualifies.
  319. * Publication copies the bytes into the site, so a reference escaping the
  320. * repository — `../../.ssh/id_rsa`, or a symlink pointing out of the tree —
  321. * would put a build-machine file on the site; `existsSync` alone, which is all
  322. * link resolution needs, does not answer that.
  323. */
  324. export function publishableImage(absPath: string, repoRoot: string): string | undefined {
  325. const real = realpathSync(absPath)
  326. const inside = real === repoRoot || real.startsWith(`${repoRoot}${sep}`)
  327. return inside && statSync(real).isFile() ? real : undefined
  328. }
  329. /** Every local image a published page references, resolved to its repository file. */
  330. function referencedImages(): string[] {
  331. const found = new Set<string>()
  332. for (const page of docsPages) {
  333. const sourceAbs = resolve(root, page.source)
  334. if (!existsSync(sourceAbs)) continue
  335. rewriteMarkdown(readFileSync(sourceAbs, 'utf8'), {
  336. sourcePath: page.source,
  337. locale: page.locale,
  338. route: page.route,
  339. pages: docsPages,
  340. repoRoot: root,
  341. repositoryRef: 'master',
  342. placeImage: (absPath) => {
  343. const real = publishableImage(absPath, root)
  344. if (real !== undefined) found.add(real)
  345. return ''
  346. },
  347. })
  348. }
  349. return [...found]
  350. }
  351. /**
  352. * Files watched by the local VitePress dev server: every canonical Markdown
  353. * source, plus the images they publish. Without the images, replacing a
  354. * screenshot leaves the previous copy in the generated tree until something
  355. * touches the Markdown beside it.
  356. */
  357. export function docsSourceFiles(): string[] {
  358. return [...new Set([...docsPages.map(page => resolve(root, page.source)), ...referencedImages()])]
  359. }
  360. /** Rebuild the disposable VitePress source tree from the publication manifest. */
  361. export function projectDocs(): void {
  362. const routes = new Set<string>()
  363. /** Projected path to the repository file that claimed it, pages and images alike. */
  364. const claimed = new Map<string, string>()
  365. const repositoryRef = process.env.GITHUB_SHA ?? 'master'
  366. rmSync(generatedRoot, { recursive: true, force: true })
  367. /** Reserve one projected path, refusing a second source for it. */
  368. const claim = (target: string, sourceAbs: string): void => {
  369. const holder = claimed.get(target)
  370. if (holder !== undefined && holder !== sourceAbs) {
  371. throw new Error(
  372. `project-doc-site: ${repoPath(sourceAbs, root)} and ${repoPath(holder, root)}`
  373. + ` both project to ${relative(generatedRoot, target).split(sep).join('/')}.`,
  374. )
  375. }
  376. claimed.set(target, sourceAbs)
  377. }
  378. for (const page of docsPages) {
  379. if (routes.has(page.route)) throw new Error(`project-doc-site: duplicate route ${JSON.stringify(page.route)}.`)
  380. routes.add(page.route)
  381. const sourceAbs = resolve(root, page.source)
  382. if (!existsSync(sourceAbs) || !lstatSync(sourceAbs).isFile()) {
  383. throw new Error(`project-doc-site: source ${JSON.stringify(page.source)} does not exist or is not a file.`)
  384. }
  385. const output = resolve(generatedRoot, page.route)
  386. // Claimed before the images are placed: a page and an image landing on one
  387. // path would otherwise overwrite each other in whichever order they ran.
  388. claim(output, sourceAbs)
  389. mkdirSync(dirname(output), { recursive: true })
  390. const markdown = readFileSync(sourceAbs, 'utf8')
  391. const projected = rewriteMarkdown(markdown, {
  392. sourcePath: page.source,
  393. locale: page.locale,
  394. route: page.route,
  395. pages: docsPages,
  396. repoRoot: root,
  397. repositoryRef,
  398. placeImage: (absPath) => {
  399. const real = publishableImage(absPath, root)
  400. if (real === undefined) {
  401. throw new Error(
  402. `project-doc-site: ${page.source} references image ${repoPath(absPath, root)},`
  403. + ' which is not a regular file inside the repository.',
  404. )
  405. }
  406. // Beside the page that references it, under its own basename: each
  407. // locale's route tree gets its own copy, so one relative URL is correct
  408. // from both.
  409. const name = basename(real)
  410. const target = resolve(dirname(output), name)
  411. claim(target, real)
  412. copyFileSync(real, target)
  413. // Encoded because the destination is a Markdown inline target, where an
  414. // unescaped space would end it early.
  415. return `./${encodeURI(name)}`
  416. },
  417. })
  418. writeFileSync(output, addProjectionFrontmatter(projectedPageContent(projected, page), page))
  419. }
  420. }