markdown-parity-check 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erik Rekola
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # markdown-parity-check
2
+
3
+ Compare the main content of HTML and Markdown pages from the command line. The report lists changed text, numbers, links and blocks, each with its source location, from two local files or from both representations of one URL.
4
+
5
+ ## Install
6
+
7
+ Use Node.js 22 or 24. The package is published on npm as `markdown-parity-check`.
8
+
9
+ ```sh
10
+ npx markdown-parity-check --help
11
+ ```
12
+
13
+ To install the command permanently, run `npm install -g markdown-parity-check`. The command name is `markdown-parity-check`.
14
+
15
+ ## Usage
16
+
17
+ To compare a website, run the CLI with `--url https://example.com/page`. It requests HTML and Markdown from the same URL using the corresponding Accept headers. Use `--markdown-url` to specify a separate Markdown address.
18
+
19
+ ```sh
20
+ markdown-parity-check --url https://example.com/page
21
+ markdown-parity-check --url https://example.com/page --format json --output report.json
22
+ markdown-parity-check --html-file page.html --markdown-file page.md --base-url https://example.com/page
23
+ ```
24
+
25
+ Front matter in the Markdown file is kept by default. Add `--front-matter strip` to remove it before the comparison.
26
+
27
+ ## Options
28
+
29
+ | Option | Purpose |
30
+ | --- | --- |
31
+ | `--url URL` | Request both formats from a URL. |
32
+ | `--markdown-url URL` | Set a separate Markdown URL. |
33
+ | `--html-file PATH --markdown-file PATH` | Compare local files. |
34
+ | `--base-url URL` | Resolve relative links in local files. |
35
+ | `--selector CSS` | Choose the HTML content container. |
36
+ | `--front-matter keep` or `--front-matter strip` | Keep metadata by default or remove it explicitly. |
37
+ | `--format json` | Print a structured report. |
38
+ | `--output PATH` | Write the report to a file. |
39
+ | `--strict` | Treat warnings as failures. |
40
+ | `--timeout-ms MS` | Set the request deadline. |
41
+ | `--max-bytes N` | Limit the decoded response size. |
42
+
43
+ ## Exit codes
44
+
45
+ | Code | Meaning |
46
+ | --- | --- |
47
+ | `0` | Comparison completed without rejecting findings. |
48
+ | `1` | Content or Markdown delivery failed the check. |
49
+ | `2` | Input or execution prevented a reliable comparison. |
50
+
51
+ A zero exit code means the implemented checks passed. It does not prove semantic equivalence.
52
+
53
+ ## Scope
54
+
55
+ The comparison covers headings, paragraphs, lists, tables, code and links. It detects repeated blocks and reports ordering changes. Formatting differences can produce warnings while changed wording produces errors.
56
+
57
+ HTML content selection prefers the main content container. A fallback to the page body produces a warning. JavaScript is not executed. Block matching is heuristic and some complex layouts need an explicit selector.
58
+
59
+ URL fetching blocks non-public network targets and checks redirects. Request deadlines and response size limits bound network work. Reports mask URL query values, but content excerpts may still contain private information. Review reports before sharing them.
60
+
61
+ ## Run from source
62
+
63
+ ```sh
64
+ git clone https://github.com/erekola/markdown-parity-check.git
65
+ cd markdown-parity-check
66
+ npm ci --ignore-scripts
67
+ npm run build
68
+ node dist/src/cli.js --html-file test/fixtures/same/page.html --markdown-file test/fixtures/same/page.md --base-url https://example.com/page --front-matter strip
69
+ ```
70
+
71
+ The bundled example compares matching content. It explicitly removes the Markdown file's front matter.
72
+
73
+ ## Development
74
+
75
+ Run `npm run typecheck` and `npm test`. GitHub Actions tests Node.js 22 and 24 on Windows and Ubuntu. After CI passes on the main branch, the release workflow publishes the package version to npm when it is not there yet and creates the matching GitHub release with the package tarball attached.
76
+
77
+ ## Security
78
+
79
+ Report vulnerabilities privately to info@turva.dev. See [SECURITY.md](SECURITY.md) for the reporting instructions and the operating limits.
80
+
81
+ ## License
82
+
83
+ MIT. See [LICENSE](LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,23 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ Security fixes target the latest published release. Update to that release when a fix is available.
6
+
7
+ ## Reporting a vulnerability
8
+
9
+ Report suspected vulnerabilities privately to info@turva.dev. Include the affected version, reproduction steps and the expected impact. Remove credentials and private content from examples.
10
+
11
+ Please do not open a public issue for security reports. You can expect an initial response within a few days. Confirmed issues will be prioritized and you will be kept informed of progress.
12
+
13
+ ## Network and file access
14
+
15
+ URL mode requests HTML and Markdown over HTTP or HTTPS. Non-public network targets are blocked, including targets reached through DNS and redirects. Each fetch has a deadline and a limit on decoded response bytes. The defaults are 15 seconds and 5 MiB. JavaScript from fetched pages is not executed.
16
+
17
+ Offline mode reads the two files supplied by the caller. The output option writes a report to the selected path. Reports mask URL query values, but excerpts may contain private page content. Review reports before sharing them.
18
+
19
+ ## Dependencies and releases
20
+
21
+ The tool uses runtime dependencies to parse and compare content. Dependency versions and integrity hashes are recorded in package-lock.json. GitHub Actions installs locked dependencies with install scripts disabled and runs type checks and tests on Windows and Ubuntu.
22
+
23
+ The package is published on npm as `markdown-parity-check`. Each version has a matching GitHub release with the tarball attached. The first npm release was published from a maintainer machine and has no provenance attestation. Later versions may be published from GitHub Actions with trusted publishing. Check the version page on npmjs.com before relying on provenance for a given version.
@@ -0,0 +1,160 @@
1
+ // Block alignment between the HTML block list (A) and the Markdown block list (B).
2
+ // 1. Exact matches in order (LCS over strict keys) preserve duplicates and order.
3
+ // 2. Remaining exact-key blocks are paired as moved blocks (order changed).
4
+ // 3. Remaining blocks of the same type are paired by loose-key equality, then by token similarity.
5
+ // Everything left is missing (HTML only) or added (Markdown only).
6
+ /** paragraph and listItem are one group for alignment: a list rendered as paragraphs is a structure
7
+ * difference, not missing content. */
8
+ export function typeGroup(b) {
9
+ return b.type === 'listItem' ? 'paragraph' : b.type;
10
+ }
11
+ export function strictKey(b) {
12
+ const t = b.type === 'code' ? (b.code ?? b.text) : b.text;
13
+ return `${typeGroup(b)} ${t}`;
14
+ }
15
+ function looseKey(b) {
16
+ return `${typeGroup(b)} ${b.loose}`;
17
+ }
18
+ export const SIMILARITY_THRESHOLD = 0.6;
19
+ export const UNCERTAIN_THRESHOLD = 0.8;
20
+ function tokens(s) {
21
+ const m = new Map();
22
+ for (const t of s.split(' '))
23
+ if (t)
24
+ m.set(t, (m.get(t) ?? 0) + 1);
25
+ return m;
26
+ }
27
+ /** Dice coefficient over word tokens of the loose text. */
28
+ export function similarity(a, b) {
29
+ if (a.loose === '' || b.loose === '')
30
+ return 0;
31
+ const ta = tokens(a.loose);
32
+ const tb = tokens(b.loose);
33
+ let inter = 0;
34
+ let na = 0;
35
+ let nb = 0;
36
+ for (const [, c] of ta)
37
+ na += c;
38
+ for (const [, c] of tb)
39
+ nb += c;
40
+ for (const [t, c] of ta)
41
+ inter += Math.min(c, tb.get(t) ?? 0);
42
+ return (2 * inter) / (na + nb);
43
+ }
44
+ function lcs(keysA, keysB) {
45
+ const n = keysA.length;
46
+ const m = keysB.length;
47
+ const dp = [];
48
+ for (let i = 0; i <= n; i++)
49
+ dp.push(new Uint32Array(m + 1));
50
+ for (let i = n - 1; i >= 0; i--) {
51
+ const row = dp[i];
52
+ const next = dp[i + 1];
53
+ for (let j = m - 1; j >= 0; j--) {
54
+ row[j] = keysA[i] === keysB[j] ? next[j + 1] + 1 : Math.max(next[j], row[j + 1]);
55
+ }
56
+ }
57
+ const out = [];
58
+ let i = 0;
59
+ let j = 0;
60
+ while (i < n && j < m) {
61
+ if (keysA[i] === keysB[j]) {
62
+ out.push([i, j]);
63
+ i++;
64
+ j++;
65
+ }
66
+ else if (dp[i + 1][j] >= dp[i][j + 1])
67
+ i++;
68
+ else
69
+ j++;
70
+ }
71
+ return out;
72
+ }
73
+ export function align(a, b) {
74
+ const pairs = [];
75
+ const usedA = new Set();
76
+ const usedB = new Set();
77
+ const keysA = a.map(strictKey);
78
+ const keysB = b.map(strictKey);
79
+ for (const [i, j] of lcs(keysA, keysB)) {
80
+ pairs.push({ a: i, b: j, kind: 'exact', similarity: 1 });
81
+ usedA.add(i);
82
+ usedB.add(j);
83
+ }
84
+ // Moved blocks: exact key present on both sides but outside the in-order LCS.
85
+ const freeB = new Map();
86
+ for (let j = 0; j < b.length; j++) {
87
+ if (usedB.has(j))
88
+ continue;
89
+ const k = keysB[j];
90
+ const list = freeB.get(k) ?? [];
91
+ list.push(j);
92
+ freeB.set(k, list);
93
+ }
94
+ for (let i = 0; i < a.length; i++) {
95
+ if (usedA.has(i))
96
+ continue;
97
+ const list = freeB.get(keysA[i]);
98
+ if (list && list.length > 0) {
99
+ const j = list.shift();
100
+ pairs.push({ a: i, b: j, kind: 'moved', similarity: 1 });
101
+ usedA.add(i);
102
+ usedB.add(j);
103
+ }
104
+ }
105
+ // Loose-key pairs (formatting or punctuation differences only), in document order.
106
+ const looseB = new Map();
107
+ for (let j = 0; j < b.length; j++) {
108
+ if (usedB.has(j))
109
+ continue;
110
+ const k = looseKey(b[j]);
111
+ const list = looseB.get(k) ?? [];
112
+ list.push(j);
113
+ looseB.set(k, list);
114
+ }
115
+ for (let i = 0; i < a.length; i++) {
116
+ if (usedA.has(i))
117
+ continue;
118
+ const list = looseB.get(looseKey(a[i]));
119
+ if (list && list.length > 0) {
120
+ const j = list.shift();
121
+ pairs.push({ a: i, b: j, kind: 'loose', similarity: 1 });
122
+ usedA.add(i);
123
+ usedB.add(j);
124
+ }
125
+ }
126
+ // Similar pairs: greedy best-match by similarity above the threshold, same type only. Ties are broken
127
+ // by document order to keep results deterministic.
128
+ const candidates = [];
129
+ for (let i = 0; i < a.length; i++) {
130
+ if (usedA.has(i))
131
+ continue;
132
+ for (let j = 0; j < b.length; j++) {
133
+ if (usedB.has(j))
134
+ continue;
135
+ if (typeGroup(a[i]) !== typeGroup(b[j]))
136
+ continue;
137
+ const s = similarity(a[i], b[j]);
138
+ if (s >= SIMILARITY_THRESHOLD)
139
+ candidates.push({ i, j, s });
140
+ }
141
+ }
142
+ candidates.sort((x, y) => y.s - x.s || x.i - y.i || x.j - y.j);
143
+ for (const c of candidates) {
144
+ if (usedA.has(c.i) || usedB.has(c.j))
145
+ continue;
146
+ pairs.push({ a: c.i, b: c.j, kind: 'similar', similarity: c.s });
147
+ usedA.add(c.i);
148
+ usedB.add(c.j);
149
+ }
150
+ pairs.sort((x, y) => x.a - y.a || x.b - y.b);
151
+ const unmatchedA = [];
152
+ const unmatchedB = [];
153
+ for (let i = 0; i < a.length; i++)
154
+ if (!usedA.has(i))
155
+ unmatchedA.push(i);
156
+ for (let j = 0; j < b.length; j++)
157
+ if (!usedB.has(j))
158
+ unmatchedB.push(j);
159
+ return { pairs, unmatchedA, unmatchedB };
160
+ }
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env node
2
+ // Command-line entry point. Exit codes: 0 no rejecting finding, 1 rejecting findings, 2 input, fetch,
3
+ // parse or report error that prevented a reliable comparison.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { fetchUrl, FetchError, validateUrl } from './fetch.js';
9
+ import { renderJson, renderText } from './report.js';
10
+ import { errorReport, run, RunError } from './run.js';
11
+ import { maskUrl } from './normalize.js';
12
+ import { TOOL_NAME, TOOL_VERSION } from './version.js';
13
+ export const HELP = `${TOOL_NAME} ${TOOL_VERSION}
14
+ Compares the main content of a web page's HTML and Markdown representations and reports concrete
15
+ missing, added and changed blocks.
16
+
17
+ Usage:
18
+ ${TOOL_NAME} --url <https://example.com/page> [--markdown-url <url>] [options]
19
+ ${TOOL_NAME} --html-file <page.html> --markdown-file <page.md> [--base-url <url>] [options]
20
+
21
+ Modes:
22
+ --url <url> Fetch <url> twice: with Accept: text/html and with Accept: text/markdown.
23
+ --markdown-url <url> Fetch the Markdown from this explicit address instead (requires --url).
24
+ --html-file <path> Offline: local HTML file (requires --markdown-file).
25
+ --markdown-file <path> Offline: local Markdown file (requires --html-file).
26
+ --base-url <url> Offline: base for resolving relative links on both sides.
27
+
28
+ Options:
29
+ --selector <css> CSS selector for the HTML main content (default: main, article, [role=main], then body).
30
+ --front-matter keep|strip
31
+ Markdown front matter. keep (default) removes nothing and warns when the document
32
+ starts with a YAML-looking fenced block; strip removes that leading block.
33
+ --format text|json Report format (default: text).
34
+ --output <path> Write the report to a file instead of stdout. Refuses to overwrite an input file.
35
+ --timeout-ms <n> Per-fetch timeout in milliseconds (default: 15000).
36
+ --max-bytes <n> Cap on decoded response bytes per fetch (default: 5242880).
37
+ --strict Treat warnings as rejecting findings too.
38
+ --help, -h Show this help.
39
+ --version, -V Show the version.
40
+
41
+ Exit codes:
42
+ 0 comparison completed, no rejecting finding
43
+ 1 comparison completed, rejecting content or delivery differences found
44
+ 2 input, fetch, parse or report error prevented a reliable comparison
45
+
46
+ Only http(s) URLs to public addresses are fetched; loopback, private, link-local and other non-public
47
+ addresses are refused, also behind DNS and redirects. No JavaScript is executed. Exit 0 does not prove
48
+ semantic equivalence.
49
+ `;
50
+ export class CliError extends Error {
51
+ }
52
+ function positiveInt(name, raw, fallback) {
53
+ if (raw === undefined)
54
+ return fallback;
55
+ if (!/^\d+$/.test(raw) || Number(raw) <= 0)
56
+ throw new CliError(`${name} must be a positive integer (got "${raw}").`);
57
+ return Number(raw);
58
+ }
59
+ export function parseCliArgs(argv) {
60
+ let parsed;
61
+ try {
62
+ parsed = parseArgs({
63
+ args: argv,
64
+ allowPositionals: false,
65
+ strict: true,
66
+ options: {
67
+ url: { type: 'string' },
68
+ 'markdown-url': { type: 'string' },
69
+ 'html-file': { type: 'string' },
70
+ 'markdown-file': { type: 'string' },
71
+ 'base-url': { type: 'string' },
72
+ selector: { type: 'string' },
73
+ 'front-matter': { type: 'string', default: 'keep' },
74
+ format: { type: 'string', default: 'text' },
75
+ output: { type: 'string' },
76
+ 'timeout-ms': { type: 'string' },
77
+ 'max-bytes': { type: 'string' },
78
+ strict: { type: 'boolean', default: false },
79
+ help: { type: 'boolean', short: 'h', default: false },
80
+ version: { type: 'boolean', short: 'V', default: false },
81
+ },
82
+ });
83
+ }
84
+ catch (err) {
85
+ throw new CliError(err.message);
86
+ }
87
+ const v = parsed.values;
88
+ const format = v.format;
89
+ if (format !== 'text' && format !== 'json')
90
+ throw new CliError(`--format must be text or json (got "${format}").`);
91
+ const frontMatter = v['front-matter'];
92
+ if (frontMatter !== 'keep' && frontMatter !== 'strip')
93
+ throw new CliError(`--front-matter must be keep or strip (got "${frontMatter}").`);
94
+ const args = {
95
+ url: v.url,
96
+ markdownUrl: v['markdown-url'],
97
+ htmlFile: v['html-file'],
98
+ markdownFile: v['markdown-file'],
99
+ baseUrl: v['base-url'],
100
+ selector: v.selector,
101
+ frontMatter,
102
+ format,
103
+ output: v.output,
104
+ timeoutMs: positiveInt('--timeout-ms', v['timeout-ms'], 15000),
105
+ maxBytes: positiveInt('--max-bytes', v['max-bytes'], 5 * 1024 * 1024),
106
+ strict: v.strict ?? false,
107
+ help: v.help ?? false,
108
+ version: v.version ?? false,
109
+ };
110
+ if (args.help || args.version)
111
+ return args;
112
+ const urlMode = args.url !== undefined || args.markdownUrl !== undefined;
113
+ const fileMode = args.htmlFile !== undefined || args.markdownFile !== undefined;
114
+ if (urlMode && fileMode)
115
+ throw new CliError('Choose one mode: --url (with optional --markdown-url) or --html-file with --markdown-file.');
116
+ if (!urlMode && !fileMode)
117
+ throw new CliError('Missing input. Give --url <url>, or --html-file <path> with --markdown-file <path>. See --help.');
118
+ if (urlMode) {
119
+ if (args.url === undefined)
120
+ throw new CliError('--markdown-url requires --url.');
121
+ if (args.baseUrl !== undefined)
122
+ throw new CliError('--base-url applies to the offline mode only; in URL mode links resolve against the fetched URLs.');
123
+ validateUrl(args.url);
124
+ if (args.markdownUrl !== undefined)
125
+ validateUrl(args.markdownUrl);
126
+ }
127
+ else {
128
+ if (args.htmlFile === undefined || args.markdownFile === undefined)
129
+ throw new CliError('Offline mode needs both --html-file and --markdown-file.');
130
+ if (args.baseUrl !== undefined) {
131
+ try {
132
+ const u = new URL(args.baseUrl);
133
+ if (u.protocol !== 'http:' && u.protocol !== 'https:')
134
+ throw new Error('not http(s)');
135
+ }
136
+ catch {
137
+ throw new CliError(`--base-url must be an absolute http(s) URL (got "${args.baseUrl}").`);
138
+ }
139
+ }
140
+ }
141
+ if (args.selector !== undefined && args.selector.trim() === '')
142
+ throw new CliError('--selector must not be empty.');
143
+ if (args.output !== undefined) {
144
+ const out = path.resolve(args.output);
145
+ for (const input of [args.htmlFile, args.markdownFile]) {
146
+ if (input !== undefined && samePath(out, path.resolve(input)))
147
+ throw new CliError(`--output must not point at an input file (${args.output}).`);
148
+ }
149
+ }
150
+ return args;
151
+ }
152
+ function samePath(a, b) {
153
+ const norm = (p) => {
154
+ try {
155
+ return fs.realpathSync.native(p);
156
+ }
157
+ catch {
158
+ return p;
159
+ }
160
+ };
161
+ const x = norm(a);
162
+ const y = norm(b);
163
+ return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
164
+ }
165
+ function readFileInput(file, base) {
166
+ let body;
167
+ try {
168
+ body = fs.readFileSync(file, 'utf8');
169
+ }
170
+ catch (err) {
171
+ throw new CliError(`Cannot read ${file}: ${err.message}`);
172
+ }
173
+ if (body.charCodeAt(0) === 0xfeff)
174
+ body = body.slice(1);
175
+ return { meta: { kind: 'file', file, bytes: Buffer.byteLength(body, 'utf8'), baseUrl: base ? maskUrl(base) : null }, body, base };
176
+ }
177
+ async function fetchInput(url, accept, args, fetchFn) {
178
+ const res = await fetchFn(url, { accept, timeoutMs: args.timeoutMs, maxBytes: args.maxBytes });
179
+ return {
180
+ meta: { kind: 'url', url: maskUrl(res.finalUrl), requestedUrl: maskUrl(url), status: res.status, contentType: res.contentType, accept, redirects: res.redirects, bytes: res.bytes, baseUrl: maskUrl(res.finalUrl) },
181
+ body: res.body,
182
+ base: res.finalUrl,
183
+ };
184
+ }
185
+ function emit(report, args, io) {
186
+ const text = args.format === 'json' ? renderJson(report) : renderText(report);
187
+ if (args.output === undefined) {
188
+ io.stdout(text);
189
+ return;
190
+ }
191
+ try {
192
+ fs.writeFileSync(args.output, text, { encoding: 'utf8' });
193
+ }
194
+ catch (err) {
195
+ throw new CliError(`Cannot write report to ${args.output}: ${err.message}`);
196
+ }
197
+ io.stderr(`Report written to ${args.output} (${report.summary.result.toUpperCase()}, exit ${report.summary.exitCode}).\n`);
198
+ }
199
+ /** Runs the CLI and returns the exit code. Throws nothing; every failure becomes exit 2. */
200
+ export async function main(argv, io = { stdout: (s) => process.stdout.write(s), stderr: (s) => process.stderr.write(s) }, deps = {}) {
201
+ const fetchFn = deps.fetch ?? fetchUrl;
202
+ let args;
203
+ try {
204
+ args = parseCliArgs(argv);
205
+ }
206
+ catch (err) {
207
+ io.stderr(`Error: ${err.message}\n`);
208
+ return 2;
209
+ }
210
+ if (args.help) {
211
+ io.stdout(HELP);
212
+ return 0;
213
+ }
214
+ if (args.version) {
215
+ io.stdout(`${TOOL_VERSION}\n`);
216
+ return 0;
217
+ }
218
+ const options = { selector: args.selector, frontMatter: args.frontMatter, strict: args.strict, mode: args.url !== undefined ? 'url' : 'offline' };
219
+ let html = null;
220
+ let markdown = null;
221
+ let report;
222
+ try {
223
+ if (args.url !== undefined) {
224
+ html = await fetchInput(args.url, 'text/html', args, fetchFn);
225
+ if (html.meta.status !== undefined && html.meta.status >= 400) {
226
+ throw new CliError(`The HTML request returned HTTP ${html.meta.status}; there is no page to compare.`);
227
+ }
228
+ markdown = await fetchInput(args.markdownUrl ?? args.url, 'text/markdown', args, fetchFn);
229
+ }
230
+ else {
231
+ const base = args.baseUrl ?? null;
232
+ html = readFileInput(args.htmlFile, base);
233
+ markdown = readFileInput(args.markdownFile, base);
234
+ }
235
+ report = run(html, markdown, options);
236
+ }
237
+ catch (err) {
238
+ let message;
239
+ if (err instanceof FetchError)
240
+ message = `Fetch failed (${err.kind}) for ${err.url}: ${err.message}`;
241
+ else if (err instanceof CliError || err instanceof RunError)
242
+ message = err.message;
243
+ else
244
+ message = `Unexpected error: ${err.stack ?? String(err)}`;
245
+ report = errorReport(options, html?.meta ?? null, markdown?.meta ?? null, message);
246
+ try {
247
+ emit(report, args, io);
248
+ }
249
+ catch (e2) {
250
+ io.stderr(`Error: ${e2.message}\n`);
251
+ }
252
+ io.stderr(`Error: ${message}\n`);
253
+ return 2;
254
+ }
255
+ try {
256
+ emit(report, args, io);
257
+ }
258
+ catch (err) {
259
+ io.stderr(`Error: ${err.message}\n`);
260
+ return 2;
261
+ }
262
+ return report.summary.exitCode;
263
+ }
264
+ const invokedDirectly = process.argv[1] !== undefined && samePath(path.resolve(process.argv[1]), fileURLToPath(import.meta.url));
265
+ if (invokedDirectly) {
266
+ main(process.argv.slice(2)).then((code) => {
267
+ process.exitCode = code;
268
+ });
269
+ }