From e68923e87fe2927b5bca95e97d1929252c935f24 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Fri, 6 Jun 2025 12:00:22 -0400 Subject: [PATCH 1/7] Fix default style to prevent callouts overflowing --- src/defaults/default-style.css | 1 - 1 file changed, 1 deletion(-) diff --git a/src/defaults/default-style.css b/src/defaults/default-style.css index c7e2f9c..4299046 100644 --- a/src/defaults/default-style.css +++ b/src/defaults/default-style.css @@ -256,7 +256,6 @@ th { overflow: hidden; - width: 100%; padding: 12px 12px 12px 24px; border-radius: 4px; margin: 1em 0; From 51b3633077f7f659a816a89db6e48a12f82e4b59 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Fri, 6 Jun 2025 12:00:37 -0400 Subject: [PATCH 2/7] 0.2.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4083909..05fcb90 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "module": "index.ts", "type": "module", "private": true, - "version": "0.2.0", + "version": "0.2.1", "devDependencies": { "@types/bun": "latest" }, From 5dfb004a5982c68f6ce62ddd8c9938990abdbb99 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Sat, 7 Jun 2025 10:32:06 -0400 Subject: [PATCH 3/7] Support overflowing tables in default styles --- bun.lock | 5 ++ demo/another.md | 4 ++ demo/index.md | 6 +++ package.json | 1 + src/defaults/default-style.css | 17 ++++--- src/index.ts | 86 +++++++++++++++++++++++++--------- 6 files changed, 90 insertions(+), 29 deletions(-) diff --git a/bun.lock b/bun.lock index bb6a4c4..a9dd4de 100644 --- a/bun.lock +++ b/bun.lock @@ -6,6 +6,7 @@ "dependencies": { "@biomejs/biome": "^1.9.4", "@endeavorance/emdy": "^1.0.0", + "chokidar": "^4.0.3", "rehype-callouts": "^2.1.0", "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", @@ -72,6 +73,8 @@ "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], + "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], "debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="], @@ -206,6 +209,8 @@ "property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="], + "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "rehype-callouts": ["rehype-callouts@2.1.0", "", { "dependencies": { "@types/hast": "^3.0.4", "hast-util-from-html": "^2.0.3", "hast-util-is-element": "^3.0.0", "hastscript": "^9.0.1", "unist-util-visit": "^5.0.0" } }, "sha512-Als/wlYpXg2Rs0p/yofrkSH6IQzn1xh6cvBC5BHy5JVT3lGlzUvVT8wOyVqCEgf8Eun6cQ3f47rLLoaiyLkP0w=="], "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], diff --git a/demo/another.md b/demo/another.md index 2792cae..2786cbc 100644 --- a/demo/another.md +++ b/demo/another.md @@ -17,3 +17,7 @@ How about a callout? > [!warning]- This is collapsible > And how! + +## A subheading + +This is a section! diff --git a/demo/index.md b/demo/index.md index 339807f..5830805 100644 --- a/demo/index.md +++ b/demo/index.md @@ -1,5 +1,6 @@ --- title: Home | Demo +and: how --- # Demo Data @@ -33,3 +34,8 @@ Tables should be a thing too - Need numbers HTML works, still! + + +| hello | world | hello | world | hello | world | hello | world | hello | world | hello | +| ------------------------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | +| dfjhasfdlkjahslfkjahsdlfjhasldjhasldjhasldk | | | | | | | | | | | diff --git a/package.json b/package.json index 05fcb90..a62542f 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "dependencies": { "@biomejs/biome": "^1.9.4", "@endeavorance/emdy": "^1.0.0", + "chokidar": "^4.0.3", "rehype-callouts": "^2.1.0", "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", diff --git a/src/defaults/default-style.css b/src/defaults/default-style.css index 4299046..7e111a4 100644 --- a/src/defaults/default-style.css +++ b/src/defaults/default-style.css @@ -92,16 +92,19 @@ a { } table { - border-collapse: collapse; - width: 100%; - max-width: 100%; - margin: 1em 0; - font-size: 1em; - background-color: var(--color-bg); + display: block; color: var(--color-text); + background-color: var(--color-bg); + width: 100%; + max-width: -moz-fit-content; + max-width: fit-content; + overflow-x: auto; + font-size: 1em; border: 1px solid var(--color-text); + margin: 0 auto; + white-space: nowrap; + border-collapse: collapse; } - th, td { padding: 0.5em 0.5em; diff --git a/src/index.ts b/src/index.ts index ab83f80..3a6e9ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ import Path from "node:path"; import { parseArgs } from "node:util"; import EMDY from "@endeavorance/emdy"; -import type { BunFile } from "bun"; +import { Glob, type BunFile } from "bun"; import DEFAULT_STYLESHEET from "./defaults/default-style.css" with { type: "text", }; @@ -10,10 +10,17 @@ import DEFAULT_TEMPLATE from "./defaults/default-template.html" with { }; import { CLIError } from "./error"; import { parseMarkdown } from "./markdown"; +import { watch } from "node:fs/promises"; const DEFAULT_TEMPLATE_FILE = "_template.html"; const DEFAULT_STYLESHEET_FILE = "_style.css"; +async function isDirectory(path: string): Promise { + const file = Bun.file(path); + const stat = await file.stat(); + return stat.isDirectory(); +} + /** * Given a file path, attempt to read the text of the file * @param filePath - The path to the file to read @@ -66,6 +73,9 @@ interface CLIOptions { /** The path to the stylesheet file */ stylesheetFilePath: string | null; + /** If the default stylesheet should be included regardless of the provided stylesheet */ + includeDefaultStylesheet: boolean; + /** If true, show help message */ help: boolean; @@ -107,6 +117,10 @@ function parseCLIArgs(): { options: CLIOptions; args: string[] } { type: "string", short: "s", }, + "include-default-stylesheet": { + type: "boolean", + short: "S", + }, cwd: { type: "string", default: process.cwd(), @@ -119,12 +133,14 @@ function parseCLIArgs(): { options: CLIOptions; args: string[] } { allowPositionals: true, }); - // Validation + // == Argument Validation == - if (positionals.length > 1 && flags.outfile) { + // Outfile requires only one argument + if (flags.outfile && positionals.length > 1) { throw new CLIError("--outfile cannot be used with multiple inputs."); } + // Outfile and Outdir cannot be used together if (flags.outdir && flags.outfile) { throw new CLIError("--outdir and --outfile cannot be used together."); } @@ -137,6 +153,7 @@ function parseCLIArgs(): { options: CLIOptions; args: string[] } { stdout: flags.stdout ?? false, templateFilePath: flags.template ?? null, stylesheetFilePath: flags.stylesheet ?? null, + includeDefaultStylesheet: flags["include-default-stylesheet"] ?? false, help: flags.help ?? false, title: flags.title ?? null, }, @@ -171,8 +188,11 @@ async function loadTemplate(options: CLIOptions): Promise { * @returns The stylesheet string */ async function loadStylesheet(options: CLIOptions): Promise { + const preamble = options.includeDefaultStylesheet ? DEFAULT_STYLESHEET : ""; + if (options.stylesheetFilePath) { - return readFile(options.stylesheetFilePath); + const loadedSheet = await readFile(options.stylesheetFilePath); + return [preamble, loadedSheet].join("\n"); } const checkStylesheetFile = Bun.file( @@ -180,7 +200,8 @@ async function loadStylesheet(options: CLIOptions): Promise { ); if (await checkStylesheetFile.exists()) { - return checkStylesheetFile.text(); + const loadedSheet = await checkStylesheetFile.text(); + return [preamble, loadedSheet].join("\n"); } return DEFAULT_STYLESHEET; @@ -263,6 +284,27 @@ async function getOutputFile( return Bun.file(outputPath); } +function processStdin(options: CLIOptions): Promise { + const outfile = options.outfile ? Bun.file(options.outfile) : Bun.stdout; + return buildFile(Bun.stdin, outfile, options); +} + +async function processFile( + options: CLIOptions, + filePath: string, +): Promise { + console.log(`Building ${filePath}...`); + const file = Bun.file(filePath); + + // Ensure input files exist + if (!(await file.exists())) { + throw new CLIError(`File ${filePath} does not exist.`); + } + + const outfile = await getOutputFile(filePath, options); + await buildFile(file, outfile, options); +} + async function main() { const { options, args } = parseCLIArgs(); @@ -277,13 +319,14 @@ Usage: echo "some markdown" | buildmd Options: - --outfile, -o Output path - --outdir, -d Output directory - --stdout Force output to stdout - --template, -t Template path (default: _template.html) - --stylesheet, -s Stylesheet path (default: _style.css) - --title, -T Document title override - --help, -h Show this help message + --outfile, -o Output path + --outdir, -d Output directory + --stdout Force output to stdout + --template, -t Template path (default: _template.html) + --stylesheet, -s Stylesheet path (default: _style.css) + --include-default-stylesheet, -S Extend default CSS instead of overwriting + --title, -T Document title override + --help, -h Show this help message `.trim(), ); process.exit(0); @@ -291,22 +334,21 @@ Options: // stdin mode if (args.length === 0) { - const outfile = options.outfile ? Bun.file(options.outfile) : Bun.stdout; - await buildFile(Bun.stdin, outfile, options); - process.exit(0); + return processStdin(options); } // file mode for (const arg of args) { - const file = Bun.file(arg); + const isDir = await isDirectory(arg); - // Ensure input files exist - if (!(await file.exists())) { - throw new CLIError(`File ${arg} does not exist.`); + if (isDir) { + const dirGlob = new Glob(`${arg}/**/*.md`); + for await (const file of dirGlob.scan()) { + await processFile(options, file); + } + } else { + await processFile(options, arg); } - - const outfile = await getOutputFile(arg, options); - await buildFile(file, outfile, options); } } From 5d5b2ffb6855867f246e7e8246f45a5814eb0655 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Sat, 7 Jun 2025 10:32:27 -0400 Subject: [PATCH 4/7] Remove unused dep --- bun.lock | 5 ----- package.json | 3 +-- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/bun.lock b/bun.lock index a9dd4de..bb6a4c4 100644 --- a/bun.lock +++ b/bun.lock @@ -6,7 +6,6 @@ "dependencies": { "@biomejs/biome": "^1.9.4", "@endeavorance/emdy": "^1.0.0", - "chokidar": "^4.0.3", "rehype-callouts": "^2.1.0", "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", @@ -73,8 +72,6 @@ "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], - "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], - "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], "debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="], @@ -209,8 +206,6 @@ "property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="], - "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], - "rehype-callouts": ["rehype-callouts@2.1.0", "", { "dependencies": { "@types/hast": "^3.0.4", "hast-util-from-html": "^2.0.3", "hast-util-is-element": "^3.0.0", "hastscript": "^9.0.1", "unist-util-visit": "^5.0.0" } }, "sha512-Als/wlYpXg2Rs0p/yofrkSH6IQzn1xh6cvBC5BHy5JVT3lGlzUvVT8wOyVqCEgf8Eun6cQ3f47rLLoaiyLkP0w=="], "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], diff --git a/package.json b/package.json index a62542f..68ed5b8 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "module": "index.ts", "type": "module", "private": true, - "version": "0.2.1", + "version": "0.3.0", "devDependencies": { "@types/bun": "latest" }, @@ -13,7 +13,6 @@ "dependencies": { "@biomejs/biome": "^1.9.4", "@endeavorance/emdy": "^1.0.0", - "chokidar": "^4.0.3", "rehype-callouts": "^2.1.0", "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", From 6afc96f3326df28bf19e09fd432c59eae16b0873 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Sat, 7 Jun 2025 10:51:22 -0400 Subject: [PATCH 5/7] Support custom heading IDs --- bun.lock | 7 +++++++ demo/index.md | 2 +- package.json | 3 ++- src/markdown.ts | 2 ++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/bun.lock b/bun.lock index bb6a4c4..32d84ef 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,7 @@ "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", "rehype-stringify": "^10.0.1", + "remark-custom-heading-id": "^2.0.0", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", @@ -120,6 +121,8 @@ "markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="], + "mdast-heading-id": ["mdast-heading-id@2.0.0", "", {}, "sha512-JVh0xKqsI3INPzJEqqCiuq3BGde5x6AlBTQAetLQQr9qTiDjX4dCvFhIiGmyPt1rftiHELQPI5obGphIOTXeWQ=="], + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="], "mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA=="], @@ -172,6 +175,8 @@ "micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="], + "micromark-heading-id": ["micromark-heading-id@2.0.0", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-TdR5WCmwuCroK8QrfX0/4w9bjj3ayN0GzatxGV/lWQKmM75kNKVZEmdvKZS4MOskARxWXu1WHdIJjMSVMBegow=="], + "micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], "micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="], @@ -214,6 +219,8 @@ "rehype-stringify": ["rehype-stringify@10.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-html": "^9.0.0", "unified": "^11.0.0" } }, "sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA=="], + "remark-custom-heading-id": ["remark-custom-heading-id@2.0.0", "", { "dependencies": { "mdast-heading-id": "*", "micromark-heading-id": "*", "unist-util-visit": "^5.0.0" } }, "sha512-LpR+c4pmuBGG/zhNbebecDnpKyXU4B7bdNu6tXW83T3QWlkwUpHYyUR8uXQ/BERK9HlI5pXGLu7DjkIS07/iVQ=="], + "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], "remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="], diff --git a/demo/index.md b/demo/index.md index 5830805..1cbb734 100644 --- a/demo/index.md +++ b/demo/index.md @@ -17,7 +17,7 @@ Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapi Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapien vitae pellentesque sem placerat. In id cursus mi pretium tellus duis convallis. Tempus leo eu aenean sed diam urna tempor. Pulvinar vivamus fringilla lacus nec metus bibendum egestas. Iaculis massa nisl malesuada lacinia integer nunc posuere. Ut hendrerit semper vel class aptent taciti sociosqu. Ad litora torquent per conubia nostra inceptos himenaeos. -## Another section +## Another section {#customid} Tables should be a thing too diff --git a/package.json b/package.json index 68ed5b8..2d67dd2 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "module": "index.ts", "type": "module", "private": true, - "version": "0.3.0", + "version": "0.3.1", "devDependencies": { "@types/bun": "latest" }, @@ -17,6 +17,7 @@ "rehype-raw": "^7.0.0", "rehype-slug": "^6.0.0", "rehype-stringify": "^10.0.1", + "remark-custom-heading-id": "^2.0.0", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", diff --git a/src/markdown.ts b/src/markdown.ts index e03dd76..8d497e2 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -6,11 +6,13 @@ import remarkRehype from "remark-rehype"; import rehypeSlug from "rehype-slug"; import { unified } from "unified"; import rehypeCallouts from "rehype-callouts"; +import { remarkHeadingId } from "remark-custom-heading-id"; export async function parseMarkdown(markdown: string): Promise { const file = await unified() .use(remarkParse) .use(remarkGfm) + .use(remarkHeadingId) .use(remarkRehype, { allowDangerousHtml: true }) .use(rehypeRaw) .use(rehypeSlug) From 459f144bef1fade048fa7760bd8ba2ce774cad49 Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Sat, 7 Jun 2025 11:33:38 -0400 Subject: [PATCH 6/7] Fix table whitespace --- demo/index.md | 2 +- src/defaults/default-style.css | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/demo/index.md b/demo/index.md index 1cbb734..eca0e1c 100644 --- a/demo/index.md +++ b/demo/index.md @@ -38,4 +38,4 @@ Tables should be a thing too | hello | world | hello | world | hello | world | hello | world | hello | world | hello | | ------------------------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | ----- | -| dfjhasfdlkjahslfkjahsdlfjhasldjhasldjhasldk | | | | | | | | | | | +| dfjhasfdlkjahslfkjahsdlfjhasldjhasldjhasldk and such and things and whatnot and even more words in this cell so that hopefully itll wrap at some point ya dig? | | | | | | | | | | | diff --git a/src/defaults/default-style.css b/src/defaults/default-style.css index 7e111a4..d03160b 100644 --- a/src/defaults/default-style.css +++ b/src/defaults/default-style.css @@ -102,7 +102,6 @@ table { font-size: 1em; border: 1px solid var(--color-text); margin: 0 auto; - white-space: nowrap; border-collapse: collapse; } th, From 0dbba6f238c75872ae6ad4b08b7542f518ba5edd Mon Sep 17 00:00:00 2001 From: Endeavorance Date: Sat, 7 Jun 2025 13:13:18 -0400 Subject: [PATCH 7/7] Restructure files --- package.json | 4 + src/build.ts | 42 ++++++ src/file-util.ts | 77 +++++++++++ src/index.ts | 334 +++------------------------------------------- src/markdown.ts | 30 ++++- src/options.ts | 128 ++++++++++++++++++ src/stylesheet.ts | 33 +++++ src/template.ts | 46 +++++++ 8 files changed, 375 insertions(+), 319 deletions(-) create mode 100644 src/build.ts create mode 100644 src/file-util.ts create mode 100644 src/options.ts create mode 100644 src/stylesheet.ts create mode 100644 src/template.ts diff --git a/package.json b/package.json index 2d67dd2..b14fa37 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,10 @@ "type": "module", "private": true, "version": "0.3.1", + "scripts": { + "build": ".run/build", + "fmt": "bunx --bun biome check --fix" + }, "devDependencies": { "@types/bun": "latest" }, diff --git a/src/build.ts b/src/build.ts new file mode 100644 index 0000000..cb8d5c9 --- /dev/null +++ b/src/build.ts @@ -0,0 +1,42 @@ +import EMDY from "@endeavorance/emdy"; +import type { BunFile } from "bun"; +import { parseMarkdown } from "./markdown"; +import type { CLIOptions } from "./options"; +import { loadStylesheet } from "./stylesheet"; +import { loadTemplate, renderTemplate } from "./template"; + +/** + * Build a file and return the rendered HTML string + * @param infile - The input file to read from + * @param outfile - The output file to write to + * @param options - The CLI options containing template and stylesheet paths + */ +export async function buildFile( + infile: BunFile, + options: CLIOptions, +): Promise { + // Load resources + const input = await infile.text(); + const template = await loadTemplate(options); + const stylesheet = await loadStylesheet(options); + const { content, ...props } = EMDY.parse(input) as Record & { + content: string; + }; + + // Render markdown + const html = await parseMarkdown(content); + + // Prepare data + const title = options.title ?? props.title ?? "Untitled"; + const templateData = { + content: html, + title, + stylesheet: stylesheet, + timestamp: new Date().toISOString(), + datetime: new Date().toLocaleString(), + ...props, + }; + + // Render template + return renderTemplate(template, templateData); +} diff --git a/src/file-util.ts b/src/file-util.ts new file mode 100644 index 0000000..f4a0d78 --- /dev/null +++ b/src/file-util.ts @@ -0,0 +1,77 @@ +import Path from "node:path"; +import type { BunFile } from "bun"; +import { CLIError } from "./error"; +import type { CLIOptions } from "./options"; + +/** + * Check if a given path is a directory + * + * @param path - The path to check + * @returns A promise that resolves to true if the path is a directory, false otherwise + */ +export async function isDirectory(path: string): Promise { + const file = Bun.file(path); + const stat = await file.stat(); + return stat.isDirectory(); +} + +/** + * Given a file path, attempt to read the text of the file + * @param filePath - The path to the file to read + * @returns The text content of the file + * + * @throws CLIError if the file does not exist + */ +export async function readFile(filePath: string): Promise { + const file = Bun.file(filePath); + const exists = await file.exists(); + if (!exists) { + throw new CLIError(`File ${filePath} does not exist.`); + } + return file.text(); +} + +/** + * Get the output path based on the input path and options + * @param inputPath - The path of the input file + * @param options - The CLI options containing output directory + * @returns The resolved output path + */ +async function getOutputPath(inputPath: string, options: CLIOptions) { + const inputDirname = Path.dirname(inputPath); + const inputBasename = Path.basename(inputPath); + const outputBasename = inputBasename.replace(/\.md$/, ".html"); + + if (options.outdir) { + const dirPath = Path.relative(options.cwd, inputDirname); + const outputPath = Path.join(options.outdir, dirPath, outputBasename); + return Path.resolve(outputPath); + } + + return Path.join(inputDirname, outputBasename); +} + +/** + * Get the output file based on the input path and options + * @param inputPath - The path of the input file + * @param options - The CLI options containing output file and directory + * @returns The BunFile object representing the output file + */ +export async function getOutputFile( + inputPath: string, + options: CLIOptions, +): Promise { + // --stdout option -> Force stdout + if (options.stdout) { + return Bun.stdout; + } + + // Exact outfile defined -> write to file + if (options.outfile) { + return Bun.file(options.outfile); + } + + // Input path with --outdir -> calculate output path + const outputPath = await getOutputPath(inputPath, options); + return Bun.file(outputPath); +} diff --git a/src/index.ts b/src/index.ts index 3a6e9ba..e6bee9a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,297 +1,18 @@ -import Path from "node:path"; -import { parseArgs } from "node:util"; -import EMDY from "@endeavorance/emdy"; -import { Glob, type BunFile } from "bun"; -import DEFAULT_STYLESHEET from "./defaults/default-style.css" with { - type: "text", -}; -import DEFAULT_TEMPLATE from "./defaults/default-template.html" with { - type: "text", -}; +import { Glob } from "bun"; +import { buildFile } from "./build"; import { CLIError } from "./error"; -import { parseMarkdown } from "./markdown"; -import { watch } from "node:fs/promises"; +import { getOutputFile, isDirectory } from "./file-util"; +import { type CLIOptions, USAGE, parseCLIArgs } from "./options"; -const DEFAULT_TEMPLATE_FILE = "_template.html"; -const DEFAULT_STYLESHEET_FILE = "_style.css"; - -async function isDirectory(path: string): Promise { - const file = Bun.file(path); - const stat = await file.stat(); - return stat.isDirectory(); -} - -/** - * Given a file path, attempt to read the text of the file - * @param filePath - The path to the file to read - * @returns The text content of the file - * - * @throws CLIError if the file does not exist - */ -async function readFile(filePath: string): Promise { - const file = Bun.file(filePath); - const exists = await file.exists(); - if (!exists) { - throw new CLIError(`File ${filePath} does not exist.`); - } - return file.text(); -} - -/** - * Renders the provided template with the given data. - * @param template - The template string containing placeholders like %key% - * @param data - An object containing key-value pairs to replace in the template - * @returns The rendered string with all placeholders replaced by their corresponding values - */ -function renderTemplate( - template: string, - data: Record, -): string { - let output = template; - for (const [key, value] of Object.entries(data)) { - output = output.replace(new RegExp(`%${key}%`, "g"), String(value)); - } - return output; -} - -/** - * A collection of options parsed from the command line arguments. - */ -interface CLIOptions { - /** A path to the output file */ - outfile: string | null; - - /** A path to the output directory */ - outdir: string | null; - - /** If true, force output to stdout */ - stdout: boolean; - - /** The path to the template file */ - templateFilePath: string | null; - - /** The path to the stylesheet file */ - stylesheetFilePath: string | null; - - /** If the default stylesheet should be included regardless of the provided stylesheet */ - includeDefaultStylesheet: boolean; - - /** If true, show help message */ - help: boolean; - - /** If provided, overrides the document title */ - title: string | null; - - /** If provided, overrides the current working directory (default: .) */ - cwd: string; -} - -/** - * Parse the command line arguments and return the options and positional arguments. - * @returns An object containing the parsed options and positional arguments - */ -function parseCLIArgs(): { options: CLIOptions; args: string[] } { - const { values: flags, positionals } = parseArgs({ - args: Bun.argv.slice(2), - options: { - outfile: { - type: "string", - short: "o", - }, - outdir: { - type: "string", - short: "d", - }, - stdout: { - type: "boolean", - }, - template: { - type: "string", - short: "t", - }, - title: { - type: "string", - short: "T", - }, - stylesheet: { - type: "string", - short: "s", - }, - "include-default-stylesheet": { - type: "boolean", - short: "S", - }, - cwd: { - type: "string", - default: process.cwd(), - }, - help: { - type: "boolean", - short: "h", - }, - }, - allowPositionals: true, - }); - - // == Argument Validation == - - // Outfile requires only one argument - if (flags.outfile && positionals.length > 1) { - throw new CLIError("--outfile cannot be used with multiple inputs."); - } - - // Outfile and Outdir cannot be used together - if (flags.outdir && flags.outfile) { - throw new CLIError("--outdir and --outfile cannot be used together."); - } - - return { - options: { - cwd: flags.cwd, - outfile: flags.outfile ?? null, - outdir: flags.outdir ?? null, - stdout: flags.stdout ?? false, - templateFilePath: flags.template ?? null, - stylesheetFilePath: flags.stylesheet ?? null, - includeDefaultStylesheet: flags["include-default-stylesheet"] ?? false, - help: flags.help ?? false, - title: flags.title ?? null, - }, - args: positionals, - }; -} - -/** - * Attempt to load a custom template, falling back to a default - * @param options - The CLI options containing the template file path - * @returns The template string - */ -async function loadTemplate(options: CLIOptions): Promise { - if (options.templateFilePath) { - return readFile(options.templateFilePath); - } - - const checkTemplateFile = Bun.file( - Path.join(options.cwd, DEFAULT_TEMPLATE_FILE), - ); - - if (await checkTemplateFile.exists()) { - return checkTemplateFile.text(); - } - - return DEFAULT_TEMPLATE; -} - -/** - * Attempt to load a custom stylesheet, falling back to a default - * @param options - The CLI options containing the stylesheet file path - * @returns The stylesheet string - */ -async function loadStylesheet(options: CLIOptions): Promise { - const preamble = options.includeDefaultStylesheet ? DEFAULT_STYLESHEET : ""; - - if (options.stylesheetFilePath) { - const loadedSheet = await readFile(options.stylesheetFilePath); - return [preamble, loadedSheet].join("\n"); - } - - const checkStylesheetFile = Bun.file( - Path.join(options.cwd, DEFAULT_STYLESHEET_FILE), - ); - - if (await checkStylesheetFile.exists()) { - const loadedSheet = await checkStylesheetFile.text(); - return [preamble, loadedSheet].join("\n"); - } - - return DEFAULT_STYLESHEET; -} - -/** - * Build and write a file - * @param infile - The input file to read from - * @param outfile - The output file to write to - * @param options - The CLI options containing template and stylesheet paths - */ -async function buildFile( - infile: BunFile, - outfile: BunFile, - options: CLIOptions, -): Promise { - const input = await infile.text(); - const template = await loadTemplate(options); - const stylesheet = await loadStylesheet(options); - const { content, ...props } = EMDY.parse(input) as Record & { - content: string; - }; - - const html = await parseMarkdown(content); - const title = options.title ?? props.title ?? "Untitled"; - const templateData = { - content: html, - title, - stylesheet: stylesheet, - timestamp: new Date().toISOString(), - datetime: new Date().toLocaleString(), - ...props, - }; - - await Bun.write(outfile, renderTemplate(template, templateData)); -} - -/** - * Get the output path based on the input path and options - * @param inputPath - The path of the input file - * @param options - The CLI options containing output directory - * @returns The resolved output path - */ -async function getOutputPath(inputPath: string, options: CLIOptions) { - const inputDirname = Path.dirname(inputPath); - const inputBasename = Path.basename(inputPath); - const outputBasename = inputBasename.replace(/\.md$/, ".html"); - - if (options.outdir) { - const dirPath = Path.relative(options.cwd, inputDirname); - const outputPath = Path.join(options.outdir, dirPath, outputBasename); - return Path.resolve(outputPath); - } - - return Path.join(inputDirname, outputBasename); -} - -/** - * Get the output file based on the input path and options - * @param inputPath - The path of the input file - * @param options - The CLI options containing output file and directory - * @returns The BunFile object representing the output file - */ -async function getOutputFile( - inputPath: string, - options: CLIOptions, -): Promise { - // --stdout option -> Force stdout - if (options.stdout) { - return Bun.stdout; - } - - // Exact outfile defined -> write to file - if (options.outfile) { - return Bun.file(options.outfile); - } - - // Input path with --outdir -> calculate output path - const outputPath = await getOutputPath(inputPath, options); - return Bun.file(outputPath); -} - -function processStdin(options: CLIOptions): Promise { +async function processStdin(options: CLIOptions): Promise { const outfile = options.outfile ? Bun.file(options.outfile) : Bun.stdout; - return buildFile(Bun.stdin, outfile, options); + const renderedHTML = await buildFile(Bun.stdin, options); + await Bun.write(outfile, renderedHTML); } -async function processFile( - options: CLIOptions, +async function processFileAtPath( filePath: string, + options: CLIOptions, ): Promise { console.log(`Building ${filePath}...`); const file = Bun.file(filePath); @@ -302,34 +23,16 @@ async function processFile( } const outfile = await getOutputFile(filePath, options); - await buildFile(file, outfile, options); + const renderedHTML = await buildFile(file, options); + await Bun.write(outfile, renderedHTML); } async function main() { const { options, args } = parseCLIArgs(); if (options.help) { - console.log( - ` -buildmd - Build markdown files to html with templates and metadata - -Usage: - buildmd file.md - buildmd file.md -o output.html - echo "some markdown" | buildmd - -Options: - --outfile, -o Output path - --outdir, -d Output directory - --stdout Force output to stdout - --template, -t Template path (default: _template.html) - --stylesheet, -s Stylesheet path (default: _style.css) - --include-default-stylesheet, -S Extend default CSS instead of overwriting - --title, -T Document title override - --help, -h Show this help message -`.trim(), - ); - process.exit(0); + console.log(USAGE); + return; } // stdin mode @@ -338,22 +41,23 @@ Options: } // file mode - for (const arg of args) { - const isDir = await isDirectory(arg); + for (const inputPath of args) { + const isDir = await isDirectory(inputPath); if (isDir) { - const dirGlob = new Glob(`${arg}/**/*.md`); + const dirGlob = new Glob(`${inputPath}/**/*.md`); for await (const file of dirGlob.scan()) { - await processFile(options, file); + await processFileAtPath(file, options); } } else { - await processFile(options, arg); + await processFileAtPath(inputPath, options); } } } try { await main(); + process.exit(0); } catch (error) { if (error instanceof CLIError) { console.error(error.message); diff --git a/src/markdown.ts b/src/markdown.ts index 8d497e2..3e9aef2 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -1,22 +1,44 @@ +import rehypeCallouts from "rehype-callouts"; import rehypeRaw from "rehype-raw"; -import remarkGfm from "remark-gfm"; +import rehypeSlug from "rehype-slug"; import rehypeStringify from "rehype-stringify"; +import { remarkHeadingId } from "remark-custom-heading-id"; +import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; -import rehypeSlug from "rehype-slug"; import { unified } from "unified"; -import rehypeCallouts from "rehype-callouts"; -import { remarkHeadingId } from "remark-custom-heading-id"; +/** + * Parse the provided markdown into an HTML string + * + * @param markdown - The markdown string to parse + * @returns The parsed HTML string in a promise + */ export async function parseMarkdown(markdown: string): Promise { const file = await unified() + + // Parse markdown .use(remarkParse) + + // Support github-flavored markdown .use(remarkGfm) + + // Accept custom heading ids: # My heading {#custom-id} .use(remarkHeadingId) + + // Pass-thru HTML .use(remarkRehype, { allowDangerousHtml: true }) + + // Process to html/html .use(rehypeRaw) + + // Apply heading IDs to headings without a custom ID .use(rehypeSlug) + + // Support callouts/admonitions .use(rehypeCallouts) + + // Render to string .use(rehypeStringify) .process(markdown); diff --git a/src/options.ts b/src/options.ts new file mode 100644 index 0000000..d0b6f3e --- /dev/null +++ b/src/options.ts @@ -0,0 +1,128 @@ +import { parseArgs } from "node:util"; +import { CLIError } from "./error"; + +/** + * A collection of options parsed from the command line arguments. + */ +export interface CLIOptions { + /** A path to the output file */ + outfile: string | null; + + /** A path to the output directory */ + outdir: string | null; + + /** If true, force output to stdout */ + stdout: boolean; + + /** The path to the template file */ + templateFilePath: string | null; + + /** The path to the stylesheet file */ + stylesheetFilePath: string | null; + + /** If the default stylesheet should be included regardless of the provided stylesheet */ + includeDefaultStylesheet: boolean; + + /** If true, show help message */ + help: boolean; + + /** If provided, overrides the document title */ + title: string | null; + + /** If provided, overrides the current working directory (default: .) */ + cwd: string; +} + +/** + * Parse the command line arguments and return the options and positional arguments. + * @returns An object containing the parsed options and positional arguments + */ +export function parseCLIArgs(): { options: CLIOptions; args: string[] } { + const { values: flags, positionals } = parseArgs({ + args: Bun.argv.slice(2), + options: { + outfile: { + type: "string", + short: "o", + }, + outdir: { + type: "string", + short: "d", + }, + stdout: { + type: "boolean", + }, + template: { + type: "string", + short: "t", + }, + title: { + type: "string", + short: "T", + }, + stylesheet: { + type: "string", + short: "s", + }, + "include-default-stylesheet": { + type: "boolean", + short: "S", + }, + cwd: { + type: "string", + default: process.cwd(), + }, + help: { + type: "boolean", + short: "h", + }, + }, + allowPositionals: true, + }); + + // == Argument Validation == + + // Outfile requires only one argument + if (flags.outfile && positionals.length > 1) { + throw new CLIError("--outfile cannot be used with multiple inputs."); + } + + // Outfile and Outdir cannot be used together + if (flags.outdir && flags.outfile) { + throw new CLIError("--outdir and --outfile cannot be used together."); + } + + return { + options: { + cwd: flags.cwd, + outfile: flags.outfile ?? null, + outdir: flags.outdir ?? null, + stdout: flags.stdout ?? false, + templateFilePath: flags.template ?? null, + stylesheetFilePath: flags.stylesheet ?? null, + includeDefaultStylesheet: flags["include-default-stylesheet"] ?? false, + help: flags.help ?? false, + title: flags.title ?? null, + }, + args: positionals, + }; +} + +export const USAGE = ` +buildmd - Build markdown files to html with templates and metadata + +Usage: + buildmd file.md + buildmd file.md -o output.html + echo "some markdown" | buildmd + +Options: + --outfile, -o Output path + --outdir, -d Output directory + --stdout Force output to stdout + --template, -t Template path (default: _template.html) + --stylesheet, -s Stylesheet path (default: _style.css) + --include-default-stylesheet, -S Extend default CSS instead of overwriting + --title, -T Document title override + --help, -h Show this help message +`.trim(); diff --git a/src/stylesheet.ts b/src/stylesheet.ts new file mode 100644 index 0000000..595bae3 --- /dev/null +++ b/src/stylesheet.ts @@ -0,0 +1,33 @@ +import Path from "node:path"; +import DEFAULT_STYLESHEET from "./defaults/default-style.css" with { + type: "text", +}; +import { readFile } from "./file-util"; +import type { CLIOptions } from "./options"; + +const DEFAULT_STYLESHEET_FILE = "_style.css"; + +/** + * Attempt to load a custom stylesheet, falling back to a default + * @param options - The CLI options containing the stylesheet file path + * @returns The stylesheet string + */ +export async function loadStylesheet(options: CLIOptions): Promise { + const preamble = options.includeDefaultStylesheet ? DEFAULT_STYLESHEET : ""; + + if (options.stylesheetFilePath) { + const loadedSheet = await readFile(options.stylesheetFilePath); + return [preamble, loadedSheet].join("\n"); + } + + const checkStylesheetFile = Bun.file( + Path.join(options.cwd, DEFAULT_STYLESHEET_FILE), + ); + + if (await checkStylesheetFile.exists()) { + const loadedSheet = await checkStylesheetFile.text(); + return [preamble, loadedSheet].join("\n"); + } + + return DEFAULT_STYLESHEET; +} diff --git a/src/template.ts b/src/template.ts new file mode 100644 index 0000000..c340a1a --- /dev/null +++ b/src/template.ts @@ -0,0 +1,46 @@ +import Path from "node:path"; +import DEFAULT_TEMPLATE from "./defaults/default-template.html" with { + type: "text", +}; +import { readFile } from "./file-util"; +import type { CLIOptions } from "./options"; + +const DEFAULT_TEMPLATE_FILE = "_template.html"; + +/** + * Renders the provided template with the given data. + * @param template - The template string containing placeholders like %key% + * @param data - An object containing key-value pairs to replace in the template + * @returns The rendered string with all placeholders replaced by their corresponding values + */ +export function renderTemplate( + template: string, + data: Record, +): string { + let output = template; + for (const [key, value] of Object.entries(data)) { + output = output.replace(new RegExp(`%${key}%`, "g"), String(value)); + } + return output; +} + +/** + * Attempt to load a custom template, falling back to a default + * @param options - The CLI options containing the template file path + * @returns The template string + */ +export async function loadTemplate(options: CLIOptions): Promise { + if (options.templateFilePath) { + return readFile(options.templateFilePath); + } + + const checkTemplateFile = Bun.file( + Path.join(options.cwd, DEFAULT_TEMPLATE_FILE), + ); + + if (await checkTemplateFile.exists()) { + return checkTemplateFile.text(); + } + + return DEFAULT_TEMPLATE; +}