markdown-parity-check 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -56,7 +56,7 @@ The comparison covers headings, paragraphs, lists, tables, code and links. It de
56
56
 
57
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
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.
59
+ URL fetching blocks non-public network targets and checks redirects. Request deadlines and response size limits bound network work. The comparison itself is bounded too: the product of the HTML and Markdown block counts may not exceed 4 000 000, which is 2 000 blocks on each side. Above that the tool exits with code 2 and an error instead of allocating memory without limit. Reports mask URL query values, but content excerpts may still contain private information. Review reports before sharing them.
60
60
 
61
61
  ## Run from source
62
62
 
@@ -72,7 +72,7 @@ The bundled example compares matching content. It explicitly removes the Markdow
72
72
 
73
73
  ## Development
74
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.
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 packs the tarball once, publishes it to npm when the version is not there yet, downloads the registry copy and checks its integrity hash and its content against the packed file. Only then does it create the GitHub release with that verified tarball attached. A version that exists on npm with different content stops the release.
76
76
 
77
77
  ## Security
78
78
 
package/SECURITY.md CHANGED
@@ -14,10 +14,12 @@ Please do not open a public issue for security reports. You can expect an initia
14
14
 
15
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
16
 
17
+ The comparison work is bounded by the product of the two block counts, at most 4 000 000 block pairs. The number of similar block pairs kept for matching is bounded as well. Above either limit the tool stops with exit code 2 and an error message instead of reporting a pass for a comparison it did not complete.
18
+
17
19
  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
20
 
19
21
  ## Dependencies and releases
20
22
 
21
23
  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
24
 
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.
25
+ The package is published on npm as `markdown-parity-check`. Each version has a matching GitHub release. The attached tarball is the registry copy after its integrity hash and content were checked against the freshly packed file. 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.
package/dist/src/align.js CHANGED
@@ -17,33 +17,59 @@ function looseKey(b) {
17
17
  }
18
18
  export const SIMILARITY_THRESHOLD = 0.6;
19
19
  export const UNCERTAIN_THRESHOLD = 0.8;
20
+ /** Upper bound on the alignment work, as the product of the HTML and Markdown block counts. The LCS
21
+ * table holds (n+1)*(m+1) Uint32 cells, 16 MiB at the limit (2 000 by 2 000 blocks), and the similarity
22
+ * search visits at most n*m block pairs. Above the limit the comparison stops with an error before any
23
+ * table is allocated, instead of growing without bound with the page size. */
24
+ export const MAX_ALIGNMENT_PAIRS = 4_000_000;
25
+ /** Upper bound on the similarity candidates kept for the greedy best-match pass. Only pairs at or above
26
+ * SIMILARITY_THRESHOLD are kept, so this is reached only when a large share of the free blocks on both
27
+ * sides resemble each other. */
28
+ export const MAX_SIMILARITY_CANDIDATES = 1_000_000;
29
+ /** Thrown when the comparison would exceed a documented resource limit. The caller reports it as an
30
+ * error result (exit 2), never as a pass or a silently truncated comparison. */
31
+ export class AlignmentLimitError extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = 'AlignmentLimitError';
35
+ }
36
+ }
20
37
  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;
38
+ const counts = new Map();
39
+ let total = 0;
40
+ for (const t of s.split(' ')) {
41
+ if (!t)
42
+ continue;
43
+ counts.set(t, (counts.get(t) ?? 0) + 1);
44
+ total++;
45
+ }
46
+ return { counts, total };
47
+ }
48
+ function dice(ta, tb) {
49
+ if (ta.total === 0 || tb.total === 0)
50
+ return 0;
51
+ let inter = 0;
52
+ for (const [t, c] of ta.counts)
53
+ inter += Math.min(c, tb.counts.get(t) ?? 0);
54
+ return (2 * inter) / (ta.total + tb.total);
26
55
  }
27
56
  /** Dice coefficient over word tokens of the loose text. */
28
57
  export function similarity(a, b) {
29
58
  if (a.loose === '' || b.loose === '')
30
59
  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);
60
+ return dice(tokens(a.loose), tokens(b.loose));
61
+ }
62
+ /** Checks the block counts against MAX_ALIGNMENT_PAIRS before any work is done. */
63
+ export function checkAlignmentLimit(htmlBlocks, markdownBlocks) {
64
+ const pairs = htmlBlocks * markdownBlocks;
65
+ if (pairs > MAX_ALIGNMENT_PAIRS) {
66
+ throw new AlignmentLimitError(`Comparison limit exceeded: ${htmlBlocks} HTML blocks by ${markdownBlocks} Markdown blocks is ${pairs} block pairs, above the limit of ${MAX_ALIGNMENT_PAIRS}. Narrow the HTML content with --selector or compare a smaller page.`);
67
+ }
43
68
  }
44
69
  function lcs(keysA, keysB) {
45
70
  const n = keysA.length;
46
71
  const m = keysB.length;
72
+ checkAlignmentLimit(n, m);
47
73
  const dp = [];
48
74
  for (let i = 0; i <= n; i++)
49
75
  dp.push(new Uint32Array(m + 1));
@@ -71,6 +97,7 @@ function lcs(keysA, keysB) {
71
97
  return out;
72
98
  }
73
99
  export function align(a, b) {
100
+ checkAlignmentLimit(a.length, b.length);
74
101
  const pairs = [];
75
102
  const usedA = new Set();
76
103
  const usedB = new Set();
@@ -124,19 +151,38 @@ export function align(a, b) {
124
151
  }
125
152
  }
126
153
  // Similar pairs: greedy best-match by similarity above the threshold, same type only. Ties are broken
127
- // by document order to keep results deterministic.
154
+ // by document order to keep results deterministic. Token counts are computed once per block, and the
155
+ // candidate list is bounded by MAX_SIMILARITY_CANDIDATES.
156
+ const freeA = [];
157
+ const freeBs = [];
158
+ for (let i = 0; i < a.length; i++)
159
+ if (!usedA.has(i))
160
+ freeA.push(i);
161
+ for (let j = 0; j < b.length; j++)
162
+ if (!usedB.has(j))
163
+ freeBs.push(j);
164
+ const tokensA = new Map();
165
+ const tokensB = new Map();
166
+ for (const i of freeA)
167
+ tokensA.set(i, tokens(a[i].loose));
168
+ for (const j of freeBs)
169
+ tokensB.set(j, tokens(b[j].loose));
128
170
  const candidates = [];
129
- for (let i = 0; i < a.length; i++) {
130
- if (usedA.has(i))
171
+ for (const i of freeA) {
172
+ const ta = tokensA.get(i);
173
+ if (ta.total === 0)
131
174
  continue;
132
- for (let j = 0; j < b.length; j++) {
133
- if (usedB.has(j))
175
+ const ga = typeGroup(a[i]);
176
+ for (const j of freeBs) {
177
+ if (typeGroup(b[j]) !== ga)
134
178
  continue;
135
- if (typeGroup(a[i]) !== typeGroup(b[j]))
179
+ const s = dice(ta, tokensB.get(j));
180
+ if (s < SIMILARITY_THRESHOLD)
136
181
  continue;
137
- const s = similarity(a[i], b[j]);
138
- if (s >= SIMILARITY_THRESHOLD)
139
- candidates.push({ i, j, s });
182
+ if (candidates.length >= MAX_SIMILARITY_CANDIDATES) {
183
+ throw new AlignmentLimitError(`Comparison limit exceeded: more than ${MAX_SIMILARITY_CANDIDATES} similar block pairs among ${freeA.length} unmatched HTML blocks and ${freeBs.length} unmatched Markdown blocks. Narrow the HTML content with --selector or compare a smaller page.`);
184
+ }
185
+ candidates.push({ i, j, s });
140
186
  }
141
187
  }
142
188
  candidates.sort((x, y) => y.s - x.s || x.i - y.i || x.j - y.j);
@@ -4,7 +4,7 @@ import { gfm } from 'micromark-extension-gfm';
4
4
  import { gfmFromMarkdown } from 'mdast-util-gfm';
5
5
  import { extractHtml } from './html.js';
6
6
  import { parseDocument } from 'htmlparser2';
7
- import { Element } from 'domhandler';
7
+ import { Element, Text } from 'domhandler';
8
8
  import { excerpt, extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
9
9
  /** Parses one inline HTML node (a single tag, per micromark) with htmlparser2. Returns null for comments,
10
10
  * processing instructions or anything that is not exactly one tag. */
@@ -229,14 +229,13 @@ function handle(ctx, node, listItem = false) {
229
229
  /** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
230
230
  * comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
231
231
  function handleRawHtml(ctx, value, line) {
232
- const withoutComments = value.replace(/<!--[\s\S]*?-->/g, '');
233
- // Text check for the fallback warning: script, style, template and noscript are page machinery on both
234
- // sides, so their content does not count as skipped text.
235
- const visibleSource = withoutComments.replace(/<(script|style|template|noscript)\b[\s\S]*?<\/\1\s*>/gi, ' ');
236
- const textOnly = strictNormalize(visibleSource.replace(/<[^>]*>/g, ' '));
232
+ // Text check for the fallback warning, taken from the parsed DOM rather than from regex stripping:
233
+ // comments are not text, and script, style, template and noscript are page machinery on both sides,
234
+ // so their content does not count as skipped text.
235
+ const textOnly = visibleText(value);
237
236
  let parsed = null;
238
237
  try {
239
- parsed = extractHtml(`<body>${withoutComments}</body>`, { selector: 'body', baseUrl: ctx.base });
238
+ parsed = extractHtml(`<body>${value}</body>`, { selector: 'body', baseUrl: ctx.base });
240
239
  }
241
240
  catch {
242
241
  parsed = null;
@@ -256,6 +255,25 @@ function handleRawHtml(ctx, value, line) {
256
255
  ctx.issues.push({ code: 'MARKDOWN_RAW_HTML_SKIPPED', severity: 'warning', message: 'A raw HTML block in the Markdown carries text that could not be parsed into blocks; it was not compared.', line, excerpt: excerpt(textOnly) });
257
256
  }
258
257
  }
258
+ const MACHINERY = new Set(['script', 'style', 'template', 'noscript']);
259
+ /** Strictly normalized text of an HTML fragment as a parser sees it: text nodes only, comments and
260
+ * machinery elements excluded. */
261
+ function visibleText(fragment) {
262
+ const parts = [];
263
+ const walk = (nodes) => {
264
+ for (const node of nodes) {
265
+ if (node instanceof Text)
266
+ parts.push(node.data);
267
+ else if (node instanceof Element) {
268
+ if (MACHINERY.has(node.name.toLowerCase()))
269
+ continue;
270
+ walk(node.children);
271
+ }
272
+ }
273
+ };
274
+ walk(parseDocument(fragment).children);
275
+ return strictNormalize(parts.join(' '));
276
+ }
259
277
  const YAML_LINE = /^(?:[A-Za-z0-9_.-]+\s*:(?:\s|$)|\s+\S|-\s|#)/;
260
278
  const FENCE_RE = /^(?:\ufeff)?---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;
261
279
  /**
package/dist/src/run.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Orchestration: takes resolved inputs (already fetched or read), runs extraction and comparison, and
2
2
  // builds the report object. No argument parsing and no I/O here.
3
+ import { AlignmentLimitError } from './align.js';
3
4
  import { compare } from './compare.js';
4
5
  import { extractHtml, HtmlExtractError } from './html.js';
5
6
  import { extractMarkdown } from './markdown.js';
@@ -96,7 +97,15 @@ export function run(html, markdown, options) {
96
97
  throw new RunError(`HTML main content is empty (strategy ${h.strategy}); nothing to compare.`);
97
98
  if (m.blocks.length === 0)
98
99
  throw new RunError('Markdown content is empty; nothing to compare.');
99
- const result = compare(h, m, { bothBases: html.base !== null && markdown.base !== null });
100
+ let result;
101
+ try {
102
+ result = compare(h, m, { bothBases: html.base !== null && markdown.base !== null });
103
+ }
104
+ catch (err) {
105
+ if (err instanceof AlignmentLimitError)
106
+ throw new RunError(err.message);
107
+ throw err;
108
+ }
100
109
  const findings = [...delivery, ...result.findings];
101
110
  const c = count(findings);
102
111
  const failing = c.errors > 0 || (options.strict && c.warnings > 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-parity-check",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Compares the main content of a web page's HTML and Markdown representations and reports concrete differences.",
5
5
  "keywords": [
6
6
  "markdown",