reformat-mdx.mjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env node
  2. 'use strict'
  3. import { readFileSync, writeFileSync } from 'node:fs';
  4. import { join, dirname } from 'node:path';
  5. import { fileURLToPath } from 'node:url'
  6. import { sync } from 'glob';
  7. import * as prettier from "prettier";
  8. const __dirname = dirname(fileURLToPath(import.meta.url))
  9. const docs = sync(join(__dirname, '..', 'docs', '**', '*.md'))
  10. async function formatHTML(htmlString) {
  11. try {
  12. const formattedHtml = await prettier.format(htmlString, {
  13. parser: "html",
  14. printWidth: 100,
  15. });
  16. return formattedHtml;
  17. } catch (error) {
  18. console.error("Error formatting HTML:", error);
  19. return htmlString; // Return original in case of an error
  20. }
  21. }
  22. async function replaceAsync(str, regex, asyncFn) {
  23. const matches = [...str.matchAll(regex)];
  24. const replacements = await Promise.all(
  25. matches.map(async (match) => asyncFn(...match))
  26. );
  27. let result = str;
  28. matches.forEach((match, i) => {
  29. result = result.replace(match[0], replacements[i]);
  30. });
  31. return result;
  32. }
  33. for (const file of docs) {
  34. const oldContent = readFileSync(file, 'utf8')
  35. // get codeblocks from markdown
  36. const content = await replaceAsync(oldContent, /(```([a-z0-9]+).*?\n)(.*?)(```)/gs, async (m, m1, m2, m3, m4) => {
  37. if (m2 === 'html') {
  38. m3 = await formatHTML(m3);
  39. // remove empty lines
  40. m3 = m3.replace(/^\s*[\r\n]/gm, '');
  41. return m1 + m3.trim() + "\n" + m4;
  42. }
  43. return m.trim();
  44. })
  45. if (content !== oldContent) {
  46. writeFileSync(file, content, 'utf8')
  47. console.log(`Reformatted ${file}`)
  48. }
  49. }