translation-links.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /** Locale-aware resolution and byte-preserving rewrites for bilingual Markdown links. */
  2. import { existsSync, statSync } from 'node:fs'
  3. import { posix, resolve } from 'node:path'
  4. import type { Nodes } from 'mdast'
  5. import {
  6. isExternalOrAbsoluteMarkdownUrl,
  7. markdownDestination,
  8. parseMarkdown,
  9. splitMarkdownUrlTarget,
  10. visitMarkdown,
  11. type MarkdownDestination,
  12. } from './markdown.ts'
  13. /** Repository and source document used to resolve one relative link. */
  14. export interface TranslationLinkContext {
  15. /** Absolute repository root. */
  16. repoRoot: string
  17. /** Repository-relative Markdown source path. */
  18. sourcePath: string
  19. /** Whether an English Markdown path belongs to the active bilingual corpus. */
  20. isTranslationPairSource: (sourcePath: string) => boolean
  21. /** Selected content plane; defaults to regular files in the working tree. */
  22. repositoryFileExists?: (repoPath: string) => boolean
  23. }
  24. /** One relative document link whose target uses the wrong locale sibling. */
  25. export interface TranslationLinkLocaleViolation {
  26. sourcePath: string
  27. line: number
  28. url: string
  29. expectedUrl: string
  30. }
  31. /** Result of rewriting wrong-locale relative document links. */
  32. export interface TranslationLinkRewriteResult {
  33. content: string
  34. rewritten: number
  35. }
  36. interface TranslationPairTarget {
  37. source: string
  38. zh: string
  39. }
  40. interface ResolvedTranslationLink {
  41. pair: TranslationPairTarget
  42. targetPath: string
  43. suffix: string
  44. expectedPath: string
  45. expectedUrl: string
  46. locale: 'en' | 'zh'
  47. }
  48. interface Replacement {
  49. start: number
  50. end: number
  51. value: string
  52. }
  53. type LinkNode = Extract<Nodes, { type: 'link' | 'definition' }>
  54. /** Offset of the one top-level switcher link immediately following the H1. */
  55. export function languageSwitcherLinkOffset(
  56. tree: Nodes,
  57. markdown: string,
  58. acceptedTargets: string | readonly string[],
  59. ): number | undefined {
  60. if (tree.type !== 'root') return undefined
  61. const accepted = new Set(typeof acceptedTargets === 'string' ? [acceptedTargets] : acceptedTargets)
  62. const headingIndex = tree.children.findIndex(node => node.type === 'heading' && node.depth === 1)
  63. if (headingIndex < 0) return undefined
  64. for (const node of tree.children.slice(headingIndex + 1)) {
  65. if (node.type === 'heading') return undefined
  66. if (node.type !== 'paragraph' || node.position === undefined) continue
  67. const start = node.position.start.offset
  68. const end = node.position.end.offset
  69. if (start === undefined || end === undefined) continue
  70. const authored = markdown.slice(start, end)
  71. if (!/^(?:English \| \[中文\]\([^\n]+\)|\[English\]\([^\n]+\) \| 中文)$/.test(authored)) continue
  72. const links = node.children.filter((child): child is Extract<Nodes, { type: 'link' }> => child.type === 'link')
  73. if (links.length === 1 && accepted.has(links[0]?.url ?? '')) {
  74. return links[0]?.position?.start.offset
  75. }
  76. }
  77. return undefined
  78. }
  79. /** Whether the tree carries its canonical top-level language switcher. */
  80. export function hasLanguageSwitcher(
  81. tree: Nodes,
  82. markdown: string,
  83. acceptedTargets: string | readonly string[],
  84. ): boolean {
  85. return languageSwitcherLinkOffset(tree, markdown, acceptedTargets) !== undefined
  86. }
  87. function decodePath(path: string): string {
  88. try {
  89. return decodeURIComponent(path)
  90. } catch {
  91. return path
  92. }
  93. }
  94. function worktreeFileExists(repoRoot: string, repoPath: string): boolean {
  95. try {
  96. const path = resolve(repoRoot, repoPath)
  97. return existsSync(path) && statSync(path).isFile()
  98. } catch {
  99. return false
  100. }
  101. }
  102. function repositoryFileExists(context: TranslationLinkContext, repoPath: string): boolean {
  103. return context.repositoryFileExists?.(repoPath) ?? worktreeFileExists(context.repoRoot, repoPath)
  104. }
  105. function repositoryRelativePath(path: string): string | undefined {
  106. const normalized = posix.normalize(path)
  107. if (normalized === '' || normalized === '.' || normalized === '..' || normalized.startsWith('../') || posix.isAbsolute(normalized)) {
  108. return undefined
  109. }
  110. return normalized
  111. }
  112. function resolveRepositoryTarget(
  113. rawPath: string,
  114. context: TranslationLinkContext,
  115. ): string | undefined {
  116. const decoded = decodePath(rawPath)
  117. const exact = repositoryRelativePath(posix.join(posix.dirname(context.sourcePath), decoded))
  118. if (exact === undefined) return undefined
  119. return repositoryFileExists(context, exact) ? exact : undefined
  120. }
  121. function translationPairTarget(targetPath: string, context: TranslationLinkContext): TranslationPairTarget | undefined {
  122. const source = targetPath.endsWith('.zh.md')
  123. ? targetPath.replace(/\.zh\.md$/, '.md')
  124. : targetPath.endsWith('.md') ? targetPath : undefined
  125. if (source === undefined || !context.isTranslationPairSource(source)) return undefined
  126. const zh = source.replace(/\.md$/, '.zh.md')
  127. return { source, zh }
  128. }
  129. function encodePathSegment(segment: string): string {
  130. return encodeURIComponent(segment).replace(/[!'()*]/g, character => (
  131. `%${character.charCodeAt(0).toString(16).toUpperCase()}`
  132. ))
  133. }
  134. function relativeExpectedPath(
  135. context: TranslationLinkContext,
  136. expectedPath: string,
  137. rawPath: string,
  138. ): string {
  139. const relative = posix.relative(posix.dirname(context.sourcePath), expectedPath)
  140. const encoded = relative.split('/').map(encodePathSegment).join('/')
  141. return rawPath.startsWith('./') && !encoded.startsWith('.') ? `./${encoded}` : encoded
  142. }
  143. function expectedLocalePath(
  144. rawPath: string,
  145. locale: 'en' | 'zh',
  146. context: TranslationLinkContext,
  147. expectedPath: string,
  148. ): string {
  149. if (locale === 'zh' && rawPath.endsWith('.md') && !rawPath.endsWith('.zh.md')) {
  150. return rawPath.replace(/\.md$/, '.zh.md')
  151. }
  152. if (locale === 'en' && rawPath.endsWith('.zh.md')) return rawPath.replace(/\.zh\.md$/, '.md')
  153. return relativeExpectedPath(context, expectedPath, rawPath)
  154. }
  155. function resolveTranslationLink(
  156. url: string,
  157. context: TranslationLinkContext,
  158. authoredUrl: string,
  159. ): ResolvedTranslationLink | undefined {
  160. if (isExternalOrAbsoluteMarkdownUrl(url)) return undefined
  161. const { path } = splitMarkdownUrlTarget(url)
  162. const authored = splitMarkdownUrlTarget(authoredUrl)
  163. if (path === '') return undefined
  164. const targetPath = resolveRepositoryTarget(path, context)
  165. if (targetPath === undefined) return undefined
  166. const pair = translationPairTarget(targetPath, context)
  167. if (pair === undefined) return undefined
  168. const locale = context.sourcePath.endsWith('.zh.md') ? 'zh' : 'en'
  169. const expectedPath = locale === 'zh' ? pair.zh : pair.source
  170. return {
  171. pair,
  172. targetPath,
  173. suffix: authored.suffix,
  174. expectedPath,
  175. expectedUrl: `${expectedLocalePath(authored.path, locale, context, expectedPath)}${authored.suffix}`,
  176. locale,
  177. }
  178. }
  179. function hasExpectedLocale(resolved: ResolvedTranslationLink): boolean {
  180. return resolved.targetPath === resolved.expectedPath
  181. }
  182. function replacementFor(destination: MarkdownDestination, value: string): Replacement {
  183. return { start: destination.start, end: destination.end, value }
  184. }
  185. function authoredExternalTarget(markdown: string, node: LinkNode): string {
  186. const start = node.position?.start.offset
  187. const end = node.position?.end.offset
  188. if (start === undefined || end === undefined) {
  189. throw new Error(`translation-links: external link ${JSON.stringify(node.url)} has no source offsets`)
  190. }
  191. const raw = markdown.slice(start, end)
  192. if (node.type === 'definition' || raw.startsWith('[')) return markdownDestination(markdown, node).url
  193. if (raw.startsWith('<') && raw.endsWith('>')) return raw.slice(1, -1)
  194. return raw
  195. }
  196. function applyReplacements(markdown: string, replacements: Replacement[]): string {
  197. let output = markdown
  198. for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
  199. output = output.slice(0, replacement.start) + replacement.value + output.slice(replacement.end)
  200. }
  201. return output
  202. }
  203. function visitDocumentLinkNodes(
  204. markdown: string,
  205. skipTargets: readonly string[],
  206. visitor: (node: LinkNode) => void,
  207. ): void {
  208. const tree = parseMarkdown(markdown)
  209. const switcherOffset = languageSwitcherLinkOffset(tree, markdown, skipTargets)
  210. const referencedIdentifiers = new Set<string>()
  211. const visitedDefinitions = new Set<string>()
  212. visitMarkdown(tree, (node) => {
  213. if (node.type === 'linkReference') referencedIdentifiers.add(node.identifier)
  214. })
  215. visitMarkdown(tree, (node) => {
  216. if (node.type === 'link' && node.position?.start.offset === switcherOffset) return
  217. if (node.type === 'link') {
  218. visitor(node)
  219. } else if (node.type === 'definition'
  220. && referencedIdentifiers.has(node.identifier)
  221. && !visitedDefinitions.has(node.identifier)) {
  222. visitedDefinitions.add(node.identifier)
  223. visitor(node)
  224. }
  225. })
  226. }
  227. function visitResolvedDocumentLinks(
  228. markdown: string,
  229. context: TranslationLinkContext,
  230. skipTargets: readonly string[],
  231. visitor: (node: LinkNode, destination: MarkdownDestination, resolved: ResolvedTranslationLink) => void,
  232. ): void {
  233. visitDocumentLinkNodes(markdown, skipTargets, (node) => {
  234. if (isExternalOrAbsoluteMarkdownUrl(node.url)) return
  235. const destination = markdownDestination(markdown, node)
  236. const resolved = resolveTranslationLink(node.url, context, destination.url)
  237. if (resolved !== undefined) visitor(node, destination, resolved)
  238. })
  239. }
  240. /** Return one violation per wrong-locale link or link definition. */
  241. export function translationLinkLocaleViolations(
  242. markdown: string,
  243. context: TranslationLinkContext,
  244. skipTargets: readonly string[] = [],
  245. ): TranslationLinkLocaleViolation[] {
  246. const violations: TranslationLinkLocaleViolation[] = []
  247. visitResolvedDocumentLinks(markdown, context, skipTargets, (node, destination, resolved) => {
  248. if (hasExpectedLocale(resolved)) return
  249. violations.push({
  250. sourcePath: context.sourcePath,
  251. line: node.position?.start.line ?? 0,
  252. url: destination.url,
  253. expectedUrl: resolved.expectedUrl,
  254. })
  255. })
  256. return violations
  257. }
  258. /** Rewrite wrong-locale document links without reserializing surrounding Markdown. */
  259. export function rewriteTranslationLinkLocales(
  260. markdown: string,
  261. context: TranslationLinkContext,
  262. skipTargets: readonly string[] = [],
  263. ): TranslationLinkRewriteResult {
  264. const replacements: Replacement[] = []
  265. visitResolvedDocumentLinks(markdown, context, skipTargets, (_node, destination, resolved) => {
  266. if (hasExpectedLocale(resolved)) return
  267. replacements.push(replacementFor(destination, resolved.expectedUrl))
  268. })
  269. return { content: applyReplacements(markdown, replacements), rewritten: replacements.length }
  270. }
  271. /** Normalize only paired-document locale paths while retaining every other byte and URL suffix. */
  272. export function normalizeTranslationMarkdownLinks(
  273. markdown: string,
  274. context: TranslationLinkContext,
  275. skipTargets: readonly string[] = [],
  276. ): string {
  277. const replacements: Replacement[] = []
  278. visitResolvedDocumentLinks(markdown, context, skipTargets, (_node, destination, resolved) => {
  279. replacements.push(replacementFor(
  280. destination,
  281. `dsh-translation-target:${resolved.pair.source}${resolved.suffix}`,
  282. ))
  283. })
  284. return applyReplacements(markdown, replacements)
  285. }
  286. /** Semantic target of one authored inline link or referenced definition. */
  287. export function semanticTranslationLinkNodeTarget(
  288. node: LinkNode,
  289. markdown: string,
  290. context: TranslationLinkContext,
  291. ): string {
  292. if (isExternalOrAbsoluteMarkdownUrl(node.url)) return authoredExternalTarget(markdown, node)
  293. const destination = markdownDestination(markdown, node)
  294. const resolved = resolveTranslationLink(node.url, context, destination.url)
  295. return resolved === undefined
  296. ? destination.url
  297. : `dsh-translation-target:${resolved.pair.source}${resolved.suffix}`
  298. }