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 +21 -0
- package/README.md +83 -0
- package/SECURITY.md +23 -0
- package/dist/src/align.js +160 -0
- package/dist/src/cli.js +269 -0
- package/dist/src/compare.js +188 -0
- package/dist/src/fetch.js +275 -0
- package/dist/src/html.js +315 -0
- package/dist/src/markdown.js +320 -0
- package/dist/src/model.js +2 -0
- package/dist/src/netguard.js +129 -0
- package/dist/src/normalize.js +136 -0
- package/dist/src/report.js +88 -0
- package/dist/src/run.js +113 -0
- package/dist/src/version.js +5 -0
- package/package.json +55 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Address policy for the URL mode: only public unicast addresses are fetched. The check runs on the
|
|
2
|
+
// URL host, on every DNS answer and on every redirect target, and the checked address is the one the
|
|
3
|
+
// socket connects to (see fetch.ts).
|
|
4
|
+
import { isIP } from 'node:net';
|
|
5
|
+
export class BlockedAddressError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'BlockedAddressError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function ipv4ToInt(ip) {
|
|
12
|
+
const parts = ip.split('.').map(Number);
|
|
13
|
+
return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
|
|
14
|
+
}
|
|
15
|
+
const V4_BLOCKED = [
|
|
16
|
+
['0.0.0.0', 8],
|
|
17
|
+
['10.0.0.0', 8],
|
|
18
|
+
['100.64.0.0', 10],
|
|
19
|
+
['127.0.0.0', 8],
|
|
20
|
+
['169.254.0.0', 16],
|
|
21
|
+
['172.16.0.0', 12],
|
|
22
|
+
['192.0.0.0', 24],
|
|
23
|
+
['192.0.2.0', 24],
|
|
24
|
+
['192.88.99.0', 24],
|
|
25
|
+
['192.168.0.0', 16],
|
|
26
|
+
['198.18.0.0', 15],
|
|
27
|
+
['198.51.100.0', 24],
|
|
28
|
+
['203.0.113.0', 24],
|
|
29
|
+
['224.0.0.0', 4],
|
|
30
|
+
['240.0.0.0', 4],
|
|
31
|
+
];
|
|
32
|
+
export function isPublicIPv4(ip) {
|
|
33
|
+
const n = ipv4ToInt(ip);
|
|
34
|
+
for (const [base, bits] of V4_BLOCKED) {
|
|
35
|
+
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
|
|
36
|
+
if (((n & mask) >>> 0) === ((ipv4ToInt(base) & mask) >>> 0))
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
/** Expands an IPv6 address into 8 16-bit groups. Returns null when it cannot be parsed. */
|
|
42
|
+
export function expandIPv6(ip) {
|
|
43
|
+
let s = ip.toLowerCase();
|
|
44
|
+
const zone = s.indexOf('%');
|
|
45
|
+
if (zone >= 0)
|
|
46
|
+
s = s.slice(0, zone);
|
|
47
|
+
// Embedded IPv4 tail, for example ::ffff:127.0.0.1.
|
|
48
|
+
const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);
|
|
49
|
+
if (v4) {
|
|
50
|
+
const n = ipv4ToInt(v4[1]);
|
|
51
|
+
s = s.slice(0, -v4[1].length) + ((n >>> 16) & 0xffff).toString(16) + ':' + (n & 0xffff).toString(16);
|
|
52
|
+
}
|
|
53
|
+
const halves = s.split('::');
|
|
54
|
+
if (halves.length > 2)
|
|
55
|
+
return null;
|
|
56
|
+
const head = halves[0] ? halves[0].split(':') : [];
|
|
57
|
+
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
|
58
|
+
const fill = 8 - head.length - tail.length;
|
|
59
|
+
if (fill < 0 || (halves.length === 1 && fill !== 0))
|
|
60
|
+
return null;
|
|
61
|
+
const groups = [...head, ...Array(fill).fill('0'), ...tail].map((g) => parseInt(g, 16));
|
|
62
|
+
if (groups.length !== 8 || groups.some((g) => Number.isNaN(g) || g < 0 || g > 0xffff))
|
|
63
|
+
return null;
|
|
64
|
+
return groups;
|
|
65
|
+
}
|
|
66
|
+
export function isPublicIPv6(ip) {
|
|
67
|
+
const g = expandIPv6(ip);
|
|
68
|
+
if (!g)
|
|
69
|
+
return false;
|
|
70
|
+
const [g0, g1, g2, g3, g4, g5, g6, g7] = g;
|
|
71
|
+
const allZeroTo = (k) => g.slice(0, k).every((x) => x === 0);
|
|
72
|
+
if (allZeroTo(8))
|
|
73
|
+
return false; // ::
|
|
74
|
+
if (allZeroTo(7) && g7 === 1)
|
|
75
|
+
return false; // ::1
|
|
76
|
+
if (allZeroTo(5) && g5 === 0xffff)
|
|
77
|
+
return isPublicIPv4(v4FromGroups(g6, g7)); // ::ffff:a.b.c.d
|
|
78
|
+
if (allZeroTo(6))
|
|
79
|
+
return isPublicIPv4(v4FromGroups(g6, g7)); // ::a.b.c.d (deprecated compatible)
|
|
80
|
+
if (g0 === 0x64 && g1 === 0xff9b && g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0)
|
|
81
|
+
return isPublicIPv4(v4FromGroups(g6, g7)); // 64:ff9b::/96 NAT64
|
|
82
|
+
if (g0 === 0x64 && g1 === 0xff9b && g2 === 1)
|
|
83
|
+
return false; // 64:ff9b:1::/48 local NAT64
|
|
84
|
+
if ((g0 & 0xfe00) === 0xfc00)
|
|
85
|
+
return false; // fc00::/7 unique local
|
|
86
|
+
if ((g0 & 0xffc0) === 0xfe80)
|
|
87
|
+
return false; // fe80::/10 link local
|
|
88
|
+
if ((g0 & 0xffc0) === 0xfec0)
|
|
89
|
+
return false; // fec0::/10 site local (deprecated)
|
|
90
|
+
if ((g0 & 0xff00) === 0xff00)
|
|
91
|
+
return false; // ff00::/8 multicast
|
|
92
|
+
if (g0 === 0x2001 && g1 === 0x0db8)
|
|
93
|
+
return false; // documentation
|
|
94
|
+
if (g0 === 0x2001 && g1 === 0)
|
|
95
|
+
return isPublicIPv4(v4FromGroups(g6 ^ 0xffff, g7 ^ 0xffff)); // Teredo: check the embedded client address
|
|
96
|
+
if (g0 === 0x2002)
|
|
97
|
+
return isPublicIPv4(v4FromGroups(g1, g2)); // 6to4
|
|
98
|
+
if (g0 === 0x0100 && g1 === 0 && g2 === 0 && g3 === 0)
|
|
99
|
+
return false; // 100::/64 discard
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
function v4FromGroups(hi, lo) {
|
|
103
|
+
return `${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}`;
|
|
104
|
+
}
|
|
105
|
+
export function isPublicAddress(ip) {
|
|
106
|
+
const v = isIP(ip);
|
|
107
|
+
if (v === 4)
|
|
108
|
+
return isPublicIPv4(ip);
|
|
109
|
+
if (v === 6)
|
|
110
|
+
return isPublicIPv6(ip);
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
/** Throws when the host name itself is a non-public literal or a local name. */
|
|
114
|
+
export function assertPublicHost(hostname) {
|
|
115
|
+
let h = hostname.toLowerCase().replace(/\.$/, '');
|
|
116
|
+
if (h.startsWith('[') && h.endsWith(']'))
|
|
117
|
+
h = h.slice(1, -1);
|
|
118
|
+
if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.home.arpa') || h === '') {
|
|
119
|
+
throw new BlockedAddressError(`Host "${hostname}" is a local name and is not fetched.`);
|
|
120
|
+
}
|
|
121
|
+
if (isIP(h) && !isPublicAddress(h)) {
|
|
122
|
+
throw new BlockedAddressError(`Address ${h} is not a public address and is not fetched.`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export function assertPublicResolved(hostname, address) {
|
|
126
|
+
if (!isPublicAddress(address)) {
|
|
127
|
+
throw new BlockedAddressError(`Host "${hostname}" resolves to ${address}, which is not a public address and is not fetched.`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Text normalization. Strict normalization preserves case and content characters; loose normalization is
|
|
2
|
+
// used only as an alignment aid.
|
|
3
|
+
const NBSP = /[\u00a0\u2007\u202f]/g;
|
|
4
|
+
const WS = /[ \t\r\n\f\v]+/g;
|
|
5
|
+
const ZERO_WIDTH = /[\u200b-\u200d\ufeff\u00ad]/g;
|
|
6
|
+
export function strictNormalize(text) {
|
|
7
|
+
return text
|
|
8
|
+
.normalize('NFC')
|
|
9
|
+
.replace(ZERO_WIDTH, '')
|
|
10
|
+
.replace(NBSP, ' ')
|
|
11
|
+
.replace(WS, ' ')
|
|
12
|
+
.trim();
|
|
13
|
+
}
|
|
14
|
+
export function looseNormalize(text) {
|
|
15
|
+
return strictNormalize(text)
|
|
16
|
+
.toLowerCase()
|
|
17
|
+
// Map typographic quotes and dashes to plain forms for alignment only.
|
|
18
|
+
.replace(/[\u2018\u2019\u201a\u2032]/g, "'")
|
|
19
|
+
.replace(/[\u201c\u201d\u201e\u2033]/g, '"')
|
|
20
|
+
.replace(/[\u2010-\u2015\u2212]/g, '-')
|
|
21
|
+
.replace(/\u2026/g, '...')
|
|
22
|
+
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
|
|
23
|
+
.replace(/\s+/g, ' ')
|
|
24
|
+
.trim();
|
|
25
|
+
}
|
|
26
|
+
/** Code content: normalize line endings and strip a trailing newline only. */
|
|
27
|
+
export function normalizeCode(code) {
|
|
28
|
+
return code.replace(/\r\n?/g, '\n').replace(/\n+$/, '');
|
|
29
|
+
}
|
|
30
|
+
// A numeric token: optional sign (ASCII hyphen, Unicode minus or plus) that is not preceded by a letter
|
|
31
|
+
// or digit (so the "-09" in 2026-09-10 is a separator, not a sign), digits with inner separators
|
|
32
|
+
// (decimal, thousands, date, time, version), optional percent or currency sign on either side.
|
|
33
|
+
const NUMBER_RE = /(?<![\p{L}\p{N}])(?:[€$£]\s?)?[-\u2212+]?\d+(?:[.,:\/\-\u2010-\u2015\u2212]\d+)*\s?(?:%|€|\$|£)?/gu;
|
|
34
|
+
/** Extracts numeric tokens (prices, percentages, dates, versions, signed values) in source order. */
|
|
35
|
+
export function extractNumbers(text) {
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const m of text.matchAll(NUMBER_RE)) {
|
|
38
|
+
// Dash variants (hyphen, en dash, em dash, Unicode minus) are one separator or sign character.
|
|
39
|
+
out.push(m[0].replace(/\s+/g, '').replace(/[\u2010-\u2015\u2212]/g, '-'));
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
/** Report excerpt: URLs inside the text are masked BEFORE truncation, so a cut query value cannot leak. */
|
|
44
|
+
export function excerpt(text, max = 80) {
|
|
45
|
+
const t = redactText(strictNormalize(text));
|
|
46
|
+
return t.length <= max ? t : t.slice(0, max - 1) + '\u2026';
|
|
47
|
+
}
|
|
48
|
+
// URL-like runs inside free text: absolute URLs, www. hosts, and root-relative paths that carry a query
|
|
49
|
+
// or fragment. Only the query values and the fragment are rewritten; other text is left untouched.
|
|
50
|
+
const URL_IN_TEXT = /(?:[a-z][a-z0-9+.-]*:\/\/[^\s<>"'()]+|www\.[^\s<>"'()]+|(?<![\w/])\/[^\s<>"'()]*[?#][^\s<>"'()]*|[^\s<>"'()]*\?[\w%.-]+=[^\s<>"'()]*)/giu;
|
|
51
|
+
/** Masks query values and fragments of every URL-like run in a piece of report text. */
|
|
52
|
+
export function redactText(text) {
|
|
53
|
+
return text.replace(URL_IN_TEXT, (m) => {
|
|
54
|
+
// Keep trailing sentence punctuation outside the URL.
|
|
55
|
+
const trail = /[.,;:!?]+$/.exec(m)?.[0] ?? '';
|
|
56
|
+
const core = m.slice(0, m.length - trail.length);
|
|
57
|
+
return maskHref(core) + trail;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
61
|
+
export function resolveHref(rawHref, base) {
|
|
62
|
+
const href = rawHref.trim();
|
|
63
|
+
if (href === '')
|
|
64
|
+
return null;
|
|
65
|
+
if (base) {
|
|
66
|
+
try {
|
|
67
|
+
return new URL(href, base).href;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
return new URL(href).href; // absolute already
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Masks query values and drops the fragment for display in reports and logs. Never returns the raw
|
|
81
|
+
* query of an unparseable input either. */
|
|
82
|
+
export function maskUrl(url) {
|
|
83
|
+
try {
|
|
84
|
+
const u = new URL(url);
|
|
85
|
+
for (const key of Array.from(u.searchParams.keys()))
|
|
86
|
+
u.searchParams.set(key, '***');
|
|
87
|
+
u.hash = '';
|
|
88
|
+
return u.href;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return maskHref(url);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Masks query values and drops the fragment of an absolute or relative href for display. */
|
|
95
|
+
export function maskHref(href) {
|
|
96
|
+
try {
|
|
97
|
+
const u = new URL(href);
|
|
98
|
+
for (const key of Array.from(u.searchParams.keys()))
|
|
99
|
+
u.searchParams.set(key, '***');
|
|
100
|
+
u.hash = '';
|
|
101
|
+
return u.href;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// Relative or unparseable: mask by hand.
|
|
105
|
+
const hashAt = href.indexOf('#');
|
|
106
|
+
let h = hashAt >= 0 ? href.slice(0, hashAt) : href;
|
|
107
|
+
const q = h.indexOf('?');
|
|
108
|
+
if (q >= 0) {
|
|
109
|
+
const params = h.slice(q + 1).split('&').map((kv) => (kv === '' ? kv : `${kv.split('=')[0]}=***`));
|
|
110
|
+
h = `${h.slice(0, q)}?${params.join('&')}`;
|
|
111
|
+
}
|
|
112
|
+
return h;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** Describes how two hrefs differ without revealing masked parts. */
|
|
116
|
+
export function hrefDifference(a, b) {
|
|
117
|
+
const parse = (h) => {
|
|
118
|
+
try {
|
|
119
|
+
const u = new URL(h, 'http://relative.invalid/');
|
|
120
|
+
return { path: `${u.origin}${u.pathname}`, query: u.search, hash: u.hash };
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return { path: h, query: '', hash: '' };
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const x = parse(a);
|
|
127
|
+
const y = parse(b);
|
|
128
|
+
const parts = [];
|
|
129
|
+
if (x.path !== y.path)
|
|
130
|
+
parts.push('path or host');
|
|
131
|
+
if (x.query !== y.query)
|
|
132
|
+
parts.push('query');
|
|
133
|
+
if (x.hash !== y.hash)
|
|
134
|
+
parts.push('fragment');
|
|
135
|
+
return parts.length ? parts.join(', ') : 'nothing visible';
|
|
136
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Report rendering: human-readable text and JSON. No ANSI colours anywhere.
|
|
2
|
+
import { TOOL_NAME } from './version.js';
|
|
3
|
+
import { redactText } from './normalize.js';
|
|
4
|
+
/** Reporting boundary: every string that leaves the tool goes through redactText. Internal comparison
|
|
5
|
+
* has already happened on the original values. */
|
|
6
|
+
export function redactReport(report) {
|
|
7
|
+
const walk = (v) => {
|
|
8
|
+
if (typeof v === 'string')
|
|
9
|
+
return redactText(v);
|
|
10
|
+
if (Array.isArray(v))
|
|
11
|
+
return v.map(walk);
|
|
12
|
+
if (v && typeof v === 'object') {
|
|
13
|
+
const out = {};
|
|
14
|
+
for (const [k, val] of Object.entries(v))
|
|
15
|
+
out[k] = walk(val);
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
return v;
|
|
19
|
+
};
|
|
20
|
+
return walk(report);
|
|
21
|
+
}
|
|
22
|
+
export function renderJson(input) {
|
|
23
|
+
return JSON.stringify(redactReport(input), null, 2) + '\n';
|
|
24
|
+
}
|
|
25
|
+
function fmtInt(n) {
|
|
26
|
+
return n.toLocaleString('en-US');
|
|
27
|
+
}
|
|
28
|
+
function source(label, s) {
|
|
29
|
+
if (s.kind === 'url') {
|
|
30
|
+
const parts = [`HTTP ${s.status ?? '?'}`, s.contentType ?? 'no content-type', `Accept: ${s.accept ?? '?'}`, `${s.redirects ?? 0} redirect(s)`, `${fmtInt(s.bytes)} bytes`];
|
|
31
|
+
return `${label} ${s.url ?? '?'} (${parts.join(', ')})`;
|
|
32
|
+
}
|
|
33
|
+
return `${label} ${s.file ?? '?'} (file, ${fmtInt(s.bytes)} bytes${s.baseUrl ? `, base ${s.baseUrl}` : ''})`;
|
|
34
|
+
}
|
|
35
|
+
function findingLines(i, f) {
|
|
36
|
+
const lines = [`${String(i).padStart(3)}. [${f.severity}] ${f.code}: ${f.message}`];
|
|
37
|
+
if (f.html) {
|
|
38
|
+
const loc = [f.html.line !== undefined ? `line ${f.html.line}` : null, f.html.path ?? null, f.html.blockIndex !== undefined ? `block #${f.html.blockIndex}` : null].filter(Boolean).join(', ');
|
|
39
|
+
lines.push(` HTML ${loc}${f.html.excerpt !== undefined ? ` "${f.html.excerpt}"` : ''}`);
|
|
40
|
+
}
|
|
41
|
+
if (f.markdown) {
|
|
42
|
+
const loc = [f.markdown.line !== undefined ? `line ${f.markdown.line}` : null, f.markdown.blockIndex !== undefined ? `block #${f.markdown.blockIndex}` : null].filter(Boolean).join(', ');
|
|
43
|
+
lines.push(` Markdown ${loc}${f.markdown.excerpt !== undefined ? ` "${f.markdown.excerpt}"` : ''}`);
|
|
44
|
+
}
|
|
45
|
+
if (f.before !== undefined || f.after !== undefined) {
|
|
46
|
+
lines.push(` before: ${f.before ?? '(none)'}`);
|
|
47
|
+
lines.push(` after: ${f.after ?? '(none)'}`);
|
|
48
|
+
}
|
|
49
|
+
return lines;
|
|
50
|
+
}
|
|
51
|
+
export function renderText(input) {
|
|
52
|
+
const report = redactReport(input);
|
|
53
|
+
const out = [];
|
|
54
|
+
const s = report.summary;
|
|
55
|
+
out.push(`${TOOL_NAME} ${report.toolVersion} (${report.mode} mode${s.strict ? ', strict' : ''})`);
|
|
56
|
+
if (s.result === 'error') {
|
|
57
|
+
out.push(`Result: ERROR. ${s.error ?? 'The comparison could not be completed.'}`);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
out.push(`Result: ${s.result.toUpperCase()} (${s.errors} error(s), ${s.warnings} warning(s), ${s.infos} info)`);
|
|
61
|
+
}
|
|
62
|
+
out.push('');
|
|
63
|
+
out.push(source('HTML: ', report.sources.html));
|
|
64
|
+
out.push(source('Markdown:', report.sources.markdown));
|
|
65
|
+
if (report.extraction) {
|
|
66
|
+
const e = report.extraction;
|
|
67
|
+
out.push(`Extraction: HTML via ${e.html.strategy} (${e.html.confidence} confidence), ${e.html.blockCount} block(s); Markdown ${e.markdown.blockCount} block(s).`);
|
|
68
|
+
for (const n of [...e.html.notes, ...e.markdown.notes])
|
|
69
|
+
out.push(` note: ${n}`);
|
|
70
|
+
}
|
|
71
|
+
if (s.coverage) {
|
|
72
|
+
const c = s.coverage;
|
|
73
|
+
out.push(`Coverage: ${c.htmlMatched}/${c.htmlBlocks} HTML block(s) aligned (${(c.htmlRatio * 100).toFixed(0)} %), ${c.markdownMatched}/${c.markdownBlocks} Markdown block(s) aligned (${(c.markdownRatio * 100).toFixed(0)} %).`);
|
|
74
|
+
}
|
|
75
|
+
out.push('');
|
|
76
|
+
if (report.findings.length === 0) {
|
|
77
|
+
out.push(s.result === 'error' ? 'No findings (comparison not completed).' : 'No findings.');
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
out.push(`Findings (${report.findings.length}):`);
|
|
81
|
+
report.findings.forEach((f, i) => out.push(...findingLines(i + 1, f)));
|
|
82
|
+
}
|
|
83
|
+
out.push('');
|
|
84
|
+
out.push('Limitations:');
|
|
85
|
+
for (const l of report.limitations)
|
|
86
|
+
out.push(` - ${l}`);
|
|
87
|
+
return out.join('\n') + '\n';
|
|
88
|
+
}
|
package/dist/src/run.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Orchestration: takes resolved inputs (already fetched or read), runs extraction and comparison, and
|
|
2
|
+
// builds the report object. No argument parsing and no I/O here.
|
|
3
|
+
import { compare } from './compare.js';
|
|
4
|
+
import { extractHtml, HtmlExtractError } from './html.js';
|
|
5
|
+
import { extractMarkdown } from './markdown.js';
|
|
6
|
+
import { maskUrl } from './normalize.js';
|
|
7
|
+
import { TOOL_VERSION } from './version.js';
|
|
8
|
+
export class RunError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'RunError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export const LIMITATIONS = [
|
|
15
|
+
'Exit 0 means no rejecting difference was found in the extracted blocks; it does not prove semantic equivalence or factual correctness.',
|
|
16
|
+
'JavaScript is not executed. Content that a page renders client-side is compared as served.',
|
|
17
|
+
'Only the main content is compared. Page chrome (navigation, banners, footers directly under body) is removed from the HTML on purpose.',
|
|
18
|
+
'Findings are quantitative: a missing paragraph is reported as missing, not interpreted.',
|
|
19
|
+
];
|
|
20
|
+
function meta(e) {
|
|
21
|
+
return { strategy: e.strategy, confidence: e.confidence, blockCount: e.blocks.length, notes: e.notes };
|
|
22
|
+
}
|
|
23
|
+
/** Findings about how the Markdown was delivered, produced by the URL mode before extraction. */
|
|
24
|
+
export function deliveryFindings(md, body) {
|
|
25
|
+
const out = [];
|
|
26
|
+
if (md.kind !== 'url')
|
|
27
|
+
return out;
|
|
28
|
+
const ct = (md.contentType ?? '').toLowerCase();
|
|
29
|
+
const type = ct.split(';')[0].trim();
|
|
30
|
+
const looksHtml = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(body);
|
|
31
|
+
if (md.status !== undefined && md.status >= 400) {
|
|
32
|
+
out.push({ code: 'DELIVERY_HTTP_ERROR', severity: 'error', direction: 'markdown_only', message: `The Markdown request returned HTTP ${md.status}; the error page is not treated as content.`, before: String(md.status) });
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
if (type === 'text/html' || type === 'application/xhtml+xml' || looksHtml) {
|
|
36
|
+
out.push({ code: 'DELIVERY_MARKDOWN_IS_HTML', severity: 'error', direction: 'markdown_only', message: `The request with Accept: text/markdown returned HTML (Content-Type ${md.contentType ?? 'missing'}); the site does not deliver a Markdown representation at this address.`, before: md.contentType ?? '' });
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
if (type === 'text/markdown' || type === 'text/x-markdown')
|
|
40
|
+
return out;
|
|
41
|
+
if (type === 'text/plain') {
|
|
42
|
+
out.push({ code: 'DELIVERY_CONTENT_TYPE_PLAIN', severity: 'warning', direction: 'markdown_only', message: 'The Markdown response is labelled text/plain rather than text/markdown.', before: md.contentType ?? '' });
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
out.push({ code: 'DELIVERY_UNEXPECTED_CONTENT_TYPE', severity: 'error', direction: 'markdown_only', message: `The Markdown response has an unexpected Content-Type (${md.contentType ?? 'missing'}).`, before: md.contentType ?? '' });
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function count(findings) {
|
|
49
|
+
let errors = 0;
|
|
50
|
+
let warnings = 0;
|
|
51
|
+
let infos = 0;
|
|
52
|
+
for (const f of findings) {
|
|
53
|
+
if (f.severity === 'error')
|
|
54
|
+
errors++;
|
|
55
|
+
else if (f.severity === 'warning')
|
|
56
|
+
warnings++;
|
|
57
|
+
else
|
|
58
|
+
infos++;
|
|
59
|
+
}
|
|
60
|
+
return { errors, warnings, infos };
|
|
61
|
+
}
|
|
62
|
+
function baseReport(options, html, markdown) {
|
|
63
|
+
return {
|
|
64
|
+
schemaVersion: 1,
|
|
65
|
+
toolVersion: TOOL_VERSION,
|
|
66
|
+
generatedAt: new Date().toISOString(),
|
|
67
|
+
mode: options.mode,
|
|
68
|
+
sources: { html, markdown },
|
|
69
|
+
extraction: null,
|
|
70
|
+
summary: { result: 'error', strict: options.strict, errors: 0, warnings: 0, infos: 0, coverage: null, exitCode: 2 },
|
|
71
|
+
findings: [],
|
|
72
|
+
limitations: LIMITATIONS,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export function run(html, markdown, options) {
|
|
76
|
+
const report = baseReport(options, html.meta, markdown.meta);
|
|
77
|
+
const delivery = deliveryFindings(markdown.meta, markdown.body);
|
|
78
|
+
if (delivery.some((f) => f.severity === 'error')) {
|
|
79
|
+
report.findings = delivery;
|
|
80
|
+
const c = count(delivery);
|
|
81
|
+
report.summary = { ...report.summary, ...c, result: 'fail', exitCode: 1 };
|
|
82
|
+
return report;
|
|
83
|
+
}
|
|
84
|
+
let h;
|
|
85
|
+
try {
|
|
86
|
+
h = extractHtml(html.body, { selector: options.selector, baseUrl: html.base });
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err instanceof HtmlExtractError)
|
|
90
|
+
throw new RunError(err.message);
|
|
91
|
+
throw err;
|
|
92
|
+
}
|
|
93
|
+
const m = extractMarkdown(markdown.body, { baseUrl: markdown.base, frontMatter: options.frontMatter ?? 'keep' });
|
|
94
|
+
report.extraction = { html: meta(h), markdown: meta(m) };
|
|
95
|
+
if (h.blocks.length === 0)
|
|
96
|
+
throw new RunError(`HTML main content is empty (strategy ${h.strategy}); nothing to compare.`);
|
|
97
|
+
if (m.blocks.length === 0)
|
|
98
|
+
throw new RunError('Markdown content is empty; nothing to compare.');
|
|
99
|
+
const result = compare(h, m, { bothBases: html.base !== null && markdown.base !== null });
|
|
100
|
+
const findings = [...delivery, ...result.findings];
|
|
101
|
+
const c = count(findings);
|
|
102
|
+
const failing = c.errors > 0 || (options.strict && c.warnings > 0);
|
|
103
|
+
report.findings = findings;
|
|
104
|
+
report.summary = { result: failing ? 'fail' : 'pass', strict: options.strict, ...c, coverage: result.coverage, exitCode: failing ? 1 : 0 };
|
|
105
|
+
return report;
|
|
106
|
+
}
|
|
107
|
+
export function errorReport(options, html, markdown, message) {
|
|
108
|
+
const empty = { kind: options.mode === 'url' ? 'url' : 'file', bytes: 0 };
|
|
109
|
+
const r = baseReport(options, html ?? empty, markdown ?? empty);
|
|
110
|
+
r.summary.error = message;
|
|
111
|
+
return r;
|
|
112
|
+
}
|
|
113
|
+
export { maskUrl };
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "markdown-parity-check",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Compares the main content of a web page's HTML and Markdown representations and reports concrete differences.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"markdown",
|
|
7
|
+
"html",
|
|
8
|
+
"parity",
|
|
9
|
+
"content-negotiation",
|
|
10
|
+
"llms-txt",
|
|
11
|
+
"cli"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Erik Rekola",
|
|
15
|
+
"homepage": "https://github.com/erekola/markdown-parity-check#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/erekola/markdown-parity-check.git"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/erekola/markdown-parity-check/issues"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22.0.0"
|
|
26
|
+
},
|
|
27
|
+
"bin": {
|
|
28
|
+
"markdown-parity-check": "./dist/src/cli.js"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist/src/",
|
|
32
|
+
"SECURITY.md"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "node node_modules/typescript/bin/tsc -p tsconfig.json",
|
|
36
|
+
"typecheck": "node node_modules/typescript/bin/tsc -p tsconfig.json --noEmit",
|
|
37
|
+
"test": "npm run build && node --test \"dist/test/**/*.test.js\"",
|
|
38
|
+
"check": "node dist/src/cli.js",
|
|
39
|
+
"prepack": "npm run build"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"css-select": "^7.0.0",
|
|
43
|
+
"domhandler": "^6.0.1",
|
|
44
|
+
"domutils": "^3.2.2",
|
|
45
|
+
"htmlparser2": "^12.0.0",
|
|
46
|
+
"mdast-util-from-markdown": "^2.0.2",
|
|
47
|
+
"mdast-util-gfm": "^3.1.0",
|
|
48
|
+
"micromark-extension-gfm": "^3.0.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/mdast": "^4.0.4",
|
|
52
|
+
"@types/node": "^22.0.0",
|
|
53
|
+
"typescript": "^5.9.0"
|
|
54
|
+
}
|
|
55
|
+
}
|