patch.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. // @ts-ignore
  6. import path from 'path';
  7. // @ts-ignore
  8. import fs from 'fs/promises'; // 使用 fs/promises 简化异步操作
  9. async function patchLinks(outputDir: string) {
  10. /**
  11. * 修复 Markdown 文件中的链接。
  12. * 1. [foo](bar) -> [foo](./bar)
  13. * 2. [foo](./bar) -> [foo](./bar) (保持不变)
  14. * 3. [foo](http(s)://...) -> [foo](http(s)://...) (保持不变)
  15. */
  16. const normalizeLinksInFile = async (filePath: string) => {
  17. try {
  18. const content = await fs.readFile(filePath, 'utf-8');
  19. const newContent = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, p1, p2) => {
  20. // 如果链接以 '/' 或 './' 开头,则保持不变
  21. if (['/', '.'].includes(p2[0]) || p2.startsWith('http://') || p2.startsWith('https://')) {
  22. return `[${p1}](${p2})`;
  23. }
  24. // 否则添加 './'
  25. return `[${p1}](./${p2})`;
  26. });
  27. if (newContent !== content) {
  28. await fs.writeFile(filePath, newContent);
  29. // console.log(`Updated links in file: ${filePath}`);
  30. }
  31. } catch (error) {
  32. console.error(`Error processing file ${filePath}:`, error);
  33. }
  34. };
  35. const traverse = async (dir: string) => {
  36. try {
  37. const entries = await fs.readdir(dir, { withFileTypes: true });
  38. await Promise.all(
  39. entries.map(async (entry) => {
  40. const fullPath = path.join(dir, entry.name);
  41. if (entry.isDirectory()) {
  42. await traverse(fullPath);
  43. } else if (entry.isFile() && /\.mdx?$/.test(entry.name)) {
  44. await normalizeLinksInFile(fullPath);
  45. }
  46. })
  47. );
  48. } catch (error) {
  49. console.error(`Error traversing directory ${dir}:`, error);
  50. }
  51. };
  52. await traverse(outputDir);
  53. }
  54. export async function patchGeneratedApiDocs(absoluteApiDir: string) {
  55. console.log(`Patching links in API docs at: ${absoluteApiDir}`);
  56. await patchLinks(absoluteApiDir);
  57. }