Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/bug_report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ body:
- QR Code
- Lorem Ipsum
- Regex Tester
- Markdown Preview
- The site itself (⌘K palette, sidebar, shortcuts, saved state)
validations:
required: true
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ jobs:
set -euo pipefail
pnpm pack --pack-destination "$RUNNER_TEMP" >/dev/null
LIST=$(tar -tzf "$RUNNER_TEMP"/fadeltd-devtools-core-*.tgz)
for sub in base64 color cron css csv diff env escape hash html-text id-gen json json-types jwt list lorem number qr random regex share slug sql text text-bytes text-stats timestamp unicode url yaml-toml; do
for sub in base64 color cron css csv diff env escape hash html-text id-gen json json-types jwt list lorem markdown number qr random regex share slug sql text text-bytes text-stats timestamp unicode url yaml-toml; do
# A here-string, not `echo | grep -q`: grep -q stops reading at the
# first match, and under pipefail the writer's SIGPIPE fails the step.
grep -qx "package/dist/$sub/index.d.ts" <<< "$LIST" || { echo "::error::Missing dist/$sub/index.d.ts"; exit 1; }
Expand Down
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

## [Unreleased]

Nothing yet.
### Added
- Markdown Preview: write or paste GitHub-flavoured Markdown beside a live preview. Copy formatted puts the rendered HTML and the Markdown source on the clipboard together, so a paste into Slack, Google Docs or Gmail keeps tables (with column alignment, escaped pipes, and links and `<br>` line breaks inside cells), lists, links and monospace code, where a plain copy arrives as pipes and dashes. Copy Markdown copies just the source. Raw HTML in the source is shown as text, never run; links are limited to `http`, `https`, `mailto` and `tel`; remote images are not loaded, since the site makes no network requests. Rendering runs in a background worker, and the preview of a very long document shows its start while the copy carries all of it. (#28)
- CSV to Table: Copy formatted, in the Table and Markdown views, copies the data as a real table (rich text, with TSV as the plain-text half), so it pastes into Slack, Docs, Gmail and spreadsheets as a table. Number columns are right-aligned and line breaks inside cells are kept. Offered up to 10,000 cells.

### Fixed
- CSV to Table: Ctrl/Cmd+Shift+C in the Table view copied nothing. It now copies the table.

## [0.16.0] — 2026-10-30

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ It also does what the free sites usually don't: reports **every** JSON error wit

- **[Diff Checker](https://devtools.fadeltd.dev/diff)** — side-by-side or unified, word-level highlights, ignore whitespace or case, compare as sorted lines or key-sorted JSON, unified patch, share by link
- **[Regex Tester](https://devtools.fadeltd.dev/regex)** — JavaScript regex with every match, line and column, named and numbered groups, replace preview; runaway patterns can be cancelled
- **[Markdown Preview](https://devtools.fadeltd.dev/markdown)** — GitHub-flavoured Markdown with a live preview; copy it as rich text and tables stay tables in Slack, Docs and Gmail
- **[List Tools](https://devtools.fadeltd.dev/list)** — sort, natural sort, dedupe, shuffle, filter and 11 more steps chained into a shareable pipeline
- **[Word Counter & Text Statistics](https://devtools.fadeltd.dev/text-stats)** — characters four ways, words, sentences, reading time, word frequency
- **[Unicode Inspector](https://devtools.fadeltd.dev/unicode)** — finds zero-width, bidi (Trojan Source) and other invisible characters, one-click clean
Expand Down
4 changes: 3 additions & 1 deletion packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

## [Unreleased]

Nothing yet.
### Added
- `/markdown`: `parseMarkdown(src)` turns GitHub-flavoured Markdown into a plain-data tree (`MdDoc`) that survives `structuredClone`, never throwing. Raw HTML comes back as the text it is, except `<br>`; character references are decoded once; link and image destinations pass `safeHref` / `safeImageSrc` or the node degrades to its text. `toHtml(doc)` serialises a tree to escaped HTML with a fixed tag set and the inline styles a rich-text paste needs (table borders, column alignment, monospace code). `limitDoc(doc, budget)` cuts a tree to a node budget for renderers that build real DOM, inside a long list or table if need be. Adds `marked` as a dependency, for its tokenizer only.
- `/csv`: `toHtmlTable(table, types)` writes an HTML `<table>` for the clipboard, with cells escaped, line breaks as `<br>` and number columns right-aligned.

## [0.8.0] — 2026-10-30

Expand Down
1 change: 1 addition & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ await formatSql('select a from t where b = 1', { dialect: 'postgresql', keywordC
| `/color` | CSS color parsing with positioned errors; sRGB ↔ HSL ↔ OKLCH; gamut detection and clipping; WCAG contrast and nearest passing foreground |
| `/qr` | QR payloads for text, URLs and Wi-Fi, encoded to a module matrix, plus a single-path SVG |
| `/regex` | Flag checks, readable compile errors, `/pattern/flags` literals, every match with line, column and named group spans (JavaScript semantics, capped), and `replace` with a count and warnings for references that silently do nothing |
| `/markdown` | GitHub-flavoured Markdown to a plain-data tree (via `marked`'s tokenizer) and to escaped HTML for the clipboard, with raw HTML kept as text, a link-scheme allowlist, and a node budget for renderers |
| `/lorem` | Lorem ipsum by exact word, sentence or paragraph count, as text, HTML or Markdown, seedable |
| `/text` | Line/column offsets, character counts, UTF-8 size without encoding and long-line detection, shared by the tools |
| `/share` | Versioned, URL-safe compact encoding of any JSON value (deflate-raw + base64url) with a decode cap, for links that keep their content in the URL fragment |
Expand Down
11 changes: 9 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@fadeltd/devtools-core",
"version": "0.8.0",
"description": "The engines behind devtools.fadeltd.dev: list pipelines, JSON errors and fixes, JSON to TypeScript, Zod and Go types, diff, base64, IDs and UUIDs, timestamps, JWT decoding and verification, URL encoding, hashes and HMAC, slugs, text bytes, number bases, Unicode inspection, YAML/JSON/TOML, SQL and CSS formatting, CSV, .env, cron, string escaping, colors and contrast, QR codes and lorem ipsum. Pure functions, no DOM, no network.",
"description": "The engines behind devtools.fadeltd.dev: list pipelines, JSON errors and fixes, JSON to TypeScript, Zod and Go types, diff, base64, IDs and UUIDs, timestamps, JWT decoding and verification, URL encoding, hashes and HMAC, slugs, text bytes, number bases, Unicode inspection, YAML/JSON/TOML, SQL and CSS formatting, CSV, .env, cron, string escaping, colors and contrast, QR codes, lorem ipsum and Markdown to HTML. Pure functions, no DOM, no network.",
"license": "MIT",
"type": "module",
"sideEffects": false,
Expand Down Expand Up @@ -70,6 +70,10 @@
"types": "./dist/lorem/index.d.ts",
"default": "./dist/lorem/index.js"
},
"./markdown": {
"types": "./dist/markdown/index.d.ts",
"default": "./dist/markdown/index.js"
},
"./number": {
"types": "./dist/number/index.d.ts",
"default": "./dist/number/index.js"
Expand Down Expand Up @@ -151,6 +155,7 @@
"cronstrue": "3.32.0",
"diff": "9.0.0",
"jsonc-parser": "3.3.1",
"marked": "18.1.2",
"smol-toml": "1.9.1",
"uqr": "0.1.3",
"yaml": "2.9.1"
Expand Down Expand Up @@ -218,7 +223,9 @@
"oklch",
"wcag contrast",
"qr code",
"lorem ipsum"
"lorem ipsum",
"markdown",
"markdown to html"
],
"publishConfig": {
"access": "public"
Expand Down
50 changes: 49 additions & 1 deletion packages/core/src/csv/serialize.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { inferColumnTypes, valueType } from './infer.ts'
import { formatTable, jsonKeys, quoteField, toDelimited, toJson, toMarkdown } from './serialize.ts'
import { formatTable, jsonKeys, quoteField, toDelimited, toHtmlTable, toJson, toMarkdown } from './serialize.ts'

describe('quoteField', () => {
it('quotes only when needed', () => {
Expand Down Expand Up @@ -109,6 +109,54 @@ describe('toMarkdown', () => {
})
})

describe('toHtmlTable', () => {
const CELL = 'border:1px solid #d0d7de;padding:4px 8px'

it('writes a header row and a body', () => {
expect(toHtmlTable({ header: ['a', 'b'], rows: [['1', '2']] })).toBe(
'<table style="border-collapse:collapse">' +
`<thead><tr><th style="${CELL};font-weight:600">a</th><th style="${CELL};font-weight:600">b</th></tr></thead>` +
`<tbody><tr><td style="${CELL}">1</td><td style="${CELL}">2</td></tr></tbody>` +
'</table>',
)
})

it('has no header row when the header is off', () => {
const html = toHtmlTable({ header: null, rows: [['1', '2']] })
expect(html).not.toContain('<thead>')
expect(html).toContain(`<tbody><tr><td style="${CELL}">1</td>`)
})

it('escapes cells, so pasted HTML stays text', () => {
const html = toHtmlTable({ header: ['<b>h</b>'], rows: [['<script>alert(1)</script>'], ['a & "b"']] })
expect(html).toContain('&lt;b&gt;h&lt;/b&gt;')
expect(html).toContain('&lt;script&gt;alert(1)&lt;/script&gt;')
expect(html).toContain('a &amp; &quot;b&quot;')
expect(html).not.toContain('<script>')
})

it('keeps a pipe as it is and turns a line break into <br>', () => {
const html = toHtmlTable({ header: ['h'], rows: [['x|y'], ['line1\r\nline2\nline3']] })
expect(html).toContain('>x|y</td>')
expect(html).toContain('>line1<br>line2<br>line3</td>')
})

it('right-aligns number columns', () => {
const html = toHtmlTable({ header: ['name', 'n'], rows: [['ann', '7']] }, ['text', 'number'])
expect(html).toContain(`<td style="${CELL}">ann</td><td style="${CELL};text-align:right">7</td>`)
expect(html).toContain(`<th style="${CELL};font-weight:600;text-align:right">n</th>`)
})

it('fills a short row so every row has the same cells', () => {
const html = toHtmlTable({ header: ['a', 'b'], rows: [['1']] })
expect(html).toContain(`<td style="${CELL}">1</td><td style="${CELL}"></td>`)
})

it('is empty for an empty table', () => {
expect(toHtmlTable({ header: null, rows: [] })).toBe('')
})
})

describe('formatTable', () => {
it('dispatches to each writer', () => {
const t = { header: ['a'], rows: [['1']] }
Expand Down
33 changes: 33 additions & 0 deletions packages/core/src/csv/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { toHtml } from '../markdown/html.ts'
import type { MdInline } from '../markdown/types.ts'
import type { ColumnType } from './infer.ts'
import type { Delimiter } from './parse.ts'

Expand Down Expand Up @@ -128,6 +130,37 @@ export function toMarkdown(table: TableData, types: readonly ColumnType[] = []):
return [line(head), rule, ...body.map(line)].join('\n') + '\n'
}

function htmlCell(value: string): MdInline[] {
const out: MdInline[] = []
value.split(/\r\n|\r|\n/).forEach((line, i) => {
if (i > 0) out.push({ type: 'br' })
if (line !== '') out.push({ type: 'text', value: line })
})
return out
}

/**
* An HTML `<table>` for the clipboard: pasted as rich text it stays a table in
* Slack, Google Docs and Gmail, where the Markdown form arrives as pipes and
* dashes. Cells are escaped, a line break inside a cell becomes `<br>`, and
* number columns are right-aligned when `types` is given. With the header off
* there is no header row, since HTML does not require one.
*/
export function toHtmlTable(table: TableData, types: readonly ColumnType[] = []): string {
const columns = Math.max(table.header?.length ?? 0, ...table.rows.slice(0, 1).map((r) => r.length))
if (columns === 0) return ''
return toHtml({
blocks: [
{
type: 'table',
align: Array.from({ length: columns }, (_, c) => (types[c] === 'number' ? 'right' : null)),
header: (table.header ?? []).map(htmlCell),
rows: table.rows.map((r) => r.map(htmlCell)),
},
],
})
}

/** One entry point for the text outputs. */
export function formatTable(table: TableData, format: CsvOutputFormat, types: readonly ColumnType[] = []): string {
switch (format) {
Expand Down
126 changes: 126 additions & 0 deletions packages/core/src/markdown/html.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import fc from 'fast-check'
import { describe, expect, it } from 'vitest'
import { toHtml } from './html.ts'
import { parseMarkdown } from './parse.ts'

const html = (src: string): string => toHtml(parseMarkdown(src))

/** Every tag `toHtml` may write. */
const TAGS = new Set([
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'blockquote', 'ul', 'ol', 'li', 'pre', 'code',
'table', 'thead', 'tbody', 'tr', 'th', 'td', 'hr', 'strong', 'em', 'del', 'a', 'img', 'br',
])
const ATTRS = new Set(['href', 'title', 'src', 'alt', 'style', 'start'])

/**
* Walk the output as a browser's tokenizer would see it: text and quoted
* attribute values hold no bare `<`, `>` or `"`, so a tag is exactly `<…>`.
*/
function audit(out: string): { tags: string[]; attrs: string[]; schemes: string[] } {
const tags: string[] = []
const attrs: string[] = []
const schemes: string[] = []
for (const m of out.matchAll(/<(\/?)([^\s>]*)((?:\s+[^\s=>]+="[^"]*")*)\s*>/g)) {
tags.push(m[2]!)
for (const a of m[3]!.matchAll(/\s+([^\s=>]+)="([^"]*)"/g)) {
attrs.push(a[1]!)
if (a[1] === 'href' || a[1] === 'src') schemes.push(a[2]!.split(':')[0]!.toLowerCase())
}
}
// Anything the pattern above did not consume must hold no `<` at all.
const rest = out.replace(/<(\/?)([^\s>]*)((?:\s+[^\s=>]+="[^"]*")*)\s*>/g, '')
if (rest.includes('<') || rest.includes('>')) throw new Error(`stray angle bracket in: ${rest.slice(0, 200)}`)
return { tags, attrs, schemes }
}

describe('toHtml', () => {
it('is empty for an empty document', () => {
expect(html('')).toBe('')
})

it('writes the usual blocks', () => {
expect(html('# T\n\npara *e* **s** ~~d~~\n\n> q\n\n---')).toBe(
'<h1>T</h1>\n<p>para <em>e</em> <strong>s</strong> <del>d</del></p>\n<blockquote><p>q</p></blockquote>\n<hr>',
)
})

it('writes a table with borders and the alignment of each column', () => {
const out = html('| a | b |\n|:--|--:|\n| 1 | 2 |')
expect(out).toContain('<table style="border-collapse:collapse"><thead><tr><th style="border:1px solid #d0d7de;padding:4px 8px;font-weight:600;text-align:left">a</th>')
expect(out).toContain('<td style="border:1px solid #d0d7de;padding:4px 8px;text-align:right">2</td>')
expect(out.endsWith('</tbody></table>')).toBe(true)
})

it('keeps escaped pipes, line breaks and links inside cells', () => {
const out = html('| k | v |\n|---|---|\n| a\\|b | one<br>two [l](https://x.example) |')
expect(out).toContain('>a|b</td>')
expect(out).toContain('>one<br>two <a href="https://x.example">l</a></td>')
})

it('marks code as monospace, inline and in a block', () => {
expect(html('`a < b`')).toBe(
'<p><code style="font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace">a &lt; b</code></p>',
)
expect(html('```\n<b>&amp;\n```')).toBe(
'<pre style="font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace"><code>&lt;b&gt;&amp;amp;</code></pre>',
)
})

it('writes lists, the start number, and task marks on the first line', () => {
expect(html('- a\n- b')).toBe('<ul><li>a</li>\n<li>b</li></ul>')
expect(html('3. a')).toBe('<ol start="3"><li>a</li></ol>')
expect(html('- [ ] todo\n- [x] done')).toBe('<ul><li>☐ todo</li>\n<li>☑ done</li></ul>')
expect(html('- [x] loose\n\n- [ ] too')).toBe('<ul><li><p>☑ loose</p></li>\n<li><p>☐ too</p></li></ul>')
})

it('escapes raw HTML instead of emitting it', () => {
expect(html('<script>alert(1)</script>')).toBe('<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>')
expect(html('a <img src=x onerror=alert(1)> b')).toBe('<p>a &lt;img src=x onerror=alert(1)&gt; b</p>')
expect(html('&lt;script&gt;')).toBe('<p>&lt;script&gt;</p>')
})

it('drops a link it will not link, and keeps its text', () => {
expect(html('[x](javascript:alert(1))')).toBe('<p>x</p>')
})

it('escapes quotes and ampersands in attributes', () => {
expect(html('[a](https://x.example/?a=1&b=2 "say \\"hi\\" <now>")')).toBe(
'<p><a href="https://x.example/?a=1&amp;b=2" title="say &quot;hi&quot; &lt;now&gt;">a</a></p>',
)
expect(html('![a "q" <b>](https://i.example/x.png)')).toBe(
'<p><img src="https://i.example/x.png" alt="a &quot;q&quot; &lt;b&gt;"></p>',
)
expect(html('[a](<https://x.example/"onmouseover="alert(1)>)')).not.toMatch(/"\s*onmouseover=/)
})
})

describe('toHtml: properties', () => {
// Markdown-shaped noise finds more structure than uniformly random text.
const fragment = fc.constantFrom(
'# ', '> ', '- ', '1. ', '- [x] ', '| ', ' | ', '|---|', '\n', '\n\n', '```', '`', '*', '**', '~~', '_',
'[', ']', '(', ')', '<', '>', '"', "'", '&', '&amp;', '&lt;', '&#60;', '\\', '!', ':', '/',
'javascript:', 'data:text/html,', 'https://a.example', 'http://', '<script>', '</script>', '<br>',
'<img src=x onerror=alert(1)>', '<a href="javascript:x">', 'onclick="x"', ' ', 'text', 'a', '=',
)
const noisy = fc.array(fc.oneof(fragment, fc.string({ maxLength: 6 })), { maxLength: 40 }).map((a) => a.join(''))

it('has an audit that sees what it is there to catch', () => {
expect(audit('<p>a</p><script>x</script>').tags).toContain('script')
expect(audit('<p onclick="x">a</p>').attrs).toContain('onclick')
expect(audit('<a href="JavaScript:x">a</a>').schemes).toEqual(['javascript'])
expect(() => audit('<p>a < b</p>')).toThrow()
expect(() => audit('<p>a</p><img src=x onerror=alert(1)>')).toThrow()
})

it('never throws, and writes only its own tags, attributes and schemes', () => {
fc.assert(
fc.property(fc.oneof(noisy, fc.string()), (src) => {
const { tags, attrs, schemes } = audit(html(src))
for (const t of tags) expect(TAGS.has(t)).toBe(true)
for (const a of attrs) expect(ATTRS.has(a)).toBe(true)
for (const s of schemes) expect(['http', 'https', 'mailto', 'tel', 'data']).toContain(s)
}),
{ numRuns: 2000 },
)
})
})
Loading
Loading