markdown-parity-check 0.2.20 → 0.2.22

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
@@ -64,11 +64,11 @@ A value that is outside these ranges, or that is not a plain run of digits, stop
64
64
 
65
65
  ## What is compared
66
66
 
67
- Without `--selector`, the HTML content comes from the first visible `main`, `article` or `[role=main]`. If none of them exists, the page body is used and the report warns that page chrome may leak in. Two visible elements of the same kind that do not contain one another also give a warning, because only the first is compared. Front matter is kept by default and compared as content. If the HTML does not carry the same text, that alone fails the comparison. The tool also warns when the Markdown starts with a block that looks like YAML front matter, and `--front-matter strip` removes it.
67
+ Without `--selector`, the HTML content comes from the first visible `main`, `article` or `[role=main]`. A candidate is visible when neither it nor an ancestor is hidden, in a template or inside one of the left-out subtrees listed below, so an `article` inside a `nav` is not used. A `form` is the one exception, so a `main` inside a `form` that has no left-out role is still used, however far up the form sits. If none of them exists, the page body is used and the report warns that page chrome may leak in. Two visible elements of the same kind that do not contain one another also give a warning, because only the first is compared. Front matter is kept by default and compared as content. If the HTML does not carry the same text, that alone fails the comparison. The tool also warns when the Markdown starts with a block that looks like YAML front matter, and `--front-matter strip` removes it.
68
68
 
69
- Headings, paragraphs, list items, tables, code blocks and links are compared block by block. Content marked `hidden` or `aria-hidden` is left out on both sides, and a table caption counts as a paragraph before the table. Missing and added blocks are errors. A change in text or numbers is an error too, as is a changed table or link, and a list item that shows another number or task state. A difference in order, heading level, case, punctuation, list kind or nesting level is a warning. Footnotes in the Markdown are not compared. Each one is reported as a warning, and repeated blocks are reported too. The cell-by-cell comparison of a table is skipped when one of its cells has a rowspan or colspan above 1, a rowspan of 0, or a value that is empty or does not begin with a number; the number is read from the value's leading digits, so `2abc` counts as 2. A colspan of 0 and a rowspan or colspan of 1 do not trigger it. The links and the caption of such a table are still compared. The numbering of a reversed list is not compared either. Each skip is reported as an information finding, which does not fail a check, not even with `--strict`.
69
+ Headings, paragraphs, list items, tables, code blocks and links are compared block by block. Content marked `hidden` or `aria-hidden` is left out on both sides, also when a raw HTML wrapper such as `<div hidden>` is opened in one Markdown block and closed in a later one, and a table caption counts as a paragraph before the table. Missing and added blocks are errors. A change in text or numbers is an error too, as is a changed table or link, and a list item that shows another number or a different checked or unchecked state. A checkbox that is present on one side only is a warning, and so is a difference in order, which is also reported for a block that moved and was edited slightly, and a difference in heading level, case, punctuation, list kind or nesting level. Footnotes in the Markdown are not compared. Each one is reported as a warning, and repeated blocks are reported too. The cell-by-cell comparison of a table is skipped when one of its cells has a rowspan or colspan above 1, a rowspan of 0, or a value that is empty or does not begin with a number. The number is read from the value's leading digits, so `2abc` counts as 2. A colspan of 0 and a rowspan or colspan of 1 do not trigger it. The links and the caption of such a table are still compared. The numbering of a reversed list is not compared either. Each skip is reported as an information finding, which does not fail a check, not even with `--strict`.
70
70
 
71
- Some content is left out even when it sits inside the main content: the subtrees of `form`, `button`, `input`, `select`, `textarea`, `dialog`, `iframe`, `svg`, `canvas`, `object`, `embed` and `map`, of `nav`, `script`, `style`, `noscript` and `template`, and of any element with the role `navigation`, `banner`, `contentinfo`, `complementary`, `search`, `menu`, `menubar` or `dialog`. The `starlight` profile keeps an iframe that has a source and a title, as a link. An image is compared by its alt text only, not by its address, so two different images with the same alt text compare equal.
71
+ Some content is left out even when it sits inside the main content, in code blocks too: the subtrees of `form`, `button`, `input`, `select`, `textarea`, `dialog`, `iframe`, `svg`, `canvas`, `object`, `embed` and `map`, of `nav`, `script`, `style`, `noscript` and `template`, and of any element with the role `navigation`, `banner`, `contentinfo`, `complementary`, `search`, `menu`, `menubar` or `dialog`. The `starlight` profile keeps an iframe that has a source and a title, as a link. The same list applies to inline raw HTML in the Markdown and to the checkbox of a task list item, which must belong to the item itself. A left-out tag in a Markdown paragraph, such as a `<button>` or a `<script>`, is skipped through its matching closing tag in the same paragraph, and one with no closing tag is reported as a warning and its text is compared as visible. Only a self-closing `<svg/>` counts as closed by itself, as in HTML. A `<br>` in a code block is a line break. A code block that differs only in whitespace is a warning, where whitespace means the ASCII whitespace characters and the Unicode space separators such as the no-break space. Any other difference in code, an invisible character such as a soft hyphen included, is an error. An image is compared by its alt text only, not by its address, so two different images with the same alt text compare equal.
72
72
 
73
73
  In URL mode the Markdown response is checked first. An HTTP error or an HTML page in place of Markdown fails the check, and nothing is compared.
74
74
 
@@ -88,7 +88,7 @@ Both use the comparison core of this package. They differ in which pages they re
88
88
 
89
89
  The hosted page also answers a JSON POST, described on the page. It runs the release of this package pinned in [turva-worker](https://github.com/erekola/turva-worker), which can be older than the latest npm release. The report's `toolVersion` field shows which release produced it.
90
90
 
91
- Some limits are not in the table. A URL that contains a user name or password is refused even when its host is public, and the same holds for a redirect target. The tool sends `Accept-Encoding: gzip, deflate, br` and decodes responses with no Content-Encoding, `identity`, `gzip`, `x-gzip`, `deflate` or `br`. A response with any other Content-Encoding, `zstd` for example, is rejected, and the run ends with exit code 2. The command-line tool follows at most 5 redirects. The extraction stops with exit code 2 when elements are nested more than 1024 levels deep, and the matching stops the same way when more than 1 000 000 similar block pairs would have to be considered; the library `limits` default to the same values.
91
+ Some limits are not in the table. A URL that contains a user name or password is refused even when its host is public, and the same holds for a redirect target. The tool sends `Accept-Encoding: gzip, deflate, br` and decodes responses with no Content-Encoding, `identity`, `gzip`, `x-gzip`, `deflate` or `br`. A response with any other Content-Encoding, `zstd` for example, is rejected, and the run ends with exit code 2. The command-line tool follows at most 5 redirects. When elements are nested more than 1024 levels deep, in the HTML page or in a raw HTML block written inside the Markdown, the extraction stops with exit code 2. The matching stops the same way when more than 1 000 000 similar block pairs would have to be considered, and the library `limits` default to the same two values.
92
92
 
93
93
  A hosted check can fail on turva.dev's own pages as well. On 2026-09-11 the check of https://turva.dev/tools returned `fail` with five errors. The Markdown carries a Related heading and four links that the HTML page does not repeat as a list, and the report listed each of them. The same four targets are links inside that page's tool cards, so the report found a missing structure and not missing content. [HTML and Markdown can disagree](https://turva.dev/blog/html-and-markdown-can-disagree) reads that result in full.
94
94
 
@@ -114,7 +114,7 @@ console.log(renderJson(report));
114
114
 
115
115
  `run(html, markdown, options)` returns the report object that `--format json` prints. A completed run has the result `pass` with exit code 0 or `fail` with exit code 1. When the comparison cannot finish, for example because the content is empty or a limit is exceeded, `run` throws a `RunError`. `errorReport` builds the error report the command prints in that case.
116
116
 
117
- The options are `selector`, `frontMatter`, `strict` and `mode`. The report records `mode` as `url` or `offline`, and it does not switch any check on or off. When the Markdown source has `kind: 'url'` in its `meta`, the delivery check runs first and reads the HTTP `status` and `contentType` from that `meta`. A host with a smaller CPU or memory budget can pass lower `limits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The caller fetches the pages and decides which addresses are allowed. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
117
+ The options are `selector`, `frontMatter`, `htmlProfile` (`generic` or `starlight`, see docs/starlight.md), `strict` and `mode`. The report records `mode` as `url` or `offline`, and it does not switch any check on or off. When the Markdown source has `kind: 'url'` in its `meta`, the delivery check runs first and reads the HTTP `status` and `contentType` from that `meta`. A host with a smaller CPU or memory budget can pass lower `limits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The nesting limit also applies to raw HTML blocks inside the Markdown. The caller fetches the pages and decides which addresses are allowed. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
118
118
 
119
119
  ## Run from source
120
120
 
package/SECURITY.md CHANGED
@@ -8,13 +8,13 @@ Security fixes target the latest published release. Update to that release when
8
8
 
9
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
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.
11
+ Please do not open a public issue for security reports. You can expect an initial response within one business day. Confirmed issues will be prioritized and you will be kept informed of progress.
12
12
 
13
13
  ## Network and file access
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.
17
+ The work of pairing blocks 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. The pairing of links inside one block is not separately bounded by default: with the default limits it has no budget of its own, and a block with thousands of links that cannot be resolved against a base URL can take time that grows with the square of the link count. A library caller can set the maxSimilarityWork limit to stop it.
18
18
 
19
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 and fragments and remove any user name or password from a URL. Excerpts may contain private page content. Review reports before sharing them.
20
20
 
@@ -4,6 +4,8 @@ export interface Pair {
4
4
  b: number;
5
5
  kind: 'exact' | 'moved' | 'loose' | 'similar';
6
6
  similarity: number;
7
+ /** Set on a loose pair whose order disagrees with the exact and loose pairs around it (0.2.22). */
8
+ reordered?: boolean;
7
9
  }
8
10
  export interface Alignment {
9
11
  pairs: Pair[];
package/dist/src/align.js CHANGED
@@ -114,6 +114,56 @@ function lcs(keysA, keysB, maxPairs) {
114
114
  }
115
115
  return out;
116
116
  }
117
+ /**
118
+ * Flags loose pairs that sit out of order. An exact pair that is out of order is already 'moved', but a block that
119
+ * was moved and edited is paired by its loose key and kept its kind, so the reversal went unreported (0.2.22, found
120
+ * by an outside review 2026-10-02). The exact and loose pairs, in HTML order, form a sequence of Markdown positions;
121
+ * the heaviest increasing run of it is the order the page keeps, with an exact pair weighing more than all loose
122
+ * pairs together so that no exact pair is ever the one dropped. A loose pair outside the run is flagged. One pass
123
+ * with a Fenwick tree over the Markdown positions, O(n log n).
124
+ */
125
+ function markReorderedLoose(pairs, markdownBlocks) {
126
+ const chain = pairs.filter((p) => p.kind === 'exact' || p.kind === 'loose');
127
+ const looseCount = chain.reduce((n, p) => n + (p.kind === 'loose' ? 1 : 0), 0);
128
+ if (looseCount < 1 || chain.length < 2)
129
+ return;
130
+ const exactWeight = looseCount + 1;
131
+ const treeWeight = new Float64Array(markdownBlocks + 2);
132
+ const treeIndex = new Int32Array(markdownBlocks + 2).fill(-1);
133
+ const total = new Float64Array(chain.length);
134
+ const previous = new Int32Array(chain.length).fill(-1);
135
+ let bestEnd = -1;
136
+ let bestTotal = 0;
137
+ chain.forEach((p, k) => {
138
+ let w = 0;
139
+ let from = -1;
140
+ for (let x = p.b; x > 0; x -= x & -x) {
141
+ if (treeWeight[x] > w) {
142
+ w = treeWeight[x];
143
+ from = treeIndex[x];
144
+ }
145
+ }
146
+ total[k] = w + (p.kind === 'exact' ? exactWeight : 1);
147
+ previous[k] = from;
148
+ for (let x = p.b + 1; x <= markdownBlocks + 1; x += x & -x) {
149
+ if (total[k] > treeWeight[x]) {
150
+ treeWeight[x] = total[k];
151
+ treeIndex[x] = k;
152
+ }
153
+ }
154
+ if (total[k] > bestTotal) {
155
+ bestTotal = total[k];
156
+ bestEnd = k;
157
+ }
158
+ });
159
+ const kept = new Set();
160
+ for (let k = bestEnd; k >= 0; k = previous[k])
161
+ kept.add(k);
162
+ chain.forEach((p, k) => {
163
+ if (p.kind === 'loose' && !kept.has(k))
164
+ p.reordered = true;
165
+ });
166
+ }
117
167
  export function align(a, b, limits) {
118
168
  const lim = resolveLimits(limits);
119
169
  checkAlignmentLimit(a.length, b.length, lim.maxAlignmentPairs);
@@ -221,6 +271,7 @@ export function align(a, b, limits) {
221
271
  usedB.add(c.j);
222
272
  }
223
273
  pairs.sort((x, y) => x.a - y.a || x.b - y.b);
274
+ markReorderedLoose(pairs, b.length);
224
275
  const unmatchedA = [];
225
276
  const unmatchedB = [];
226
277
  for (let i = 0; i < a.length; i++)
package/dist/src/cli.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { type FetchOptions, type FetchResult } from './fetch.js';
3
- export declare const HELP = "markdown-parity-check 0.2.20\nCompares the main content of a web page's HTML and Markdown representations and reports concrete\nmissing, added and changed blocks.\n\nUsage:\n markdown-parity-check --url <https://example.com/page> [--markdown-url <url>] [options]\n markdown-parity-check --html-file <page.html> --markdown-file <page.md> [--base-url <url>] [options]\n\nModes:\n --url <url> Fetch <url> twice: with Accept: text/html and with Accept: text/markdown.\n --markdown-url <url> Fetch the Markdown from this explicit address instead (requires --url).\n --html-file <path> Offline: local HTML file (requires --markdown-file).\n --markdown-file <path> Offline: local Markdown file (requires --html-file).\n --base-url <url> Offline: base for resolving relative links on both sides.\n\nOptions:\n --html-profile generic|starlight\n HTML extraction rules (default: generic). Starlight includes inactive tab panels.\n --selector <css> CSS selector for the HTML main content (default: main, article, [role=main], then body).\n --front-matter keep|strip\n Markdown front matter. keep (default) removes nothing and warns when the document\n starts with a YAML-looking fenced block; strip removes that leading block.\n --format text|json Report format (default: text).\n --output <path> Write the report to a file instead of stdout. Refuses to overwrite an input file.\n --timeout-ms <n> Per-fetch timeout in milliseconds (default: 15000).\n --max-bytes <n> Cap on decoded response bytes per fetch (default: 5242880).\n --strict Treat warnings as rejecting findings too.\n --help, -h Show this help.\n --version, -V Show the version.\n\nExit codes:\n 0 comparison completed, no rejecting finding\n 1 comparison completed, rejecting content or delivery differences found\n 2 input, fetch, parse or report error prevented a reliable comparison\n\nOnly http(s) URLs to public addresses are fetched; loopback, private, link-local and other non-public\naddresses are refused, also behind DNS and redirects. No JavaScript is executed. Exit 0 does not prove\nsemantic equivalence.\n";
3
+ export declare const HELP = "markdown-parity-check 0.2.22\nCompares the main content of a web page's HTML and Markdown representations and reports concrete\nmissing, added and changed blocks.\n\nUsage:\n markdown-parity-check --url <https://example.com/page> [--markdown-url <url>] [options]\n markdown-parity-check --html-file <page.html> --markdown-file <page.md> [--base-url <url>] [options]\n\nModes:\n --url <url> Fetch <url> twice: with Accept: text/html and with Accept: text/markdown.\n --markdown-url <url> Fetch the Markdown from this explicit address instead (requires --url).\n --html-file <path> Offline: local HTML file (requires --markdown-file).\n --markdown-file <path> Offline: local Markdown file (requires --html-file).\n --base-url <url> Offline: base for resolving relative links on both sides.\n\nOptions:\n --html-profile generic|starlight\n HTML extraction rules (default: generic). Starlight includes inactive tab panels.\n --selector <css> CSS selector for the HTML main content (default: main, article, [role=main], then body).\n --front-matter keep|strip\n Markdown front matter. keep (default) removes nothing and warns when the document\n starts with a YAML-looking fenced block; strip removes that leading block.\n --format text|json Report format (default: text).\n --output <path> Write the report to a file instead of stdout. Refuses to overwrite an input file.\n --timeout-ms <n> Per-fetch timeout in milliseconds (default: 15000).\n --max-bytes <n> Cap on decoded response bytes per fetch (default: 5242880).\n --strict Treat warnings as rejecting findings too.\n --help, -h Show this help.\n --version, -V Show the version.\n\nExit codes:\n 0 comparison completed, no rejecting finding\n 1 comparison completed, rejecting content or delivery differences found\n 2 input, fetch, parse or report error prevented a reliable comparison\n\nOnly http(s) URLs to public addresses are fetched; loopback, private, link-local and other non-public\naddresses are refused, also behind DNS and redirects. No JavaScript is executed. Exit 0 does not prove\nsemantic equivalence.\n";
4
4
  export declare class CliError extends Error {
5
5
  }
6
6
  export interface CliArgs {
package/dist/src/cli.js CHANGED
@@ -74,6 +74,28 @@ function rawWantsJson(argv) {
74
74
  // error built from the value the caller gave would misreport what is actually going to happen
75
75
  // (P-N4, found by an outside review 2026-09-28).
76
76
  const MAX_TIMEOUT_MS = 2147483647;
77
+ /** A rejected option value as it may be echoed in an error. maskUrl handles anything the URL parser reads with a
78
+ * host. When the value holds an '@' and the parser finds no host (user:secret@example.com parses as an opaque URL,
79
+ * and some shapes do not parse at all), everything up to the last '@' is shown as ***, whatever slashes, question
80
+ * marks or hashes come before it, as the hosted maskLocation does. What follows the last '@' has its query values
81
+ * masked and its fragment dropped. */
82
+ function maskOption(value) {
83
+ const plain = value.replace(/[\t\n\r]/g, '');
84
+ let hasHost = false;
85
+ try {
86
+ hasHost = new URL(plain).host !== '';
87
+ }
88
+ catch {
89
+ hasHost = false;
90
+ }
91
+ const at = plain.lastIndexOf('@');
92
+ if (hasHost || at < 0)
93
+ return maskUrl(value);
94
+ const rest = plain.slice(at + 1);
95
+ const stop = rest.search(/[?#]/);
96
+ const tail = stop < 0 ? rest : rest.slice(0, stop) + (rest[stop] === '?' ? '?***' : '');
97
+ return '***@' + tail;
98
+ }
77
99
  function positiveInt(name, raw, fallback, max = Number.MAX_SAFE_INTEGER) {
78
100
  if (raw === undefined)
79
101
  return fallback;
@@ -82,7 +104,7 @@ function positiveInt(name, raw, fallback, max = Number.MAX_SAFE_INTEGER) {
82
104
  // space inside the value and lets a fragment such as a password through unmasked (P-N3, found by an
83
105
  // outside review 2026-09-28); a CLI argument is attacker input the moment it is echoed back in an error,
84
106
  // whatever option it was given for.
85
- const shown = () => maskUrl(raw);
107
+ const shown = () => maskOption(raw);
86
108
  if (!/^\d+$/.test(raw))
87
109
  throw new CliError(`${name} must be a positive integer (got "${shown()}").`);
88
110
  const n = Number(raw);
@@ -126,12 +148,15 @@ export function parseCliArgs(argv) {
126
148
  const htmlProfile = v['html-profile'];
127
149
  if (htmlProfile !== 'generic' && htmlProfile !== 'starlight')
128
150
  throw new CliError('--html-profile must be generic or starlight.');
151
+ // A rejected option value is echoed back in the error, so it is masked like the numeric and base-URL values above:
152
+ // a raw space splits the later report redactor's URL detection and let a password through (P01, found by an
153
+ // outside review 2026-10-02).
129
154
  const format = v.format;
130
155
  if (format !== 'text' && format !== 'json')
131
- throw new CliError(`--format must be text or json (got "${format}").`);
156
+ throw new CliError(`--format must be text or json (got "${maskOption(format)}").`);
132
157
  const frontMatter = v['front-matter'];
133
158
  if (frontMatter !== 'keep' && frontMatter !== 'strip')
134
- throw new CliError(`--front-matter must be keep or strip (got "${frontMatter}").`);
159
+ throw new CliError(`--front-matter must be keep or strip (got "${maskOption(frontMatter)}").`);
135
160
  const args = {
136
161
  htmlProfile,
137
162
  url: v.url,
@@ -180,7 +205,7 @@ export function parseCliArgs(argv) {
180
205
  // redactText pass over stderr/JSON: a raw space breaks that pass's run-based URL detection into
181
206
  // fragments too small to recognize as one URL, leaving user information such as a password visible
182
207
  // (0.2.16, found by an outside review 2026-09-28). maskUrl handles the whole value correctly regardless.
183
- throw new CliError(`--base-url must be an absolute http(s) URL (got "${maskUrl(args.baseUrl)}").`);
208
+ throw new CliError(`--base-url must be an absolute http(s) URL (got "${maskOption(args.baseUrl)}").`);
184
209
  }
185
210
  }
186
211
  }
@@ -1,6 +1,6 @@
1
1
  // The comparison core: aligns blocks and turns the alignment into findings. Pure and network-free.
2
2
  import { align, resolveLimits, AlignmentLimitError, UNCERTAIN_THRESHOLD } from './align.js';
3
- import { excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, visibleNumbers } from './normalize.js';
3
+ import { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, visibleNumbers } from './normalize.js';
4
4
  // The excerpt masks the whole block text before it cuts it, so it is computed once per block. Up to 0.2.11 every
5
5
  // finding computed it again, and a block with thousands of link findings did that thousands of times (0.2.12).
6
6
  const sides = new WeakMap();
@@ -154,10 +154,17 @@ export function pairLinks(hLinks, mLinks, maxWork = Number.POSITIVE_INFINITY) {
154
154
  });
155
155
  // Step 3: the links still unpaired, by loosely normalized text.
156
156
  const looseLists = new Map();
157
+ // The unused Markdown links whose label is empty once loose normalization has removed the punctuation ("?", "!"):
158
+ // they have no text key, so they pair by an unchanged target instead (0.2.22, found by an outside review 2026-10-02).
159
+ const emptyUnused = [];
157
160
  used.forEach((u, i) => {
158
- const k = u ? '' : looseNormalize(mLinks[i].text);
159
- if (k === '')
161
+ if (u)
160
162
  return;
163
+ const k = looseNormalize(mLinks[i].text);
164
+ if (k === '') {
165
+ emptyUnused.push(i);
166
+ return;
167
+ }
161
168
  const list = looseLists.get(k);
162
169
  if (list)
163
170
  list.push(i);
@@ -174,7 +181,28 @@ export function pairLinks(hLinks, mLinks, maxWork = Number.POSITIVE_INFINITY) {
174
181
  const stillMissing = [];
175
182
  for (const hi of missing) {
176
183
  const k = looseNormalize(hLinks[hi].text);
177
- const list = k === '' ? undefined : looseLists.get(k);
184
+ if (k === '') {
185
+ let found = -1;
186
+ for (const i of emptyUnused) {
187
+ work++;
188
+ if (work > maxWork) {
189
+ throw new AlignmentLimitError(`Comparison limit exceeded: pairing punctuation-only link labels by target needs more than ${maxWork} comparisons among ${hLinks.length} HTML and ${mLinks.length} Markdown links. Narrow the HTML content with --selector or compare a smaller page.`);
190
+ }
191
+ if (!used[i] && sameTarget(hLinks[hi], mLinks[i])) {
192
+ found = i;
193
+ break;
194
+ }
195
+ }
196
+ if (found < 0) {
197
+ stillMissing.push(hi);
198
+ }
199
+ else {
200
+ used[found] = true;
201
+ pairs.push([hi, found]);
202
+ }
203
+ continue;
204
+ }
205
+ const list = looseLists.get(k);
178
206
  const n = looseHeads.get(k) ?? 0;
179
207
  if (!list || n >= list.length) {
180
208
  stillMissing.push(hi);
@@ -273,8 +301,11 @@ function compareTables(out, h, m) {
273
301
  return;
274
302
  const hc = h.cells ?? [];
275
303
  const mc = m.cells ?? [];
276
- const hCols = Math.max(0, ...hc.map((r) => r.length));
277
- const mCols = Math.max(0, ...mc.map((r) => r.length));
304
+ // A loop, not Math.max(...rows): a spread passes one argument per row and a table of about 130 000 rows overran the
305
+ // call stack with an unwrapped RangeError (0.2.22, found by an outside review 2026-10-02).
306
+ const widest = (rows) => rows.reduce((n, r) => (r.length > n ? r.length : n), 0);
307
+ const hCols = widest(hc);
308
+ const mCols = widest(mc);
278
309
  if (hc.length !== mc.length || hCols !== mCols) {
279
310
  out.push({ code: 'TABLE_SHAPE_CHANGED', severity: 'error', direction: 'both', message: `Table shape differs: HTML ${hc.length}x${hCols}, Markdown ${mc.length}x${mCols} (rows x columns).`, html: side(h), markdown: side(m), before: `${hc.length}x${hCols}`, after: `${mc.length}x${mCols}` });
280
311
  return;
@@ -290,7 +321,7 @@ function compareTables(out, h, m) {
290
321
  }
291
322
  }
292
323
  function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
293
- if (p.kind === 'moved') {
324
+ if (p.kind === 'moved' || p.reordered) {
294
325
  out.push({ code: 'ORDER_CHANGED', severity: 'warning', direction: 'both', message: `The ${label(h)} appears in a different position in the Markdown.`, html: side(h), markdown: side(m) });
295
326
  }
296
327
  if (h.type !== m.type) {
@@ -310,7 +341,9 @@ function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
310
341
  const hc = h.code ?? '';
311
342
  const mc = m.code ?? '';
312
343
  if (hc !== mc) {
313
- if (h.text === m.text)
344
+ // Only whitespace may differ: the prose text normalizer also applies NFC and drops zero width characters,
345
+ // which would call a changed soft hyphen a whitespace edit (0.2.22, found by an outside review 2026-10-02).
346
+ if (codeWhitespaceKey(hc) === codeWhitespaceKey(mc))
314
347
  out.push({ code: 'CODE_WHITESPACE_CHANGED', severity: 'warning', direction: 'both', message: 'Code block differs only in whitespace or indentation.', html: side(h), markdown: side(m) });
315
348
  else
316
349
  out.push({ code: 'TEXT_CHANGED', severity: 'error', direction: 'both', message: 'Code block content differs.', html: side(h), markdown: side(m), before: excerpt(hc), after: excerpt(mc) });
@@ -25,4 +25,15 @@ export declare const MAX_NESTING_DEPTH = 1024;
25
25
  /** Deepest element nesting under a node, counted with an explicit stack so the count itself cannot
26
26
  * exhaust the call stack. */
27
27
  export declare function nestingDepth(node: ParentNode): number;
28
+ /** Whether an opening tag starts a subtree this extraction leaves out: the tag and role lists of isSkipped. The
29
+ * Markdown side asks it for inline raw HTML, so a button or a script in a Markdown paragraph is left out the way
30
+ * it is in an HTML paragraph (0.2.22, found by an outside review 2026-10-02). */
31
+ export declare function opensExcludedSubtree(name: string, attribs: Record<string, string>): boolean;
32
+ /** The nesting limit was exceeded. A subclass so a caller that otherwise tolerates a parse failure (raw HTML
33
+ * inside Markdown) can tell a limit from any other failure and let the limit through. */
34
+ export declare class HtmlDepthError extends HtmlExtractError {
35
+ readonly depth: number;
36
+ readonly limit: number;
37
+ constructor(depth: number, limit: number);
38
+ }
28
39
  export declare function extractHtml(source: string, options?: HtmlExtractOptions): Extraction;
package/dist/src/html.js CHANGED
@@ -44,6 +44,14 @@ export function nestingDepth(node) {
44
44
  }
45
45
  const SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'nav', 'iframe', 'svg', 'canvas', 'object', 'embed', 'map', 'form', 'button', 'input', 'select', 'textarea', 'dialog']);
46
46
  const SKIP_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary', 'search', 'menu', 'menubar', 'dialog']);
47
+ /** Whether an opening tag starts a subtree this extraction leaves out: the tag and role lists of isSkipped. The
48
+ * Markdown side asks it for inline raw HTML, so a button or a script in a Markdown paragraph is left out the way
49
+ * it is in an HTML paragraph (0.2.22, found by an outside review 2026-10-02). */
50
+ export function opensExcludedSubtree(name, attribs) {
51
+ if (SKIP_TAGS.has(name))
52
+ return true;
53
+ return SKIP_ROLES.has((attribs['role'] ?? '').toLowerCase());
54
+ }
47
55
  const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'summary', 'dd', 'dl', 'dt', 'div', 'fieldset', 'figcaption', 'figure', 'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'hr', 'li', 'main', 'ol', 'p', 'pre', 'section', 'table', 'ul', 'body', 'html', 'center', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'caption']);
48
56
  const HEADING_RE = /^h([1-6])$/;
49
57
  function lineOf(ctx, node) {
@@ -107,22 +115,33 @@ function iframeLink(el) {
107
115
  const title = el.attribs['title'] ?? '';
108
116
  return src && title ? { src, title } : null;
109
117
  }
110
- /** The hidden and aria-hidden attributes alone, without the tag, role and page chrome rules of isSkipped. */
118
+ /** The hidden and aria-hidden attributes alone, without the tag, role and page chrome rules of isSkipped. Used
119
+ * where only those two attributes matter (a task checkbox, a hidden-ancestor test); code text uses isSkipped. */
111
120
  function hiddenAttr(el) {
112
121
  return el.attribs['hidden'] !== undefined || el.attribs['aria-hidden'] === 'true';
113
122
  }
114
123
  /**
115
- * Text of code as the page shows it: every text node with its whitespace, except under a hidden or aria-hidden
116
- * element. Up to 0.2.12 code used textContent, which also returns hidden descendants, so a hidden span inside a
117
- * code block counted as code while the same span in a paragraph did not (found by an outside review 2026-09-26).
124
+ * Text of code as the page shows it: every text node with its whitespace, except under an element the rest of the
125
+ * extraction skips (isSkipped: the tag, role and page chrome rules, hidden and aria-hidden). Up to 0.2.12 code
126
+ * used textContent, which also returns hidden descendants, so a hidden span inside a code block counted as code
127
+ * while the same span in a paragraph did not (found by an outside review 2026-09-26). Up to 0.2.20 only hidden
128
+ * and aria-hidden were applied here, so the text of a button, template or nav inside a pre was still code while
129
+ * the same element in a paragraph was left out (found by an outside review 2026-10-02).
118
130
  */
119
- function visibleCode(nodes) {
131
+ function visibleCode(nodes, profile = 'generic') {
120
132
  let out = '';
121
133
  for (const node of nodes) {
122
134
  if (node instanceof Text)
123
135
  out += node.data;
124
- else if (node instanceof Element && !hiddenAttr(node))
125
- out += visibleCode(node.children);
136
+ // The root argument only matters for header and footer directly under body, which cannot occur inside a pre.
137
+ else if (node instanceof Element && !isSkipped(node, node, profile)) {
138
+ // A visible <br> is a line break in a pre; up to 0.2.21 it contributed nothing, so two lines read as one
139
+ // joined word (0.2.22, found by an outside review 2026-10-02).
140
+ if (node.name === 'br')
141
+ out += '\n';
142
+ else
143
+ out += visibleCode(node.children, profile);
144
+ }
126
145
  }
127
146
  return out;
128
147
  }
@@ -265,7 +284,7 @@ function handleBlock(ctx, el) {
265
284
  return;
266
285
  }
267
286
  if (el.name === 'pre') {
268
- const code = normalizeCode(ctx.profile === 'starlight' ? starlightCode(el) : visibleCode(el.children));
287
+ const code = normalizeCode(ctx.profile === 'starlight' ? starlightCode(el) : visibleCode(el.children, ctx.profile));
269
288
  if (code.trim() !== '')
270
289
  pushBlock(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, el, el);
271
290
  return;
@@ -309,7 +328,7 @@ function listInfo(ctx, li) {
309
328
  if (p === ctx.root)
310
329
  break;
311
330
  }
312
- const info = { ordered, depth: ctx.listBase + Math.max(0, lists - 1), checked: taskState(li) };
331
+ const info = { ordered, depth: ctx.listBase + Math.max(0, lists - 1), checked: taskState(li, ctx.profile) };
313
332
  if (ordered && parent) {
314
333
  const reversed = parent.attribs['reversed'] !== undefined;
315
334
  const ordinal = listOrdinals(ctx, parent).get(li);
@@ -358,7 +377,7 @@ function listOrdinals(ctx, ol) {
358
377
  * checkbox hidden by the hidden or aria-hidden attribute, or wrapped in a hidden ancestor, is skipped like any
359
378
  * other hidden content: its subtree is never pushed onto the stack, so an earlier hidden checkbox cannot answer
360
379
  * for a later visible one (0.2.16, found by an outside review 2026-09-28). */
361
- function taskState(li) {
380
+ function taskState(li, profile = 'generic') {
362
381
  const stack = [...li.children].reverse();
363
382
  while (stack.length > 0) {
364
383
  const node = stack.pop();
@@ -366,12 +385,19 @@ function taskState(li) {
366
385
  // same reason hiddenInPage above treats it like a hidden ancestor for the main extraction. taskState had
367
386
  // no matching check, so a checkbox sitting in a <template> answered for a later, real checkbox in the
368
387
  // same item (found by an outside review 2026-09-28).
369
- if (!(node instanceof Element) || node.name === 'ul' || node.name === 'ol' || node.name === 'template')
370
- continue;
371
- if (hiddenAttr(node))
388
+ if (!(node instanceof Element) || node.name === 'ul' || node.name === 'ol')
372
389
  continue;
373
- if (node.name === 'input' && (node.attribs['type'] ?? '').toLowerCase() === 'checkbox')
390
+ // The checkbox itself is the one skipped tag whose state is wanted; a hidden one is still ignored.
391
+ if (node.name === 'input' && (node.attribs['type'] ?? '').toLowerCase() === 'checkbox') {
392
+ if (hiddenAttr(node))
393
+ continue;
374
394
  return node.attribs['checked'] !== undefined;
395
+ }
396
+ // Every other subtree the extraction leaves out (a form, a nav, a template, a role such as navigation, hidden
397
+ // and aria-hidden) is never walked, so a checkbox inside one cannot answer for the item (0.2.22, found by an
398
+ // outside review 2026-10-02).
399
+ if (isSkipped(node, node, profile))
400
+ continue;
375
401
  for (let i = node.children.length - 1; i >= 0; i--)
376
402
  stack.push(node.children[i]);
377
403
  }
@@ -411,23 +437,25 @@ function handleListItem(ctx, li) {
411
437
  }
412
438
  flushRun(ctx, run, li, ownFlushed ? 'paragraph' : 'listItem', info);
413
439
  }
414
- /** Read only recognized direct line wrappers; never discard extra non-whitespace code children. */
440
+ /** Read only recognized direct line wrappers; a shape that is not recognized falls back to visibleCode over all
441
+ * children, so extra non-whitespace code children are never discarded by the shape test. Elements isSkipped
442
+ * excludes are left out in every path, as in the generic profile. */
415
443
  function starlightCode(pre) {
416
444
  if (!ancestor(pre, (node) => hasClass(node, 'expressive-code')))
417
- return visibleCode(pre.children);
445
+ return visibleCode(pre.children, 'starlight');
418
446
  const meaningful = pre.children.filter((node) => !(node instanceof Text && !node.data.trim()));
419
447
  const code = meaningful.length === 1 ? meaningful[0] : null;
420
448
  if (!(code instanceof Element) || code.name !== 'code')
421
- return visibleCode(pre.children);
449
+ return visibleCode(pre.children, 'starlight');
422
450
  // The specialized shape below reads code.children directly and never passes through visibleCode, so a
423
451
  // hidden or aria-hidden <code> wrapper (the whole block, not one .ec-line inside it) was never checked and
424
452
  // its lines were exported as if visible (found by an outside review 2026-09-28). A hidden wrapper has no
425
453
  // visible code at all, the same outcome visibleCode itself gives a hidden element anywhere else.
426
- if (hiddenAttr(code))
454
+ if (isSkipped(code, code, 'starlight'))
427
455
  return '';
428
456
  const lines = code.children.filter((node) => !(node instanceof Text && !node.data.trim()));
429
457
  if (lines.length === 0 || !lines.every((node) => node instanceof Element && node.name === 'div' && hasClass(node, 'ec-line')))
430
- return visibleCode(pre.children);
458
+ return visibleCode(pre.children, 'starlight');
431
459
  // A gutter (line numbers from a plugin) sits beside the code as a direct child of the line; it is not code text.
432
460
  const gutter = (node) => node instanceof Element && node.name === 'div' && hasClass(node, 'gutter');
433
461
  // starlight-llms-txt prefixes + or - to ins and del lines when the block has a language other than diff. The page
@@ -437,7 +465,7 @@ function starlightCode(pre) {
437
465
  && lines.some((line) => line instanceof Element && (hasClass(line, 'ins') || hasClass(line, 'del')));
438
466
  // A line hidden with the hidden attribute is not exported either: up to 0.2.15 every .ec-line reached the text
439
467
  // regardless of visibility (0.2.16, found by an outside review 2026-09-28).
440
- const visibleLines = lines.filter((line) => !(line instanceof Element && hiddenAttr(line)));
468
+ const visibleLines = lines.filter((line) => !(line instanceof Element && isSkipped(line, line, 'starlight')));
441
469
  return visibleLines.map((line) => starlightLineText(line.children.filter((node) => !gutter(node)), line, diffMarkers)).join('\n');
442
470
  }
443
471
  /** One Expressive Code line as starlight-llms-txt exports it. The marker goes before the first text of the first
@@ -445,17 +473,21 @@ function starlightCode(pre) {
445
473
  function starlightLineText(children, line, diffMarkers) {
446
474
  const inserted = hasClass(line, 'ins');
447
475
  if (!diffMarkers || !(inserted || hasClass(line, 'del')))
448
- return visibleCode(children);
476
+ return visibleCode(children, 'starlight');
449
477
  const target = firstNonIndentSpan(children)?.children[0];
450
478
  if (!(target instanceof Text))
451
- return visibleCode(children);
479
+ return visibleCode(children, 'starlight');
452
480
  let out = '';
453
481
  const collect = (nodes) => {
454
482
  for (const node of nodes) {
455
483
  if (node instanceof Text)
456
484
  out += (node === target ? (inserted ? '+' : '-') : '') + node.data;
457
- else if (node instanceof Element && !hiddenAttr(node))
458
- collect(node.children);
485
+ else if (node instanceof Element && !isSkipped(node, node, 'starlight')) {
486
+ if (node.name === 'br')
487
+ out += '\n';
488
+ else
489
+ collect(node.children);
490
+ }
459
491
  }
460
492
  };
461
493
  collect(children);
@@ -630,6 +662,19 @@ function hiddenInPage(el) {
630
662
  }
631
663
  return false;
632
664
  }
665
+ /** Whether the element, or any ancestor, is a subtree the extraction leaves out (navigation, a dialog, a banner
666
+ * role and the rest of isSkipped). A candidate root inside one is page chrome, not main content. A plain <form> is
667
+ * the one exception: a page-wide form (ASP.NET WebForms) wraps the real content, so a candidate inside it is kept
668
+ * (Erik's foreman decision 2026-10-02). A form with a left-out role still counts. */
669
+ function inExcludedSubtree(el) {
670
+ for (let cur = el; cur instanceof Element; cur = cur.parent) {
671
+ if (cur.name === 'form' && cur !== el && !SKIP_ROLES.has((cur.attribs['role'] ?? '').toLowerCase()))
672
+ continue;
673
+ if (isSkipped(cur, el))
674
+ return true;
675
+ }
676
+ return false;
677
+ }
633
678
  function pickRoot(doc, selector, notes, issues) {
634
679
  if (selector) {
635
680
  let matches;
@@ -651,9 +696,14 @@ function pickRoot(doc, selector, notes, issues) {
651
696
  // one nested inside another (an <article> inside an <article>) is part of it (found by an outside review 2026-09-26).
652
697
  for (const tag of ['main', 'article', '[role=main]']) {
653
698
  const matches = selectAll(tag, doc.children).filter((n) => n instanceof Element);
654
- const visible = matches.filter((el) => !hiddenInPage(el));
655
- if (matches.length > visible.length)
656
- notes.push(`${matches.length - visible.length} hidden <${tag}> element(s) were not used as the main content.`);
699
+ const shown = matches.filter((el) => !hiddenInPage(el));
700
+ // A candidate inside excluded content, such as an <article> inside a <nav>, is left out the same way: up to
701
+ // 0.2.21 it became the root and the real body was never compared (0.2.22, found by an outside review 2026-10-02).
702
+ const visible = shown.filter((el) => !inExcludedSubtree(el));
703
+ if (matches.length > shown.length)
704
+ notes.push(`${matches.length - shown.length} hidden <${tag}> element(s) were not used as the main content.`);
705
+ if (shown.length > visible.length)
706
+ notes.push(`${shown.length - visible.length} <${tag}> element(s) inside left-out content (navigation, a form, a dialog and the like) were not used as the main content.`);
657
707
  if (visible.length >= 1) {
658
708
  const set = new Set(visible);
659
709
  const outer = visible.filter((el) => {
@@ -678,6 +728,17 @@ function pickRoot(doc, selector, notes, issues) {
678
728
  }
679
729
  throw new HtmlExtractError('Document has no <body> element.');
680
730
  }
731
+ /** The nesting limit was exceeded. A subclass so a caller that otherwise tolerates a parse failure (raw HTML
732
+ * inside Markdown) can tell a limit from any other failure and let the limit through. */
733
+ export class HtmlDepthError extends HtmlExtractError {
734
+ depth;
735
+ limit;
736
+ constructor(depth, limit) {
737
+ super(`HTML nesting depth ${depth} exceeds the limit of ${limit} levels; the comparison was not run.`);
738
+ this.depth = depth;
739
+ this.limit = limit;
740
+ }
741
+ }
681
742
  export function extractHtml(source, options = {}) {
682
743
  const profile = options.profile ?? 'generic';
683
744
  if (profile !== 'generic' && profile !== 'starlight')
@@ -687,7 +748,7 @@ export function extractHtml(source, options = {}) {
687
748
  const maxDepth = options.maxDepth ?? MAX_NESTING_DEPTH;
688
749
  const depth = nestingDepth(doc);
689
750
  if (depth > maxDepth)
690
- throw new HtmlExtractError(`HTML nesting depth ${depth} exceeds the limit of ${maxDepth} levels; the comparison was not run.`);
751
+ throw new HtmlDepthError(depth, maxDepth);
691
752
  const notes = [];
692
753
  const issues = [];
693
754
  const baseEl = selectOne('base[href]', doc.children);
@@ -2,8 +2,8 @@
2
2
  import { fromMarkdown } from 'mdast-util-from-markdown';
3
3
  import { gfm } from 'micromark-extension-gfm';
4
4
  import { gfmFromMarkdown } from 'mdast-util-gfm';
5
- import { extractHtml, MAX_NESTING_DEPTH } from './html.js';
6
- import { parseDocument } from 'htmlparser2';
5
+ import { extractHtml, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
6
+ import { parseDocument, Parser } from 'htmlparser2';
7
7
  import { Element, Text } from 'domhandler';
8
8
  import { excerpt, extractNumbers, insideHiddenUrlPart, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
9
9
  export class MarkdownExtractError extends Error {
@@ -37,7 +37,7 @@ function parseInlineTag(value) {
37
37
  const el = doc.children.find((c) => c instanceof Element);
38
38
  if (!el)
39
39
  return null;
40
- return { name: el.name.toLowerCase(), closing: false, attribs: el.attribs };
40
+ return { name: el.name.toLowerCase(), closing: false, selfClosing: /\/\s*>$/.test(v), attribs: el.attribs };
41
41
  }
42
42
  /**
43
43
  * Walks phrasing children in order so that inline HTML anchors (<a href="..">text</a>) become links with
@@ -58,7 +58,16 @@ function inlineChildren(ctx, children, run, line) {
58
58
  // A hidden inline element hides its text in a reader that renders the HTML, as the same attribute does on the
59
59
  // HTML side. Up to 0.2.12 only the tags were dropped and the text between them stayed (found by an outside review
60
60
  // 2026-09-26). Its content up to the matching closing tag is left out; without one the tag is reported.
61
- if (!tag.closing && (tag.attribs['hidden'] !== undefined || tag.attribs['aria-hidden'] === 'true')) {
61
+ // An inline element the HTML side leaves out (a button, a script, a nav, a role such as navigation) is skipped the
62
+ // same way: up to 0.2.21 only its tags were dropped and its text compared as visible (0.2.22, found by an outside
63
+ // review 2026-10-02).
64
+ // A left-out foreign element written as self-closing (<svg/>) is closed and empty, as the HTML parser reads it:
65
+ // there is nothing to skip through and nothing to report. Any other tag with a trailing slash is not closed in
66
+ // HTML (<button/> stays open), so it takes the normal path below. Void elements already end at their own tag.
67
+ if (!tag.closing && tag.selfClosing && FOREIGN_TAGS.has(tag.name) && opensExcludedSubtree(tag.name, tag.attribs))
68
+ continue;
69
+ const hiddenTag = tag.attribs['hidden'] !== undefined || tag.attribs['aria-hidden'] === 'true';
70
+ if (!tag.closing && (hiddenTag || opensExcludedSubtree(tag.name, tag.attribs))) {
62
71
  // A trailing "/>" on a non-void element is not a self-close in HTML: <span hidden/>text</span> does not
63
72
  // show "text" in a browser either, only a void element's own tag ends there. Up to 0.2.15 the slash alone
64
73
  // was read as a close, so a malformed but common self-closing spelling left hidden text visible (0.2.16,
@@ -68,7 +77,7 @@ function inlineChildren(ctx, children, run, line) {
68
77
  closes ??= closingTags(children);
69
78
  const end = closes.get(i) ?? -1;
70
79
  if (end < 0) {
71
- ctx.issues.push({ code: 'MARKDOWN_INLINE_HTML_UNSUPPORTED', severity: 'warning', message: `A hidden inline <${tag.name}> has no matching </${tag.name}> in the same paragraph; its text was compared as visible.`, line: node.position?.start.line ?? line, excerpt: excerpt(node.value) });
80
+ ctx.issues.push({ code: 'MARKDOWN_INLINE_HTML_UNSUPPORTED', severity: 'warning', message: `A ${hiddenTag ? 'hidden' : 'left-out'} inline <${tag.name}> has no matching </${tag.name}> in the same paragraph; its text was compared as visible.`, line: node.position?.start.line ?? line, excerpt: excerpt(node.value) });
72
81
  continue;
73
82
  }
74
83
  i = end;
@@ -120,6 +129,7 @@ function inlineChildren(ctx, children, run, line) {
120
129
  i = end;
121
130
  }
122
131
  }
132
+ const FOREIGN_TAGS = new Set(['svg', 'math']);
123
133
  const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
124
134
  /**
125
135
  * For every opening tag among the inline nodes of a paragraph, the index of its matching closing tag, counting
@@ -242,6 +252,8 @@ function handleTable(ctx, table) {
242
252
  function handle(ctx, node, listItem) {
243
253
  switch (node.type) {
244
254
  case 'heading': {
255
+ if (hiddenWrapped(ctx))
256
+ return;
245
257
  const run = { text: '', links: [] };
246
258
  inlineChildren(ctx, node.children, run, node.position?.start.line);
247
259
  const text = strictNormalize(run.text);
@@ -250,6 +262,8 @@ function handle(ctx, node, listItem) {
250
262
  return;
251
263
  }
252
264
  case 'paragraph': {
265
+ if (hiddenWrapped(ctx))
266
+ return;
253
267
  const run = { text: '', links: [] };
254
268
  inlineChildren(ctx, node.children, run, node.position?.start.line);
255
269
  const text = strictNormalize(run.text);
@@ -258,13 +272,16 @@ function handle(ctx, node, listItem) {
258
272
  return;
259
273
  }
260
274
  case 'code': {
275
+ if (hiddenWrapped(ctx))
276
+ return;
261
277
  const code = normalizeCode(node.value);
262
278
  if (code.trim() !== '')
263
279
  push(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, node);
264
280
  return;
265
281
  }
266
282
  case 'table':
267
- handleTable(ctx, node);
283
+ if (!hiddenWrapped(ctx))
284
+ handleTable(ctx, node);
268
285
  return;
269
286
  case 'list': {
270
287
  // A Markdown list shows its start number and counts on; its items carry the list kind, the nesting level and
@@ -293,6 +310,8 @@ function handle(ctx, node, listItem) {
293
310
  handleRawHtml(ctx, node.value, node.position?.start.line);
294
311
  return;
295
312
  case 'footnoteDefinition':
313
+ if (hiddenWrapped(ctx))
314
+ return;
296
315
  // Footnotes are not compared: an HTML page renders them as a numbered list with back links, which would not
297
316
  // read as the Markdown definitions. Up to 0.2.12 a definition was dropped without a trace, so a footnote added
298
317
  // to the Markdown passed strict mode (found by an outside review 2026-09-26). It is now a warning with its text.
@@ -319,15 +338,27 @@ function footnoteText(node) {
319
338
  /** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
320
339
  * comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
321
340
  function handleRawHtml(ctx, value, line) {
341
+ // Wrappers an earlier raw block left open are written in front of this one, on the same line, so the extractor
342
+ // sees the same element tree a browser would and hides what a hidden wrapper still covers (P07).
343
+ const prefix = ctx.wrappers.map((w) => `<${w.name}${w.hidden ? ' hidden' : ''}>`).join('');
344
+ const fragment = prefix + value;
345
+ ctx.wrappers = openWrappers(fragment);
322
346
  // Text check for the fallback warning, taken from the parsed DOM rather than from regex stripping:
323
347
  // comments are not text, and script, style, template and noscript are page machinery on both sides,
324
- // so their content does not count as skipped text.
325
- const textOnly = visibleText(value);
348
+ // so their content does not count as skipped text. Hidden elements are left out, as in the extraction.
349
+ const textOnly = visibleText(fragment);
326
350
  let parsed = null;
327
351
  try {
328
- parsed = extractHtml(`<body>${value}</body>`, { selector: 'body', baseUrl: ctx.base });
352
+ parsed = extractHtml(`<body>${fragment}</body>`, { selector: 'body', baseUrl: ctx.base, maxDepth: ctx.maxDepth + 1 });
329
353
  }
330
- catch {
354
+ catch (err) {
355
+ // A block nested past the caller's limit stops the comparison like the same nesting in the HTML page does
356
+ // (run.ts turns this into the RunError, exit 2). Any other parse failure still falls back to the warning.
357
+ // The wrapper body is one level the block does not have, so the limit passed above is one higher and the
358
+ // reported depth one lower: the block is held to the same limit, and reported in the same terms, as the
359
+ // same element tree on the HTML side.
360
+ if (err instanceof HtmlDepthError)
361
+ throw new HtmlDepthError(err.depth - 1, ctx.maxDepth);
331
362
  parsed = null;
332
363
  }
333
364
  const blocks = parsed?.blocks ?? [];
@@ -356,6 +387,29 @@ function handleRawHtml(ctx, value, line) {
356
387
  }
357
388
  }
358
389
  const MACHINERY = new Set(['script', 'style', 'template', 'noscript']);
390
+ /** Whether a hidden raw HTML wrapper from an earlier block is still open. */
391
+ function hiddenWrapped(ctx) {
392
+ return ctx.wrappers.length > 0;
393
+ }
394
+ /**
395
+ * The elements still open at the end of a raw HTML fragment, from the outermost hidden or aria-hidden one inward,
396
+ * or none when no hidden element is open. The parser is not ended, because ending it closes every open element and
397
+ * the open ones are the answer. Bounded by the nesting limit: a deeper stack stops the comparison in extractHtml.
398
+ */
399
+ function openWrappers(fragment) {
400
+ const stack = [];
401
+ const parser = new Parser({
402
+ onopentag(name, attribs) {
403
+ stack.push({ name, hidden: attribs['hidden'] !== undefined || attribs['aria-hidden'] === 'true' });
404
+ },
405
+ onclosetag() {
406
+ stack.pop();
407
+ },
408
+ }, { decodeEntities: true });
409
+ parser.write(fragment);
410
+ const first = stack.findIndex((w) => w.hidden);
411
+ return first < 0 ? [] : stack.slice(first);
412
+ }
359
413
  /** Strictly normalized text of an HTML fragment as a parser sees it: text nodes only, comments and
360
414
  * machinery elements excluded. */
361
415
  function visibleText(fragment) {
@@ -367,6 +421,8 @@ function visibleText(fragment) {
367
421
  else if (node instanceof Element) {
368
422
  if (MACHINERY.has(node.name.toLowerCase()))
369
423
  continue;
424
+ if (node.attribs['hidden'] !== undefined || node.attribs['aria-hidden'] === 'true')
425
+ continue;
370
426
  walk(node.children);
371
427
  }
372
428
  }
@@ -416,7 +472,7 @@ export function extractMarkdown(source, options = {}) {
416
472
  const depth = treeDepth(tree);
417
473
  if (depth > maxDepth)
418
474
  throw new MarkdownExtractError(`Markdown nesting depth ${depth} exceeds the limit of ${maxDepth} levels; the comparison was not run.`);
419
- const ctx = { base: options.baseUrl ?? null, source: fm.text, blocks: [], notes: [], issues: [], definitions: collectDefinitions(tree), listDepth: 0 };
475
+ const ctx = { base: options.baseUrl ?? null, source: fm.text, blocks: [], notes: [], issues: [], definitions: collectDefinitions(tree), listDepth: 0, maxDepth, wrappers: [] };
420
476
  const fmExcerpt = () => excerpt(fm.body.replace(/\s+/g, ' '));
421
477
  if (mode === 'strip' && fm.skippedLines > 0) {
422
478
  ctx.notes.push(`Front matter (${fm.skippedLines} lines) was stripped as requested (--front-matter strip).`);
@@ -1,5 +1,11 @@
1
1
  export declare function strictNormalize(text: string): string;
2
2
  export declare function looseNormalize(text: string): string;
3
+ /** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
4
+ * whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
5
+ * Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
6
+ * a changed soft hyphen or a composed against a decomposed letter is a change of the code (0.2.22, found by an
7
+ * outside review 2026-10-02). */
8
+ export declare function codeWhitespaceKey(code: string): string;
3
9
  /** Code content: CRLF and CR line endings become LF and every trailing newline is removed; other whitespace is kept. */
4
10
  export declare function normalizeCode(code: string): string;
5
11
  /** Removes ANSI escape sequences and other C0 controls from a value that may come from a compared page or a raw
@@ -30,6 +30,14 @@ export function looseNormalize(text) {
30
30
  .replace(/\s+/g, ' ')
31
31
  .trim();
32
32
  }
33
+ /** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
34
+ * whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
35
+ * Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
36
+ * a changed soft hyphen or a composed against a decomposed letter is a change of the code (0.2.22, found by an
37
+ * outside review 2026-10-02). */
38
+ export function codeWhitespaceKey(code) {
39
+ return code.replace(/[\p{Zs}\t\r\n\f\v]+/gu, ' ').replace(/^ | $/g, '');
40
+ }
33
41
  /** Code content: CRLF and CR line endings become LF and every trailing newline is removed; other whitespace is kept. */
34
42
  export function normalizeCode(code) {
35
43
  return code.replace(/\r\n?/g, '\n').replace(/\n+$/, '');
@@ -1,2 +1,2 @@
1
1
  export declare const TOOL_NAME = "markdown-parity-check";
2
- export declare const TOOL_VERSION = "0.2.20";
2
+ export declare const TOOL_VERSION = "0.2.22";
@@ -2,4 +2,4 @@
2
2
  // Cloudflare Worker as well as under Node.js. test/version.test.ts fails the build when these differ
3
3
  // from package.json, which stays the version the release workflow publishes.
4
4
  export const TOOL_NAME = 'markdown-parity-check';
5
- export const TOOL_VERSION = '0.2.20';
5
+ export const TOOL_VERSION = '0.2.22';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-parity-check",
3
- "version": "0.2.20",
3
+ "version": "0.2.22",
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",