xonecas.io
6533
Yo

yoctomarkdown / commit 13981d2

feat: implement yoctomarkdown spec

xonecas2026-03-15 13981d25e2e6b27df6357856b46870c0ad7d830a

10 files changed

.gitignore+34−0
@@ -0,0 +1,34 @@
1+# dependencies (bun install)
2+node_modules
3+
4+# output
5+out
6+dist
7+*.tgz
8+
9+# code coverage
10+coverage
11+*.lcov
12+
13+# logs
14+logs
15+_.log
16+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
17+
18+# dotenv environment variable files
19+.env
20+.env.development.local
21+.env.test.local
22+.env.production.local
23+.env.local
24+
25+# caches
26+.eslintcache
27+.cache
28+*.tsbuildinfo
29+
30+# IntelliJ based IDEs
31+.idea
32+
33+# Finder (MacOS) folder config
34+.DS_Store
AGENTS.md+1−0
@@ -0,0 +1 @@
1+- [spec.md](spec.md) is maintained by the user, only edit when asked directly by the user. It contains the specification for the project. Use it as the source of truth
README.md+15−0
@@ -0,0 +1,15 @@
1+# yoctomarkdown
2+
3+To install dependencies:
4+
5+```bash
6+bun install
7+```
8+
9+To run:
10+
11+```bash
12+bun run index.ts
13+```
14+
15+This project was created using `bun init` in bun v1.3.9. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
bun.lock+31−0
@@ -0,0 +1,31 @@
1+{
2+ "lockfileVersion": 1,
3+ "configVersion": 1,
4+ "workspaces": {
5+ "": {
6+ "name": "yoctomarkdown",
7+ "dependencies": {
8+ "yoctocolors": "^2.1.2",
9+ },
10+ "devDependencies": {
11+ "@types/bun": "latest",
12+ },
13+ "peerDependencies": {
14+ "typescript": "^5",
15+ },
16+ },
17+ },
18+ "packages": {
19+ "@types/bun": ["@types/bun@1.3.10", "", { "dependencies": { "bun-types": "1.3.10" } }, "sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ=="],
20+
21+ "@types/node": ["@types/node@25.5.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="],
22+
23+ "bun-types": ["bun-types@1.3.10", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
24+
25+ "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
26+
27+ "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
28+
29+ "yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="],
30+ }
31+}
cli.ts+74−0
@@ -0,0 +1,74 @@
1+#!/usr/bin/env bun
2+import { parseArgs } from "util";
3+import { highlightSync, createHighlighter, Options } from "./index";
4+import { readFileSync } from "fs";
5+
6+const { values, positionals } = parseArgs({
7+ args: Bun.argv.slice(2),
8+ options: {
9+ theme: { type: "string", short: "t" },
10+ wrap: { type: "string", short: "w" },
11+ help: { type: "boolean", short: "h" },
12+ },
13+ allowPositionals: true,
14+});
15+
16+if (values.help) {
17+ console.log(`
18+Usage: yoctomarkdown [options] [file]
19+
20+Options:
21+ -t, --theme <name> Theme to use: 16, 256, truecolor, minimal, none (default: 16)
22+ -w, --wrap <n|auto|0> Word wrap setting (default: auto)
23+ -h, --help Show this help message
24+`);
25+ process.exit(0);
26+}
27+
28+const themeName = values.theme || "16";
29+const validThemes = ["16", "256", "truecolor", "minimal", "none"];
30+if (!validThemes.includes(themeName)) {
31+ console.error(`Invalid theme: ${themeName}`);
32+ process.exit(1);
33+}
34+
35+const wrapVal = values.wrap || "auto";
36+let wordWrap: number | "auto" | 0 = "auto";
37+if (wrapVal === "auto" || wrapVal === "0") {
38+ wordWrap = wrapVal === "auto" ? "auto" : 0;
39+} else {
40+ const n = parseInt(wrapVal, 10);
41+ if (isNaN(n) || n < 0) {
42+ console.error(`Invalid wrap value: ${wrapVal}`);
43+ process.exit(1);
44+ }
45+ wordWrap = n;
46+}
47+
48+const options: Options = {
49+ theme: themeName as any,
50+ wordWrap,
51+};
52+
53+const highlighter = createHighlighter(options);
54+
55+async function run() {
56+ if (positionals.length > 0) {
57+ const file = positionals[0];
58+ try {
59+ const content = readFileSync(file, "utf8");
60+ process.stdout.write(highlighter.write(content));
61+ process.stdout.write(highlighter.end());
62+ } catch (err: any) {
63+ console.error(`Error reading file: ${err.message}`);
64+ process.exit(1);
65+ }
66+ } else {
67+ for await (const chunk of process.stdin) {
68+ process.stdout.write(highlighter.write(chunk));
69+ }
70+ process.stdout.write(highlighter.end());
71+ }
72+}
73+
74+run();
index.ts+148−0
@@ -0,0 +1,148 @@
1+import { Theme, themes } from "./themes";
2+
3+export interface Options {
4+ theme?: "16" | "256" | "truecolor" | "minimal" | "none" | Theme;
5+ tabWidth?: number;
6+ wordWrap?: number | "auto" | 0;
7+ yieldEvery?: number;
8+}
9+
10+export interface Highlighter {
11+ write(chunk: string | Uint8Array): string;
12+ end(): string;
13+}
14+
15+function resolveTheme(options?: Options): Theme {
16+ const t = options?.theme || "16";
17+ if (typeof t === "string") {
18+ return themes[t] || themes["none"];
19+ }
20+ return t;
21+}
22+
23+export function highlightSync(input: string, options?: Options): string {
24+ const highlighter = createHighlighter(options);
25+ const out = highlighter.write(input);
26+ return out + highlighter.end();
27+}
28+
29+export function createHighlighter(options?: Options): Highlighter {
30+ const theme = resolveTheme(options);
31+ let buffer = "";
32+ let inCodeBlock = false;
33+
34+ function parseInline(text: string): string {
35+
36+ let result = "";
37+ let i = 0;
38+ while (i < text.length) {
39+ if (text.startsWith("`", i) && !text.startsWith("``", i)) {
40+ let end = text.indexOf("`", i + 1);
41+ if (end !== -1) {
42+ result += theme.code(`\`${text.slice(i + 1, end)}\``);
43+ i = end + 1;
44+ continue;
45+ }
46+ }
47+
48+ if (text.startsWith("**", i)) {
49+ let end = text.indexOf("**", i + 2);
50+ if (end !== -1) {
51+ result += theme.bold(`**${text.slice(i + 2, end)}**`);
52+ i = end + 2;
53+ continue;
54+ }
55+ }
56+
57+ if (text.startsWith("*", i) && !text.startsWith("**", i)) {
58+ let end = text.indexOf("*", i + 1);
59+ if (end !== -1 && !text.startsWith("**", end)) {
60+ result += theme.italic(`*${text.slice(i + 1, end)}*`);
61+ i = end + 1;
62+ continue;
63+ }
64+ }
65+
66+ if (text.startsWith("[", i)) {
67+ let bracketEnd = text.indexOf("]", i + 1);
68+ if (bracketEnd !== -1 && text.charAt(bracketEnd + 1) === "(") {
69+ let parenEnd = text.indexOf(")", bracketEnd + 2);
70+ if (parenEnd !== -1) {
71+ result += theme.link(`[${text.slice(i + 1, bracketEnd)}](${text.slice(bracketEnd + 2, parenEnd)})`);
72+ i = parenEnd + 1;
73+ continue;
74+ }
75+ }
76+ }
77+
78+ result += text[i];
79+ i++;
80+ }
81+
82+ return result;
83+ }
84+
85+ function parseLine(line: string, isLastLine: boolean): string {
86+ if (inCodeBlock) {
87+ if (line.trim().startsWith("```")) {
88+ inCodeBlock = false;
89+ return theme.codeBlock(line);
90+ }
91+ return theme.codeBlock(line);
92+ }
93+
94+ if (line.trim().startsWith("```")) {
95+ inCodeBlock = true;
96+ return theme.codeBlock(line);
97+ }
98+
99+ const hrMatch = line.trim().match(/^(?:-{3,}|\*{3,}|_{3,})$/);
100+ if (hrMatch) {
101+ return theme.hr(line);
102+ }
103+
104+ const headingMatch = line.match(/^(#{1,3})\s+(.*)$/);
105+ if (headingMatch) {
106+ const hashes = headingMatch[1];
107+ const text = headingMatch[2];
108+ return theme.heading(`${hashes} ${parseInline(text)}`);
109+ }
110+
111+ const bqMatch = line.match(/^(>\s+)(.*)$/);
112+ if (bqMatch) {
113+ return theme.blockquote(bqMatch[1]) + parseInline(bqMatch[2]);
114+ }
115+
116+ const ulMatch = line.match(/^([-*]\s+)(.*)$/);
117+ if (ulMatch) {
118+ return theme.listMarker(ulMatch[1]) + parseInline(ulMatch[2]);
119+ }
120+
121+ const olMatch = line.match(/^(\d+\.\s+)(.*)$/);
122+ if (olMatch) {
123+ return theme.listMarker(olMatch[1]) + parseInline(olMatch[2]);
124+ }
125+
126+ return parseInline(line);
127+ }
128+
129+ return {
130+ write(chunk: string | Uint8Array): string {
131+ const text = typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
132+ buffer += text;
133+
134+ const lines = buffer.split("\n");
135+ buffer = lines.pop() ?? "";
136+
137+ return lines.map((line) => parseLine(line, false)).join("\n") + (lines.length > 0 ? "\n" : "");
138+ },
139+ end(): string {
140+ if (buffer.length > 0) {
141+ const out = parseLine(buffer, true);
142+ buffer = "";
143+ return out;
144+ }
145+ return "";
146+ }
147+ };
148+}
package.json+18−0
@@ -0,0 +1,18 @@
1+{
2+ "name": "yoctomarkdown",
3+ "module": "index.ts",
4+ "type": "module",
5+ "private": true,
6+ "devDependencies": {
7+ "@types/bun": "latest"
8+ },
9+ "peerDependencies": {
10+ "typescript": "^5"
11+ },
12+ "dependencies": {
13+ "yoctocolors": "^2.1.2"
14+ },
15+ "bin": {
16+ "yoctomarkdown": "./cli.ts"
17+ }
18+}
spec.md+193−0
@@ -0,0 +1,193 @@
1+# YoctoMarkdown Specification
2+
3+YoctoMarkdown is a small Bun-native Markdown highlighter for terminal output.
4+It reads Markdown and writes ANSI-colored text to stdout or returns it as a string.
5+The focus is simple, fast, incremental rendering for CLI and Programmatic use.
6+
7+## Overview
8+
9+YoctoMarkdown MUST:
10+
11+- accept Markdown from a complete string, a file, or a stream
12+- process input incrementally
13+- render supported Markdown syntax as ANSI-styled terminal text
14+- preserve unsupported or malformed Markdown as plain text
15+- avoid buffering the full document when used in streaming mode
16+
17+YoctoMarkdown is not a full CommonMark implementation.
18+It supports a small, practical subset intended for terminal display.
19+
20+## Dependencies
21+
22+YoctoMarkdown is intended to use:
23+
24+- **Bun** as the runtime, stream, and build tool
25+- **yoctocolors** from npm for ANSI color rendering - https://github.com/sindresorhus/yoctocolors
26+
27+## Supported Markdown
28+
29+Version 1 supports the following syntax:
30+
31+| Element | Syntax | Behavior |
32+| ----------------- | ------------------ | ------------------ |
33+| Heading 1 | `# Title` | styled heading |
34+| Heading 2 | `## Title` | styled heading |
35+| Heading 3 | `### Title` | styled heading |
36+| Bold | `**text**` | styled inline text |
37+| Italic | `*text*` | styled inline text |
38+| Inline code | `` `code` `` | styled inline code |
39+| Fenced code block | ` ``` ` | styled block code |
40+| Link | `[text](url)` | styled link text |
41+| Unordered list | `- item`, `* item` | styled marker |
42+| Ordered list | `1. item` | styled marker |
43+| Blockquote | `> quote` | styled marker |
44+| Horizontal rule | `---` | styled rule |
45+| Plain text | any other text | unchanged text |
46+
47+Unsupported syntax MUST be rendered as plain text.
48+
49+## Parsing Rules
50+
51+The parser is line-aware and incremental.
52+
53+### Block rules
54+
55+- Headings are recognized only at the start of a line.
56+- Only `#`, `##`, and `###` headings are supported.
57+- Fenced code blocks use triple backticks.
58+- Inside a fenced code block, all text is treated as code until a closing triple backtick fence is found.
59+- Horizontal rules are recognized only when the full trimmed line is `---`, `***`, or `___`.
60+- List and blockquote markers are recognized only at the start of a line.
61+
62+### Inline rules
63+
64+- Inline code has priority over other inline formatting.
65+- Links are recognized only in the form `[text](url)`.
66+- Bold uses `**text**`.
67+- Italic uses `*text*`.
68+- Nested or ambiguous inline formatting is not required to match full CommonMark behavior.
69+
70+### Malformed input
71+
72+- Incomplete inline constructs MAY remain buffered while more input is expected.
73+- At end of input, any unclosed inline construct MUST be emitted as plain text.
74+- An unclosed fenced code block MUST render as code until end of input.
75+
76+## Streaming Behavior
77+
78+Streaming mode MUST work chunk by chunk.
79+
80+For each chunk:
81+
82+1. append the chunk to an internal buffer
83+2. parse as much complete Markdown as possible
84+3. render completed output immediately
85+4. keep only unresolved trailing text in the buffer
86+
87+The implementation MUST preserve enough state to handle syntax split across chunk boundaries.
88+
89+## Rendering
90+
91+Rendering maps recognized Markdown elements to ANSI styles.
92+
93+The implementation MUST provide these built-in theme names:
94+
95+- `16`
96+- `256`
97+- `truecolor`
98+- `minimal`
99+- `none`
100+
101+Theme behavior:
102+
103+- headings MUST be visually distinct from plain text
104+- bold and italic SHOULD be visually distinct from plain text
105+- code and code blocks MUST be visually distinct from surrounding text
106+- links SHOULD be visually distinct from plain text
107+- list and blockquote markers MAY be styled independently
108+- `none` MUST disable ANSI styling entirely
109+
110+The exact colors are implementation-defined.
111+
112+## Configuration
113+
114+The implementation MUST support the following options:
115+
116+```ts
117+interface Options {
118+ theme?: "16" | "256" | "truecolor" | "minimal" | "none" | Theme;
119+ tabWidth?: number;
120+ wordWrap?: number | "auto" | 0;
121+ yieldEvery?: number;
122+}
123+```
124+
125+Default values:
126+
127+- `theme`: `'16'`
128+- `tabWidth`: `2`
129+- `wordWrap`: `'auto'`
130+- `yieldEvery`: `1000`
131+
132+### Word wrap
133+
134+If wrapping is enabled:
135+
136+- `'auto'` means terminal width when available, otherwise `80`
137+- `0` disables wrapping
138+- ANSI escape sequences MUST NOT count toward visible width
139+
140+## Library API
141+
142+The library MUST expose:
143+
144+```ts
145+highlightSync(input: string, options?: Options): string
146+createHighlighter(options?: Options): Highlighter
147+```
148+
149+```ts
150+interface Highlighter {
151+ write(chunk: string | Uint8Array): string;
152+ end(): string;
153+}
154+```
155+
156+Behavior:
157+
158+- `highlightSync()` returns the fully rendered ANSI string for a complete input string
159+- `createHighlighter()` returns an incremental highlighter
160+- `write()` returns rendered output for the provided chunk
161+- `end()` flushes any remaining buffered text
162+
163+## CLI
164+
165+The CLI command is:
166+
167+```text
168+yoctomarkdown [options] [file]
169+```
170+
171+If `file` is provided, the CLI reads that file.
172+Otherwise, it reads from stdin.
173+
174+Supported options:
175+
176+- `-t, --theme <name>`
177+- `-w, --wrap <n|auto|0>`
178+- `-h, --help`
179+
180+The CLI MUST:
181+
182+- write rendered output to stdout
183+- write diagnostics to stderr
184+- exit with status `0` on success
185+- exit with non-zero status on input or argument errors
186+
187+## Non-Goals
188+
189+- full CommonMark compliance
190+- GFM extensions such as tables, task lists, or strikethrough
191+- HTML rendering
192+- syntax highlighting inside code blocks
193+- AST generation
themes.ts+60−0
@@ -0,0 +1,60 @@
1+import * as colors from "yoctocolors";
2+
3+export interface Theme {
4+ heading: (text: string) => string;
5+ bold: (text: string) => string;
6+ italic: (text: string) => string;
7+ code: (text: string) => string;
8+ codeBlock: (text: string) => string;
9+ link: (text: string) => string;
10+ listMarker: (text: string) => string;
11+ blockquote: (text: string) => string;
12+ hr: (text: string) => string;
13+}
14+
15+const none: Theme = {
16+ heading: (t) => t,
17+ bold: (t) => t,
18+ italic: (t) => t,
19+ code: (t) => t,
20+ codeBlock: (t) => t,
21+ link: (t) => t,
22+ listMarker: (t) => t,
23+ blockquote: (t) => t,
24+ hr: (t) => t,
25+};
26+
27+const minimal: Theme = {
28+ heading: colors.bold,
29+ bold: colors.bold,
30+ italic: colors.italic,
31+ code: colors.bgGray,
32+ codeBlock: colors.dim,
33+ link: colors.underline,
34+ listMarker: colors.dim,
35+ blockquote: colors.dim,
36+ hr: colors.dim,
37+};
38+
39+const ansi16: Theme = {
40+ heading: (t) => colors.cyan(colors.bold(t)),
41+ bold: colors.bold,
42+ italic: colors.italic,
43+ code: (t) => colors.bgBlack(colors.yellow(t)),
44+ codeBlock: colors.yellow,
45+ link: colors.blue,
46+ listMarker: colors.magenta,
47+ blockquote: colors.green,
48+ hr: colors.gray,
49+};
50+
51+const ansi256 = ansi16; // In a full implementation we might map specific 256 colors
52+const truecolor = ansi16; // Same
53+
54+export const themes: Record<string, Theme> = {
55+ none,
56+ minimal,
57+ "16": ansi16,
58+ "256": ansi256,
59+ truecolor: truecolor,
60+};
tsconfig.json+29−0
@@ -0,0 +1,29 @@
1+{
2+ "compilerOptions": {
3+ // Environment setup & latest features
4+ "lib": ["ESNext"],
5+ "target": "ESNext",
6+ "module": "Preserve",
7+ "moduleDetection": "force",
8+ "jsx": "react-jsx",
9+ "allowJs": true,
10+
11+ // Bundler mode
12+ "moduleResolution": "bundler",
13+ "allowImportingTsExtensions": true,
14+ "verbatimModuleSyntax": true,
15+ "noEmit": true,
16+
17+ // Best practices
18+ "strict": true,
19+ "skipLibCheck": true,
20+ "noFallthroughCasesInSwitch": true,
21+ "noUncheckedIndexedAccess": true,
22+ "noImplicitOverride": true,
23+
24+ // Some stricter flags (disabled by default)
25+ "noUnusedLocals": false,
26+ "noUnusedParameters": false,
27+ "noPropertyAccessFromIndexSignature": false
28+ }
29+}