markdown-parity-check 0.2.32 → 0.2.34
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 +15 -12
- package/SECURITY.md +1 -1
- package/dist/src/align.js +22 -4
- package/dist/src/cli.d.ts +1 -1
- package/dist/src/cli.js +16 -1
- package/dist/src/compare.d.ts +7 -5
- package/dist/src/compare.js +71 -76
- package/dist/src/fetch.js +67 -7
- package/dist/src/html.d.ts +1 -0
- package/dist/src/html.js +19 -5
- package/dist/src/markdown.js +112 -29
- package/dist/src/normalize.d.ts +13 -0
- package/dist/src/normalize.js +45 -8
- package/dist/src/run.js +33 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ npx --yes markdown-parity-check --html-file page.html --markdown-file page.md --
|
|
|
51
51
|
| --- | --- |
|
|
52
52
|
| `0` | The comparison completed without a rejecting finding. |
|
|
53
53
|
| `1` | The comparison completed and found rejecting content or delivery differences. |
|
|
54
|
-
| `2` | An input, fetch, parse or report error prevented a reliable comparison. |
|
|
54
|
+
| `2` | An input, fetch, parse or report error prevented a reliable comparison. A standard output that is closed before the report is written also gives 2. |
|
|
55
55
|
|
|
56
56
|
Exit code 0 means the implemented checks found nothing to reject. It does not prove that the two versions mean the same thing.
|
|
57
57
|
|
|
@@ -78,10 +78,10 @@ A value that is outside these ranges, or that is not a plain run of digits, stop
|
|
|
78
78
|
|
|
79
79
|
### Example output
|
|
80
80
|
|
|
81
|
-
This is the text report for the matching fixture pair in this repository, run with version 0.2.
|
|
81
|
+
This is the text report for the matching fixture pair in this repository, run with version 0.2.34 on 2026-11-05. The exact command is in the Development section below. The text report ends with a list of limitations, which is omitted here:
|
|
82
82
|
|
|
83
83
|
```text
|
|
84
|
-
markdown-parity-check 0.2.
|
|
84
|
+
markdown-parity-check 0.2.34 (offline mode)
|
|
85
85
|
Result: PASS (0 error(s), 0 warning(s), 1 info)
|
|
86
86
|
|
|
87
87
|
HTML: test/fixtures/same/page.html (file, 1,017 bytes, base https://example.com/page)
|
|
@@ -110,10 +110,10 @@ Front matter is kept by default and compared as content. If the HTML does not ca
|
|
|
110
110
|
|
|
111
111
|
### Blocks and severities
|
|
112
112
|
|
|
113
|
-
Headings, paragraphs, list items, tables, code blocks and links are compared block by block. A link that wraps block elements, such as a linked card with a heading and a paragraph, is compared as those blocks: each keeps its own type and heading level and carries the link, and the Markdown side is read the same way, so `## [Title](url)` is a heading with a link. In a table cell the link is read as part of the cell text. Content
|
|
113
|
+
Headings, paragraphs, list items, tables, code blocks and links are compared block by block. A link that wraps block elements, such as a linked card with a heading and a paragraph, is compared as those blocks: each keeps its own type and heading level and carries the link, and the Markdown side is read the same way, so `## [Title](url)` is a heading with a link. In a table cell the link is read as part of the cell text. Content that is hidden or sits inside a left-out element is left out on both sides, also when the raw HTML wrapper, such as `<div hidden>` or `<nav>`, is opened in one Markdown block and closed in a later one. A table caption counts as a paragraph before the table.
|
|
114
114
|
|
|
115
115
|
- Errors: missing and added blocks, a change in text or numbers, a changed table or link, and a list item that shows another number or a different checked or unchecked state.
|
|
116
|
-
- Warnings: a checkbox that is present on one side only, a difference in order, which is also reported for a block that moved and changed only in case, punctuation or typographic characters, and a difference in heading level, case, punctuation, list kind or nesting level. Each footnote in the Markdown is a warning, because footnotes are not compared. These are the main cases, and the `code` of each finding names the exact rule. A missing or extra copy of a repeated block is reported as a missing or added block, which is an error.
|
|
116
|
+
- Warnings: a checkbox that is present on one side only, a difference in order, which is also reported for a block that moved and changed only in case, punctuation or typographic characters, and a difference in heading level, case, punctuation, list kind or nesting level. A block that moved and also changed in its words or numbers gets the finding for that change and no order finding. A changed accent mark, vowel sign, symbol or emoji is a change in text and not in punctuation, so it is an error. A swapped symbol is an error also when a reader sees the same meaning, for example an ASCII arrow made of a hyphen and a greater-than sign against an arrow character, or a dropped trademark sign. An invisible variation selector alone is not. Each footnote in the Markdown is a warning, because footnotes are not compared. These are the main cases, and the `code` of each finding names the exact rule. A missing or extra copy of a repeated block is reported as a missing or added block, which is an error.
|
|
117
117
|
- Information: each skipped comparison, which does not fail a check, not even with `--strict`.
|
|
118
118
|
|
|
119
119
|
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.
|
|
@@ -129,13 +129,15 @@ Some content is left out even when it sits inside the main content, in code bloc
|
|
|
129
129
|
|
|
130
130
|
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.
|
|
131
131
|
|
|
132
|
-
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.
|
|
132
|
+
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. Inside a paragraph, a left-out tag with no closing tag is reported as a warning and its text is compared as visible. A left-out wrapper such as `<nav>` or `<form>` that is opened in its own Markdown block and never closed hides every block after it, the way an unclosed element does in HTML, and a Markdown document left with no content ends with exit code 2. The void tags `input` and `embed` need no closing tag and are skipped on their own. A self-closing `<svg/>` counts as closed by itself, as in HTML, and `<button/>` does not.
|
|
133
133
|
|
|
134
134
|
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.
|
|
135
135
|
|
|
136
136
|
### Delivery in URL mode
|
|
137
137
|
|
|
138
|
-
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. A Markdown response labelled `text/plain` is a warning, and any other content type than `text/markdown` or `text/x-markdown` is an error. If the HTML request itself returns an HTTP error, the run ends with exit code 2.
|
|
138
|
+
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. A Markdown response labelled `text/plain` is a warning, and any other content type than `text/markdown` or `text/x-markdown` is an error. A comment, an XML declaration or another declaration before the doctype does not hide an HTML page from this check. If the HTML request itself returns an HTTP error, the run ends with exit code 2.
|
|
139
|
+
|
|
140
|
+
An HTML response is decoded by its byte order mark first, then by the charset of its Content-Type header, then by a meta charset declaration in its first 1024 bytes, and as UTF-8 when none of them names a known encoding. A Markdown response is decoded by the charset of its header, or as UTF-8.
|
|
139
141
|
|
|
140
142
|
### Limits of the method
|
|
141
143
|
|
|
@@ -158,10 +160,11 @@ The hosted page also answers a JSON POST, described on the page. It runs the rel
|
|
|
158
160
|
Some limits are not in the table:
|
|
159
161
|
|
|
160
162
|
- 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.
|
|
163
|
+
- A host written as an IPv6 literal in brackets is checked against the same address policy as a resolved address and is not looked up in DNS.
|
|
161
164
|
- 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.
|
|
162
165
|
- The command-line tool follows at most 5 redirects.
|
|
163
|
-
- When elements are nested more than 1024 levels deep, in the HTML page, in a raw HTML block written inside the Markdown or in the Markdown's own structure, the extraction stops with exit code 2.
|
|
164
|
-
- 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 two values.
|
|
166
|
+
- When elements are nested more than 1024 levels deep, in the HTML page, in a raw HTML block written inside the Markdown, across raw elements left open between Markdown blocks, or in the Markdown's own structure, the extraction stops with exit code 2.
|
|
167
|
+
- 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 two values for block pairs and similar block pairs. `maxSimilarityWork` has no default bound.
|
|
165
168
|
- The hosted page uses lower nesting and matching limits: 512 levels and 50 000 similar block pairs.
|
|
166
169
|
|
|
167
170
|
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 leaves out, 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. The page passed again on 2026-10-02. [HTML and Markdown can disagree](https://turva.dev/blog/html-and-markdown-can-disagree) reads that result in full.
|
|
@@ -199,7 +202,7 @@ The options type is `RunOptions`. It takes `selector`, `frontMatter`, `strict`,
|
|
|
199
202
|
|
|
200
203
|
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`.
|
|
201
204
|
|
|
202
|
-
A host with a smaller CPU or memory budget can pass lower `limits`, typed as `RunLimits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The nesting limit also applies to raw HTML blocks inside the Markdown.
|
|
205
|
+
A host with a smaller CPU or memory budget can pass lower `limits`, typed as `RunLimits`: `maxAlignmentPairs`, `maxSimilarityCandidates`, `maxSimilarityWork` and `maxNestingDepth`. The nesting limit also applies to raw HTML blocks inside the Markdown. Set `maxSimilarityWork` when the library compares untrusted documents: with the default limits one measured worst case at the full 4 000 000 block pairs took between 26 and 30 seconds, and a value of 2 000 000 made the pairing step stop after about 70 milliseconds, on top of the parse time. `align` and `compare` throw an `AlignmentLimitError` there, and `run` turns it into a `RunError` with the same message.
|
|
203
206
|
|
|
204
207
|
The caller fetches the pages and decides which addresses are allowed. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
|
|
205
208
|
|
|
@@ -245,10 +248,10 @@ Only after that check does it create the GitHub release with the verified tarbal
|
|
|
245
248
|
GitHub Actions publishes every version from 0.1.2 on with npm trusted publishing, and each one carries a provenance attestation. To check one, install it in an empty directory and ask npm to verify the signatures. Replace the version with the one you want to check.
|
|
246
249
|
|
|
247
250
|
```sh
|
|
248
|
-
mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.
|
|
251
|
+
mkdir verify-mpc && cd verify-mpc && npm init -y && npm install markdown-parity-check@0.2.34 --ignore-scripts && npm audit signatures
|
|
249
252
|
```
|
|
250
253
|
|
|
251
|
-
`npm audit signatures` checks the registry signature and the provenance attestation of each installed package that has one. The attestation of this package names three things to compare with what you expect: the repository `github.com/erekola/markdown-parity-check`, the workflow file `.github/workflows/release.yml` and the commit that produced the tarball. The npm version page shows them under Provenance. Tag `v0.2.
|
|
254
|
+
`npm audit signatures` checks the registry signature and the provenance attestation of each installed package that has one. The attestation of this package names three things to compare with what you expect: the repository `github.com/erekola/markdown-parity-check`, the workflow file `.github/workflows/release.yml` and the commit that produced the tarball. The npm version page shows them under Provenance. Tag `v0.2.34` must point at that same commit, and `gh api repos/erekola/markdown-parity-check/commits/v0.2.34 --jq .sha` prints it. A mismatch is a reason not to use that version. Provenance proves which workflow built a release and from which commit. It does not prove that the code is safe, so reading the source and the dependencies stays your job.
|
|
252
255
|
|
|
253
256
|
## Security
|
|
254
257
|
|
package/SECURITY.md
CHANGED
|
@@ -14,7 +14,7 @@ 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. In the command line the same deadline also covers parsing and comparison, which run in a worker thread that is stopped when the deadline passes, and the tool then exits with code 2. The library entry point has no such deadline, so a program that compares untrusted documents with it needs a time limit of its own. JavaScript from fetched pages is not executed.
|
|
16
16
|
|
|
17
|
-
The
|
|
17
|
+
The number of block pairs is bounded by the product of the two block counts, at most 4 000 000. The time spent on each pair is not: the similarity search walks the distinct words of the HTML block once per pair, so the work grows with block pairs times distinct words per HTML block. One measured case, 100 HTML blocks of 870 distinct words each against 40 000 Markdown blocks of one word each, which is 4 000 000 pairs, took between 26 and 30 seconds with default limits on development machines, in two measurements by two people. The command line stops such a run at its deadline. 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. The maxSimilarityWork limit is unbounded by default and covers both cases, so a library caller that compares untrusted documents should set it. In the case above, a limit of 2 000 000 made the pairing step stop after about 70 milliseconds, on top of the time spent parsing the two documents, and the whole call took under one second. The comparison functions `align` and `compare` throw an `AlignmentLimitError` there, while `run` turns it into a `RunError` with the same message, which the command line reports with exit code 2.
|
|
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
|
|
package/dist/src/align.js
CHANGED
|
@@ -16,6 +16,11 @@ export function strictKey(b) {
|
|
|
16
16
|
function looseKey(b) {
|
|
17
17
|
return `${typeGroup(b)} ${b.loose}`;
|
|
18
18
|
}
|
|
19
|
+
/** The link targets of a block, with their texts, in order. Blocks with equal text and equal link signatures are the
|
|
20
|
+
* same block as far as the links go, so the alignment prefers them over equal-text blocks with other targets (MP-13). */
|
|
21
|
+
function linkSignature(b) {
|
|
22
|
+
return b.links.map((l) => `${l.text}\x1f${l.resolved ?? l.rawHref}`).join('\x1e');
|
|
23
|
+
}
|
|
19
24
|
export const SIMILARITY_THRESHOLD = 0.6;
|
|
20
25
|
export const UNCERTAIN_THRESHOLD = 0.8;
|
|
21
26
|
/** Upper bound on the alignment work, as the product of the HTML and Markdown block counts. The LCS
|
|
@@ -84,10 +89,17 @@ export function checkAlignmentLimit(htmlBlocks, markdownBlocks, maxPairs = MAX_A
|
|
|
84
89
|
throw new AlignmentLimitError(`Comparison limit exceeded: ${htmlBlocks} HTML blocks by ${markdownBlocks} Markdown blocks is ${pairs} block pairs, above the limit of ${maxPairs}. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
85
90
|
}
|
|
86
91
|
}
|
|
87
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Longest common subsequence of the strict keys. Among the chains of the same length it takes the one with the most
|
|
94
|
+
* pairs whose link signatures agree (MP-13): a match weighs W, a match with equal link signatures W + 1, and W is
|
|
95
|
+
* larger than the number of possible bonuses, so the length of the chain is decided first and the targets only break
|
|
96
|
+
* ties. Without links on either side every bonus is equal and the chain is the one the plain table gave.
|
|
97
|
+
*/
|
|
98
|
+
function lcs(keysA, keysB, sigA, sigB, maxPairs) {
|
|
88
99
|
const n = keysA.length;
|
|
89
100
|
const m = keysB.length;
|
|
90
101
|
checkAlignmentLimit(n, m, maxPairs);
|
|
102
|
+
const weight = Math.min(n, m) + 1;
|
|
91
103
|
const dp = [];
|
|
92
104
|
for (let i = 0; i <= n; i++)
|
|
93
105
|
dp.push(new Uint32Array(m + 1));
|
|
@@ -95,14 +107,20 @@ function lcs(keysA, keysB, maxPairs) {
|
|
|
95
107
|
const row = dp[i];
|
|
96
108
|
const next = dp[i + 1];
|
|
97
109
|
for (let j = m - 1; j >= 0; j--) {
|
|
98
|
-
|
|
110
|
+
let best = Math.max(next[j], row[j + 1]);
|
|
111
|
+
if (keysA[i] === keysB[j]) {
|
|
112
|
+
const take = next[j + 1] + weight + (sigA[i] === sigB[j] ? 1 : 0);
|
|
113
|
+
if (take > best)
|
|
114
|
+
best = take;
|
|
115
|
+
}
|
|
116
|
+
row[j] = best;
|
|
99
117
|
}
|
|
100
118
|
}
|
|
101
119
|
const out = [];
|
|
102
120
|
let i = 0;
|
|
103
121
|
let j = 0;
|
|
104
122
|
while (i < n && j < m) {
|
|
105
|
-
if (keysA[i] === keysB[j]) {
|
|
123
|
+
if (keysA[i] === keysB[j] && dp[i][j] === dp[i + 1][j + 1] + weight + (sigA[i] === sigB[j] ? 1 : 0)) {
|
|
106
124
|
out.push([i, j]);
|
|
107
125
|
i++;
|
|
108
126
|
j++;
|
|
@@ -172,7 +190,7 @@ export function align(a, b, limits) {
|
|
|
172
190
|
const usedB = new Set();
|
|
173
191
|
const keysA = a.map(strictKey);
|
|
174
192
|
const keysB = b.map(strictKey);
|
|
175
|
-
for (const [i, j] of lcs(keysA, keysB, lim.maxAlignmentPairs)) {
|
|
193
|
+
for (const [i, j] of lcs(keysA, keysB, a.map(linkSignature), b.map(linkSignature), lim.maxAlignmentPairs)) {
|
|
176
194
|
pairs.push({ a: i, b: j, kind: 'exact', similarity: 1 });
|
|
177
195
|
usedA.add(i);
|
|
178
196
|
usedB.add(j);
|
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.
|
|
3
|
+
export declare const HELP = "markdown-parity-check 0.2.34\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> Timeout in milliseconds for each fetch and for the parse-and-compare step\n (default: 15000). When it runs out the exit code is 2.\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
|
@@ -396,7 +396,22 @@ export async function main(argv, io = { stdout: (s) => process.stdout.write(s),
|
|
|
396
396
|
}
|
|
397
397
|
const invokedDirectly = process.argv[1] !== undefined && samePath(path.resolve(process.argv[1]), fileURLToPath(import.meta.url));
|
|
398
398
|
if (invokedDirectly) {
|
|
399
|
+
// A reader that closes the pipe before the report is written (head -c 0, a pager that quit) makes the write fail with
|
|
400
|
+
// EPIPE. The report could not be delivered, which is a failed run: exit 2, as for every other report that cannot be
|
|
401
|
+
// written (MP-21). Without a listener the error was an unhandled event and the exit code was 1.
|
|
402
|
+
let outputFailed = false;
|
|
403
|
+
process.stdout.on('error', (err) => {
|
|
404
|
+
outputFailed = true;
|
|
405
|
+
process.exitCode = 2;
|
|
406
|
+
try {
|
|
407
|
+
process.stderr.write(redactText(`Error: Cannot write the report to stdout: ${err.code ?? err.message}\n`));
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
// stderr may be closed as well; the exit code carries the failure.
|
|
411
|
+
}
|
|
412
|
+
});
|
|
399
413
|
main(process.argv.slice(2)).then((code) => {
|
|
400
|
-
|
|
414
|
+
if (!outputFailed)
|
|
415
|
+
process.exitCode = code;
|
|
401
416
|
});
|
|
402
417
|
}
|
package/dist/src/compare.d.ts
CHANGED
|
@@ -30,11 +30,13 @@ export declare function diffNumbers(a: string[], b: string[]): {
|
|
|
30
30
|
* 1. Links whose text occurs equally often on both sides pair in document order: the first "download" with the
|
|
31
31
|
* first "download". Up to 0.2.12 every link took any unused link with the same text and target, so two links with
|
|
32
32
|
* the same text and swapped targets passed with no finding (0.2.13, found by an outside review 2026-09-26).
|
|
33
|
-
* 2.
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
33
|
+
* 2. Links whose text occurs a different number of times pair in order of occurrence too (MP-14). When the targets of
|
|
34
|
+
* the shorter side appear in the same order among the targets of the longer side, they pair with those, so a link
|
|
35
|
+
* added or removed anywhere is one addition or one missing link and nothing else. Otherwise the first links of the
|
|
36
|
+
* two sides pair by position and the surplus is missing or added, so a swap that comes with an added link is two
|
|
37
|
+
* target changes and an addition. Up to 0.2.33 each HTML link took the first Markdown link with the same text and
|
|
38
|
+
* target, which paired such a swap as no change and hid it. Every target comparison counts as work, so maxWork bounds
|
|
39
|
+
* the total the way maxSimilarityWork bounds align's own similarity search (0.2.16).
|
|
38
40
|
* 3. What is still unpaired pairs by loosely normalized text, the same way as step 1 and then in order, so a link
|
|
39
41
|
* whose text differs only in case or punctuation is one changed text and not a missing and an added link (0.2.13).
|
|
40
42
|
* @internal Exported for test/compare-links.test.ts.
|
package/dist/src/compare.js
CHANGED
|
@@ -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 { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, visibleNumbers } from './normalize.js';
|
|
3
|
+
import { codeWhitespaceKey, excerpt, hrefDifference, looseNormalize, maskHref, redactText, relativeHrefRelation, textKey, trimHref, 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();
|
|
@@ -64,93 +64,86 @@ const linkHref = (l, href) => (l.masked ? '***' : maskHref(href));
|
|
|
64
64
|
* 1. Links whose text occurs equally often on both sides pair in document order: the first "download" with the
|
|
65
65
|
* first "download". Up to 0.2.12 every link took any unused link with the same text and target, so two links with
|
|
66
66
|
* the same text and swapped targets passed with no finding (0.2.13, found by an outside review 2026-09-26).
|
|
67
|
-
* 2.
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
67
|
+
* 2. Links whose text occurs a different number of times pair in order of occurrence too (MP-14). When the targets of
|
|
68
|
+
* the shorter side appear in the same order among the targets of the longer side, they pair with those, so a link
|
|
69
|
+
* added or removed anywhere is one addition or one missing link and nothing else. Otherwise the first links of the
|
|
70
|
+
* two sides pair by position and the surplus is missing or added, so a swap that comes with an added link is two
|
|
71
|
+
* target changes and an addition. Up to 0.2.33 each HTML link took the first Markdown link with the same text and
|
|
72
|
+
* target, which paired such a swap as no change and hid it. Every target comparison counts as work, so maxWork bounds
|
|
73
|
+
* the total the way maxSimilarityWork bounds align's own similarity search (0.2.16).
|
|
72
74
|
* 3. What is still unpaired pairs by loosely normalized text, the same way as step 1 and then in order, so a link
|
|
73
75
|
* whose text differs only in case or punctuation is one changed text and not a missing and an added link (0.2.13).
|
|
74
76
|
* @internal Exported for test/compare-links.test.ts.
|
|
75
77
|
*/
|
|
76
78
|
export function pairLinks(hLinks, mLinks, maxWork = Number.POSITIVE_INFINITY) {
|
|
77
79
|
const used = new Array(mLinks.length).fill(false);
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
80
|
+
const byText = (links) => {
|
|
81
|
+
const out = new Map();
|
|
82
|
+
links.forEach((l, i) => {
|
|
83
|
+
const list = out.get(l.text);
|
|
84
|
+
if (list)
|
|
85
|
+
list.push(i);
|
|
86
|
+
else
|
|
87
|
+
out.set(l.text, [i]);
|
|
88
|
+
});
|
|
89
|
+
return out;
|
|
87
90
|
};
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return
|
|
91
|
+
const hByText = byText(hLinks);
|
|
92
|
+
const mByText = byText(mLinks);
|
|
93
|
+
let work = 0;
|
|
94
|
+
const same = (hi, mi) => {
|
|
95
|
+
work++;
|
|
96
|
+
if (work > maxWork) {
|
|
97
|
+
throw new AlignmentLimitError(`Comparison limit exceeded: pairing links by shared text 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.`);
|
|
98
|
+
}
|
|
99
|
+
return sameTarget(hLinks[hi], mLinks[mi]);
|
|
97
100
|
};
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
101
|
+
/** For each index of `small`, in order, the index in `big` of the first later link with the same target; null when one has none. */
|
|
102
|
+
const inOrder = (small, big, match) => {
|
|
103
|
+
const out = [];
|
|
104
|
+
let j = 0;
|
|
105
|
+
for (const s of small) {
|
|
106
|
+
while (j < big.length && !match(s, big[j]))
|
|
107
|
+
j++;
|
|
108
|
+
if (j === big.length)
|
|
109
|
+
return null;
|
|
110
|
+
out.push(big[j]);
|
|
111
|
+
j++;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
110
114
|
};
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
hLinks.forEach((hl, hi) => {
|
|
121
|
-
let idx = -1;
|
|
122
|
-
const k = seenInH.get(hl.text) ?? 0;
|
|
123
|
-
seenInH.set(hl.text, k + 1);
|
|
124
|
-
if (hCount.get(hl.text) === mCount.get(hl.text)) {
|
|
125
|
-
idx = lists.get(key('text', hl.text))[k];
|
|
115
|
+
const planned = new Array(hLinks.length).fill(-1);
|
|
116
|
+
for (const [text, hIdx] of hByText) {
|
|
117
|
+
const mIdx = mByText.get(text);
|
|
118
|
+
if (!mIdx)
|
|
119
|
+
continue;
|
|
120
|
+
if (hIdx.length === mIdx.length) {
|
|
121
|
+
hIdx.forEach((hi, k) => {
|
|
122
|
+
planned[hi] = mIdx[k];
|
|
123
|
+
});
|
|
126
124
|
}
|
|
127
|
-
else if (
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
125
|
+
else if (hIdx.length < mIdx.length) {
|
|
126
|
+
const hit = inOrder(hIdx, mIdx, same);
|
|
127
|
+
hIdx.forEach((hi, k) => {
|
|
128
|
+
planned[hi] = hit ? hit[k] : mIdx[k];
|
|
129
|
+
});
|
|
132
130
|
}
|
|
133
131
|
else {
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
throw new AlignmentLimitError(`Comparison limit exceeded: pairing unresolved links by shared text 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.`);
|
|
139
|
-
}
|
|
140
|
-
if (!used[i] && sameTarget(hl, mLinks[i])) {
|
|
141
|
-
idx = i;
|
|
142
|
-
break;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
132
|
+
const hit = inOrder(mIdx, hIdx, (mi, hi) => same(hi, mi));
|
|
133
|
+
mIdx.forEach((mi, k) => {
|
|
134
|
+
planned[hit ? hit[k] : hIdx[k]] = mi;
|
|
135
|
+
});
|
|
145
136
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
137
|
+
}
|
|
138
|
+
const pairs = [];
|
|
139
|
+
let missing = [];
|
|
140
|
+
planned.forEach((mi, hi) => {
|
|
141
|
+
if (mi < 0) {
|
|
149
142
|
missing.push(hi);
|
|
150
143
|
return;
|
|
151
144
|
}
|
|
152
|
-
used[
|
|
153
|
-
pairs.push([hi,
|
|
145
|
+
used[mi] = true;
|
|
146
|
+
pairs.push([hi, mi]);
|
|
154
147
|
});
|
|
155
148
|
// Step 3: the links still unpaired, by loosely normalized text.
|
|
156
149
|
const looseLists = new Map();
|
|
@@ -264,7 +257,7 @@ function sameTarget(a, b) {
|
|
|
264
257
|
return a.resolved === b.resolved;
|
|
265
258
|
if (a.resolved === null && b.resolved === null)
|
|
266
259
|
return relativeHrefRelation(a.rawHref, b.rawHref) === 'same';
|
|
267
|
-
return a.rawHref
|
|
260
|
+
return trimHref(a.rawHref) === trimHref(b.rawHref);
|
|
268
261
|
}
|
|
269
262
|
/**
|
|
270
263
|
* Where a list item sits in its list (0.2.13): the list kind and the nesting level are warnings, a changed item
|
|
@@ -364,15 +357,17 @@ function comparePair(out, p, h, m, bothBases, maxSimilarityWork) {
|
|
|
364
357
|
out.push({ code: 'NUMBER_CHANGED', severity: 'error', direction: 'both', message: `Numeric value differs in the ${label(h)} inside a masked part of a URL (a query value, the fragment or user information), so the values are not shown.`, html: side(h), markdown: side(m) });
|
|
365
358
|
}
|
|
366
359
|
}
|
|
367
|
-
else if (h.
|
|
360
|
+
else if (textKey(h.text) === textKey(m.text)) {
|
|
361
|
+
// The text key keeps the marks and symbols the alignment key drops (MP-11).
|
|
368
362
|
out.push({ code: 'TEXT_MINOR_CHANGED', severity: 'warning', direction: 'both', message: `The ${label(h)} differs only in case, punctuation or typographic characters.`, html: side(h), markdown: side(m), before: excerpt(h.text), after: excerpt(m.text) });
|
|
369
363
|
}
|
|
370
364
|
else {
|
|
371
365
|
out.push({ code: 'TEXT_CHANGED', severity: 'error', direction: 'both', message: `The ${label(h)} text differs.`, html: side(h), markdown: side(m), before: excerpt(h.text), after: excerpt(m.text) });
|
|
372
366
|
}
|
|
373
367
|
}
|
|
374
|
-
|
|
375
|
-
|
|
368
|
+
// Any block can carry the list context of its item (a heading, code or a table that leads it, MP-06); the function
|
|
369
|
+
// returns at once for a block without one.
|
|
370
|
+
compareListItems(out, h, m);
|
|
376
371
|
compareLinks(out, h, m, bothBases, maxSimilarityWork);
|
|
377
372
|
}
|
|
378
373
|
const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
|
package/dist/src/fetch.js
CHANGED
|
@@ -6,8 +6,9 @@ import http from 'node:http';
|
|
|
6
6
|
import https from 'node:https';
|
|
7
7
|
import dns from 'node:dns';
|
|
8
8
|
import zlib from 'node:zlib';
|
|
9
|
-
import { assertPublicHost, assertPublicResolved, BlockedAddressError } from './netguard.js';
|
|
9
|
+
import { assertPublicHost, assertPublicResolved, BlockedAddressError, ipVersion } from './netguard.js';
|
|
10
10
|
import { maskUrl, redactText } from './normalize.js';
|
|
11
|
+
import { TOOL_NAME, TOOL_VERSION } from './version.js';
|
|
11
12
|
export class FetchError extends Error {
|
|
12
13
|
kind;
|
|
13
14
|
url;
|
|
@@ -42,6 +43,16 @@ async function pickAddress(hostname, options) {
|
|
|
42
43
|
const allowed = (options.testAllowHosts ?? []).includes(hostname.toLowerCase());
|
|
43
44
|
if (!allowed)
|
|
44
45
|
assertPublicHost(hostname);
|
|
46
|
+
// A bracketed IPv6 literal is an address and not a name (MP-20): it never goes to DNS, where the brackets made the
|
|
47
|
+
// lookup a name lookup of a string that is no name. The policy runs on the literal itself before any connection.
|
|
48
|
+
if (hostname.startsWith('[') && hostname.endsWith(']')) {
|
|
49
|
+
const literal = hostname.slice(1, -1);
|
|
50
|
+
if (ipVersion(literal) === 6) {
|
|
51
|
+
if (!allowed)
|
|
52
|
+
assertPublicResolved(hostname, literal);
|
|
53
|
+
return { address: literal, family: 6 };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
45
56
|
const resolver = options.resolver ?? defaultResolver;
|
|
46
57
|
let answers;
|
|
47
58
|
try {
|
|
@@ -59,9 +70,55 @@ async function pickAddress(hostname, options) {
|
|
|
59
70
|
}
|
|
60
71
|
return answers[0];
|
|
61
72
|
}
|
|
62
|
-
|
|
73
|
+
/** A decoder for an encoding label, or null when the runtime does not know the label. */
|
|
74
|
+
function decoderFor(label) {
|
|
75
|
+
try {
|
|
76
|
+
return new TextDecoder(label, { fatal: false });
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function headerCharset(contentType) {
|
|
63
83
|
const m = /charset=([^;]+)/i.exec(contentType ?? '');
|
|
64
|
-
|
|
84
|
+
return m?.[1] === undefined ? null : m[1].trim().replace(/^"|"$/g, '').toLowerCase();
|
|
85
|
+
}
|
|
86
|
+
/** The encoding a HTML page declares in a meta element among its first 1024 bytes (the HTML standard's prescan). A
|
|
87
|
+
* comment is skipped, and a declared UTF-16 is read as UTF-8, because a page that can be read this far as ASCII is not
|
|
88
|
+
* UTF-16. */
|
|
89
|
+
function metaCharset(buf) {
|
|
90
|
+
const head = buf.subarray(0, 1024).toString('latin1').replace(/<!--[\s\S]*?(?:-->|$)/g, '');
|
|
91
|
+
for (const tag of head.matchAll(/<meta\b[^>]*>?/gi)) {
|
|
92
|
+
const m = /charset\s*=\s*["']?\s*([^\s"'>;/]+)/i.exec(tag[0]);
|
|
93
|
+
if (!m)
|
|
94
|
+
continue;
|
|
95
|
+
const label = m[1].toLowerCase();
|
|
96
|
+
if (decoderFor(label))
|
|
97
|
+
return label.startsWith('utf-16') ? 'utf-8' : label;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
/** HTML is decoded the way the HTML standard orders the evidence: a byte order mark, then the charset of the
|
|
102
|
+
* Content-Type header, then the meta declaration, and UTF-8 when none of them names an encoding the runtime knows
|
|
103
|
+
* (MP-18). The standard's own default is windows-1252; UTF-8 is this tool's default for pages that say nothing. */
|
|
104
|
+
function decodeHtml(buf, contentType) {
|
|
105
|
+
const bom = buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 'utf-8' : buf[0] === 0xff && buf[1] === 0xfe ? 'utf-16le' : buf[0] === 0xfe && buf[1] === 0xff ? 'utf-16be' : null;
|
|
106
|
+
const fromBom = bom === null ? null : decoderFor(bom);
|
|
107
|
+
if (fromBom)
|
|
108
|
+
return fromBom.decode(buf);
|
|
109
|
+
const header = headerCharset(contentType);
|
|
110
|
+
const fromHeader = header === null ? null : decoderFor(header);
|
|
111
|
+
if (fromHeader)
|
|
112
|
+
return fromHeader.decode(buf);
|
|
113
|
+
const meta = metaCharset(buf);
|
|
114
|
+
const fromMeta = meta === null ? null : decoderFor(meta);
|
|
115
|
+
return (fromMeta ?? new TextDecoder('utf-8')).decode(buf);
|
|
116
|
+
}
|
|
117
|
+
function decodeBody(buf, contentType) {
|
|
118
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
119
|
+
if (type === 'text/html' || type === 'application/xhtml+xml')
|
|
120
|
+
return decodeHtml(buf, contentType);
|
|
121
|
+
const charset = headerCharset(contentType) ?? 'utf-8';
|
|
65
122
|
try {
|
|
66
123
|
return new TextDecoder(charset, { fatal: false }).decode(buf);
|
|
67
124
|
}
|
|
@@ -133,8 +190,11 @@ class Deadline {
|
|
|
133
190
|
if (this.expired)
|
|
134
191
|
req.destroy(this.error);
|
|
135
192
|
}
|
|
136
|
-
|
|
137
|
-
|
|
193
|
+
/** Forgets the request only if it is still the active one. The close event of a redirect hop fires after the
|
|
194
|
+
* next hop was attached, so an unconditional reset left the next hop outside the deadline. */
|
|
195
|
+
detach(req) {
|
|
196
|
+
if (this.active === req)
|
|
197
|
+
this.active = null;
|
|
138
198
|
}
|
|
139
199
|
/** Races a promise against the deadline. */
|
|
140
200
|
race(p) {
|
|
@@ -175,7 +235,7 @@ function requestOnce(url, address, options, deadline) {
|
|
|
175
235
|
headers: {
|
|
176
236
|
Accept: options.accept,
|
|
177
237
|
'Accept-Encoding': 'gzip, deflate, br',
|
|
178
|
-
'User-Agent': options.userAgent ??
|
|
238
|
+
'User-Agent': options.userAgent ?? `${TOOL_NAME}/${TOOL_VERSION} (+local content comparison)`,
|
|
179
239
|
},
|
|
180
240
|
// Explicit default: TLS verification is never disabled.
|
|
181
241
|
rejectUnauthorized: true,
|
|
@@ -245,7 +305,7 @@ function requestOnce(url, address, options, deadline) {
|
|
|
245
305
|
else
|
|
246
306
|
reject(new FetchError('network', url.href, err.message));
|
|
247
307
|
});
|
|
248
|
-
req.on('close', () => deadline.detach());
|
|
308
|
+
req.on('close', () => deadline.detach(req));
|
|
249
309
|
deadline.attach(req);
|
|
250
310
|
req.end();
|
|
251
311
|
});
|
package/dist/src/html.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export declare function nestingDepth(node: ParentNode): number;
|
|
|
29
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
30
|
* it is in an HTML paragraph (0.2.22, found by an outside review 2026-10-02). */
|
|
31
31
|
export declare function opensExcludedSubtree(name: string, attribs: Record<string, string>): boolean;
|
|
32
|
+
export declare const BLOCK_TAGS: Set<string>;
|
|
32
33
|
/** The nesting limit was exceeded. A subclass so a caller that otherwise tolerates a parse failure (raw HTML
|
|
33
34
|
* inside Markdown) can tell a limit from any other failure and let the limit through. */
|
|
34
35
|
export declare class HtmlDepthError extends HtmlExtractError {
|
package/dist/src/html.js
CHANGED
|
@@ -52,7 +52,7 @@ export function opensExcludedSubtree(name, attribs) {
|
|
|
52
52
|
return true;
|
|
53
53
|
return SKIP_ROLES.has((attribs['role'] ?? '').toLowerCase());
|
|
54
54
|
}
|
|
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']);
|
|
55
|
+
export 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']);
|
|
56
56
|
const HEADING_RE = /^h([1-6])$/;
|
|
57
57
|
function lineOf(ctx, node) {
|
|
58
58
|
const idx = node.startIndex;
|
|
@@ -428,7 +428,9 @@ function taskState(li, profile = 'generic') {
|
|
|
428
428
|
continue;
|
|
429
429
|
// The checkbox itself is the one skipped tag whose state is wanted; a hidden one is still ignored.
|
|
430
430
|
if (node.name === 'input' && (node.attribs['type'] ?? '').toLowerCase() === 'checkbox') {
|
|
431
|
-
|
|
431
|
+
// The checkbox's own role counts as well: a checkbox with an excluded role (navigation, dialog and the rest of
|
|
432
|
+
// SKIP_ROLES) is left out like any other element with that role, so it cannot answer for the item (MP-10).
|
|
433
|
+
if (hiddenAttr(node) || SKIP_ROLES.has((node.attribs['role'] ?? '').toLowerCase()))
|
|
432
434
|
continue;
|
|
433
435
|
return node.attribs['checked'] !== undefined;
|
|
434
436
|
}
|
|
@@ -452,6 +454,9 @@ function handleListItem(ctx, li) {
|
|
|
452
454
|
if (child instanceof Element && isSkipped(child, ctx.root, ctx.profile))
|
|
453
455
|
continue;
|
|
454
456
|
const blockAnchor = child instanceof Element && isBlockAnchor(ctx, child) && !isParagraphOnlyAnchor(ctx, child);
|
|
457
|
+
// An item with no text of its own that starts with a heading, code or a table carries its list context on that
|
|
458
|
+
// first block, as the Markdown side does for the first child of an item (MP-06).
|
|
459
|
+
let leading = false;
|
|
455
460
|
if (child instanceof Element && (BLOCK_TAGS.has(child.name) || blockAnchor || (ctx.profile === 'starlight' && child.name === 'starlight-tabs'))) {
|
|
456
461
|
if (!ownFlushed && child.name === 'p' && !hasBlockChild(ctx, child) && strictNormalize(run.text) === '') {
|
|
457
462
|
for (const c of child.children)
|
|
@@ -461,7 +466,9 @@ function handleListItem(ctx, li) {
|
|
|
461
466
|
continue;
|
|
462
467
|
}
|
|
463
468
|
if (!ownFlushed) {
|
|
469
|
+
const pushed = ctx.blocks.length;
|
|
464
470
|
flushRun(ctx, run, li, 'listItem', info);
|
|
471
|
+
leading = ctx.blocks.length === pushed && (HEADING_RE.test(child.name) || child.name === 'pre' || child.name === 'table');
|
|
465
472
|
ownFlushed = true;
|
|
466
473
|
run = newRun();
|
|
467
474
|
}
|
|
@@ -469,7 +476,11 @@ function handleListItem(ctx, li) {
|
|
|
469
476
|
flushRun(ctx, run, li, 'paragraph');
|
|
470
477
|
run = newRun();
|
|
471
478
|
}
|
|
479
|
+
const first = ctx.blocks.length;
|
|
472
480
|
handleBlock(ctx, child);
|
|
481
|
+
const lead = ctx.blocks[first];
|
|
482
|
+
if (leading && lead && ctx.blocks.length > first && lead.list === undefined)
|
|
483
|
+
lead.list = { ...info };
|
|
473
484
|
}
|
|
474
485
|
else {
|
|
475
486
|
inlineText(ctx, child, run);
|
|
@@ -800,16 +811,19 @@ export function extractHtml(source, options = {}) {
|
|
|
800
811
|
}
|
|
801
812
|
const { root, strategy, confidence } = pickRoot(doc, options.selector, notes, issues);
|
|
802
813
|
const lineStarts = [0];
|
|
803
|
-
|
|
804
|
-
|
|
814
|
+
// A line break is LF, CRLF or a lone CR, as the Markdown parser counts them: the CR of a CRLF pair is not a second one.
|
|
815
|
+
for (let i = 0; i < source.length; i++) {
|
|
816
|
+
const c = source.charCodeAt(i);
|
|
817
|
+
if (c === 10 || (c === 13 && source.charCodeAt(i + 1) !== 10))
|
|
805
818
|
lineStarts.push(i + 1);
|
|
819
|
+
}
|
|
806
820
|
if (profile === 'starlight')
|
|
807
821
|
notes.push('Starlight profile: all associated tab panels are compared, including inactive panels; Expressive Code line boundaries and aside titles are retained.');
|
|
808
822
|
const ctx = { profile, base, source, lineStarts, blocks: [], notes, root, listBase: 0, ordinals: new Map(), segments: new Map(), issues };
|
|
809
823
|
// A selector that picks a heading, list item, table or pre keeps that block type, so the root goes
|
|
810
824
|
// through handleBlock. Every other root is read as a container, a list included: handleBlock's list
|
|
811
825
|
// branch reads only <li> children, and a root list would lose any other content it holds.
|
|
812
|
-
if (HEADING_RE.test(root.name) || root.name === 'li' || root.name === 'table' || root.name === 'pre')
|
|
826
|
+
if (HEADING_RE.test(root.name) || root.name === 'li' || root.name === 'table' || root.name === 'pre' || (profile === 'starlight' && root.name === 'starlight-tabs'))
|
|
813
827
|
handleBlock(ctx, root);
|
|
814
828
|
else
|
|
815
829
|
walk(ctx, root);
|
package/dist/src/markdown.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
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, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
|
|
5
|
+
import { BLOCK_TAGS, extractHtml, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
|
|
6
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';
|
|
@@ -31,13 +31,33 @@ function parseInlineTag(value) {
|
|
|
31
31
|
const m = /^<\/([A-Za-z][A-Za-z0-9-]*)\s*>$/.exec(v);
|
|
32
32
|
return m ? { name: m[1].toLowerCase(), closing: true, attribs: {} } : null;
|
|
33
33
|
}
|
|
34
|
-
|
|
34
|
+
const tag = singleOpenTag(v);
|
|
35
|
+
if (!tag)
|
|
35
36
|
return null;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
return { name: tag.name.toLowerCase(), closing: false, selfClosing: /\/\s*>$/.test(v), attribs: tag.attribs };
|
|
38
|
+
}
|
|
39
|
+
/** The one opening tag a string consists of, found by the HTML tokenizer so that a quoted attribute value may hold a
|
|
40
|
+
* ">" (title="A > B"); null when the string is anything else: text after the tag, a comment, a tag still open at the
|
|
41
|
+
* end. The first version looked for the closing ">" with a pattern and cut the tag at a quoted one (MP-02). */
|
|
42
|
+
function singleOpenTag(v) {
|
|
43
|
+
if (!/^<[A-Za-z]/.test(v))
|
|
39
44
|
return null;
|
|
40
|
-
|
|
45
|
+
const seen = { tag: null, extra: false };
|
|
46
|
+
const parser = new Parser({
|
|
47
|
+
onopentag(name, attribs) {
|
|
48
|
+
if (seen.tag)
|
|
49
|
+
seen.extra = true;
|
|
50
|
+
else
|
|
51
|
+
seen.tag = { name, attribs, end: parser.endIndex };
|
|
52
|
+
},
|
|
53
|
+
ontext() { seen.extra = true; },
|
|
54
|
+
oncomment() { seen.extra = true; },
|
|
55
|
+
onprocessinginstruction() { seen.extra = true; },
|
|
56
|
+
}, { decodeEntities: true });
|
|
57
|
+
parser.write(v);
|
|
58
|
+
if (!seen.tag || seen.extra || seen.tag.end !== v.length - 1)
|
|
59
|
+
return null;
|
|
60
|
+
return { name: seen.tag.name, attribs: seen.tag.attribs };
|
|
41
61
|
}
|
|
42
62
|
/**
|
|
43
63
|
* Walks phrasing children in order so that inline HTML anchors (<a href="..">text</a>) become links with
|
|
@@ -229,9 +249,16 @@ function push(ctx, partial, node) {
|
|
|
229
249
|
numbers: extractNumbers(partial.text),
|
|
230
250
|
location: { line, blockIndex: ctx.blocks.length },
|
|
231
251
|
};
|
|
252
|
+
// A visible raw <a href> left open by an earlier raw HTML block links the blocks inside it, the way the HTML side
|
|
253
|
+
// gives every block of a block anchor the anchor's link with the block's own text; the outermost link comes first (MP-08).
|
|
254
|
+
for (let i = ctx.wrappers.length - 1; i >= 0; i--) {
|
|
255
|
+
const href = ctx.wrappers[i].href;
|
|
256
|
+
if (href !== undefined)
|
|
257
|
+
block.links.unshift({ text: strictNormalize(block.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
|
|
258
|
+
}
|
|
232
259
|
ctx.blocks.push(block);
|
|
233
260
|
}
|
|
234
|
-
function handleTable(ctx, table) {
|
|
261
|
+
function handleTable(ctx, table, listItem) {
|
|
235
262
|
const cells = [];
|
|
236
263
|
const links = [];
|
|
237
264
|
for (const row of table.children) {
|
|
@@ -247,8 +274,9 @@ function handleTable(ctx, table) {
|
|
|
247
274
|
if (cells.length === 0)
|
|
248
275
|
return;
|
|
249
276
|
const text = cells.map((r) => r.join(' | ')).join(' \n ');
|
|
250
|
-
push(ctx, { type: 'table', text: strictNormalize(text), cells, links }, table);
|
|
277
|
+
push(ctx, { type: 'table', text: strictNormalize(text), cells, links, ...(listItem ? { list: listItem } : {}) }, table);
|
|
251
278
|
}
|
|
279
|
+
const LEADING_TYPES = new Set(['paragraph', 'heading', 'code', 'table', 'html']);
|
|
252
280
|
function handle(ctx, node, listItem) {
|
|
253
281
|
switch (node.type) {
|
|
254
282
|
case 'heading': {
|
|
@@ -258,7 +286,7 @@ function handle(ctx, node, listItem) {
|
|
|
258
286
|
inlineChildren(ctx, node.children, run, node.position?.start.line);
|
|
259
287
|
const text = strictNormalize(run.text);
|
|
260
288
|
if (text !== '')
|
|
261
|
-
push(ctx, { type: 'heading', text, depth: node.depth, links: run.links }, node);
|
|
289
|
+
push(ctx, { type: 'heading', text, depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
|
|
262
290
|
return;
|
|
263
291
|
}
|
|
264
292
|
case 'paragraph': {
|
|
@@ -276,12 +304,12 @@ function handle(ctx, node, listItem) {
|
|
|
276
304
|
return;
|
|
277
305
|
const code = normalizeCode(node.value);
|
|
278
306
|
if (code.trim() !== '')
|
|
279
|
-
push(ctx, { type: 'code', text: strictNormalize(code), code, links: [] }, node);
|
|
307
|
+
push(ctx, { type: 'code', text: strictNormalize(code), code, links: [], ...(listItem ? { list: listItem } : {}) }, node);
|
|
280
308
|
return;
|
|
281
309
|
}
|
|
282
310
|
case 'table':
|
|
283
311
|
if (!hiddenWrapped(ctx))
|
|
284
|
-
handleTable(ctx, node);
|
|
312
|
+
handleTable(ctx, node, listItem);
|
|
285
313
|
return;
|
|
286
314
|
case 'list': {
|
|
287
315
|
// A Markdown list shows its start number and counts on; its items carry the list kind, the nesting level and
|
|
@@ -295,7 +323,9 @@ function handle(ctx, node, listItem) {
|
|
|
295
323
|
ctx.listDepth++;
|
|
296
324
|
let first = true;
|
|
297
325
|
for (const child of item.children) {
|
|
298
|
-
|
|
326
|
+
// The first child carries the item's list context whatever it is: a paragraph is the item text, a heading,
|
|
327
|
+
// code, a table or raw HTML keep their own type with the context on them (MP-05, MP-06).
|
|
328
|
+
handle(ctx, child, first && LEADING_TYPES.has(child.type) ? info : undefined);
|
|
299
329
|
first = false;
|
|
300
330
|
}
|
|
301
331
|
ctx.listDepth--;
|
|
@@ -307,7 +337,7 @@ function handle(ctx, node, listItem) {
|
|
|
307
337
|
handle(ctx, c);
|
|
308
338
|
return;
|
|
309
339
|
case 'html':
|
|
310
|
-
handleRawHtml(ctx, node.value, node.position?.start.line);
|
|
340
|
+
handleRawHtml(ctx, node.value, node.position?.start.line, listItem);
|
|
311
341
|
return;
|
|
312
342
|
case 'footnoteDefinition':
|
|
313
343
|
if (hiddenWrapped(ctx))
|
|
@@ -337,12 +367,19 @@ function footnoteText(node) {
|
|
|
337
367
|
}
|
|
338
368
|
/** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
|
|
339
369
|
* comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
|
|
340
|
-
function handleRawHtml(ctx, value, line) {
|
|
370
|
+
function handleRawHtml(ctx, value, line, listItem) {
|
|
341
371
|
// 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
|
|
343
|
-
|
|
344
|
-
const
|
|
345
|
-
|
|
372
|
+
// sees the same element tree a browser would and hides what a covering wrapper still holds (P07). A wrapper that
|
|
373
|
+
// hides is written with the hidden attribute whatever hid it, and an anchor with its href.
|
|
374
|
+
const prefix = ctx.wrappers.map((w) => `<${w.name}${w.covers ? ' hidden' : ''}${w.href !== undefined ? ` href="${w.href.replace(/&/g, '&').replace(/"/g, '"')}"` : ''}>`).join('');
|
|
375
|
+
// The stack always follows the prefix, because a closing tag here may end an element opened earlier. The extractor
|
|
376
|
+
// sees the prefix only while an open element hides content or links it: with nothing of the kind open the block is
|
|
377
|
+
// read on its own, as before (a long run of unclosed visible tags costs the stack but no tree per block).
|
|
378
|
+
const relevant = ctx.wrappers.some((w) => w.covers || w.href !== undefined);
|
|
379
|
+
ctx.wrappers = openWrappers(prefix + value);
|
|
380
|
+
if (ctx.wrappers.length > ctx.maxDepth)
|
|
381
|
+
throw new HtmlDepthError(ctx.wrappers.length, ctx.maxDepth);
|
|
382
|
+
const fragment = relevant ? prefix + value : value;
|
|
346
383
|
// Text check for the fallback warning, taken from the parsed DOM rather than from regex stripping:
|
|
347
384
|
// comments are not text, and script, style, template and noscript are page machinery on both sides,
|
|
348
385
|
// so their content does not count as skipped text. Hidden elements are left out, as in the extraction.
|
|
@@ -363,12 +400,24 @@ function handleRawHtml(ctx, value, line) {
|
|
|
363
400
|
}
|
|
364
401
|
const blocks = parsed?.blocks ?? [];
|
|
365
402
|
if (blocks.length > 0) {
|
|
403
|
+
let lead = listItem !== undefined && rawLeadsItem(value);
|
|
366
404
|
for (const b of blocks) {
|
|
367
405
|
// The wrapper <body> sits on the fragment's first line, so the extractor's line is 1-based within
|
|
368
406
|
// the fragment and maps onto the html node's start line.
|
|
369
407
|
const inner = b.location.line;
|
|
370
408
|
const absolute = line !== undefined && inner !== undefined ? line + inner - 1 : line;
|
|
371
|
-
|
|
409
|
+
let block = { ...b, location: { line: absolute, blockIndex: ctx.blocks.length } };
|
|
410
|
+
// A list inside a raw block sits below the Markdown list the block is in (MP-05).
|
|
411
|
+
if (block.list && ctx.listDepth > 0)
|
|
412
|
+
block = { ...block, list: { ...block.list, depth: block.list.depth + ctx.listDepth } };
|
|
413
|
+
// The first block of a raw block that leads a Markdown list item is the item's own text, or the item's leading
|
|
414
|
+
// heading, code or table, and carries the item's list context (MP-05, MP-06). A nested list there has its own.
|
|
415
|
+
if (lead) {
|
|
416
|
+
lead = false;
|
|
417
|
+
if (!block.list && listItem)
|
|
418
|
+
block = { ...block, ...(block.type === 'paragraph' ? { type: 'listItem' } : {}), list: { ...listItem } };
|
|
419
|
+
}
|
|
420
|
+
ctx.blocks.push(block);
|
|
372
421
|
}
|
|
373
422
|
// The nested extraction's own structural "not compared" issues (a spanned table, a reversed list) were
|
|
374
423
|
// read off parsed.blocks only up to here; parsed.issues was silently dropped, so a page whose span or
|
|
@@ -386,29 +435,61 @@ function handleRawHtml(ctx, value, line) {
|
|
|
386
435
|
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) });
|
|
387
436
|
}
|
|
388
437
|
}
|
|
389
|
-
|
|
390
|
-
|
|
438
|
+
/**
|
|
439
|
+
* Whether a raw HTML block that leads a Markdown list item is read as the item's own content, by the rule of html.ts
|
|
440
|
+
* handleListItem: the item's own text or inline content, a paragraph without block children, a heading, a pre or a
|
|
441
|
+
* table. Any other block element (div, blockquote, section, details, a list) is a block child of the item and gets no
|
|
442
|
+
* list context, as on the HTML side (N-1).
|
|
443
|
+
*/
|
|
444
|
+
function rawLeadsItem(value) {
|
|
445
|
+
for (const node of parseDocument(value).children) {
|
|
446
|
+
if (node instanceof Text) {
|
|
447
|
+
if (node.data.trim() !== '')
|
|
448
|
+
return true;
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (!(node instanceof Element))
|
|
452
|
+
continue;
|
|
453
|
+
const name = node.name.toLowerCase();
|
|
454
|
+
if (opensExcludedSubtree(name, node.attribs) || node.attribs['hidden'] !== undefined || node.attribs['aria-hidden'] === 'true')
|
|
455
|
+
continue;
|
|
456
|
+
if (name === 'p')
|
|
457
|
+
return !node.children.some((c) => c instanceof Element && BLOCK_TAGS.has(c.name.toLowerCase()));
|
|
458
|
+
if (/^h[1-6]$/.test(name) || name === 'pre' || name === 'table')
|
|
459
|
+
return true;
|
|
460
|
+
return !BLOCK_TAGS.has(name);
|
|
461
|
+
}
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
/** Whether a raw HTML wrapper from an earlier block that hides what it holds is still open. */
|
|
391
465
|
function hiddenWrapped(ctx) {
|
|
392
|
-
return ctx.wrappers.
|
|
466
|
+
return ctx.wrappers.some((w) => w.covers);
|
|
393
467
|
}
|
|
394
468
|
/**
|
|
395
|
-
* The elements still open at the end of a raw HTML fragment, from the outermost
|
|
396
|
-
*
|
|
397
|
-
*
|
|
469
|
+
* The elements still open at the end of a raw HTML fragment, all of them from the outermost. An element hides content
|
|
470
|
+
* when it is hidden or aria-hidden or the HTML side leaves its subtree out (a nav, a form, a role such as navigation);
|
|
471
|
+
* a visible anchor with an href links what it holds. The visible elements are kept as well, because an element opened
|
|
472
|
+
* in an earlier block can be hidden or linked only by a later one, and because their closing tags close what is open
|
|
473
|
+
* inside them: </ul> ends an open <li hidden> (MP-07). The parser is not ended, because ending it closes every open
|
|
474
|
+
* element and the open ones are the answer. The stack is written in front of every following raw block, so the caller
|
|
475
|
+
* stops the comparison when it is deeper than the nesting limit, as the same nesting is on the HTML side.
|
|
398
476
|
*/
|
|
399
477
|
function openWrappers(fragment) {
|
|
400
478
|
const stack = [];
|
|
401
479
|
const parser = new Parser({
|
|
402
480
|
onopentag(name, attribs) {
|
|
403
|
-
|
|
481
|
+
const covers = attribs['hidden'] !== undefined || attribs['aria-hidden'] === 'true' || opensExcludedSubtree(name, attribs);
|
|
482
|
+
const wrapper = { name, covers };
|
|
483
|
+
if (name === 'a' && attribs['href'] !== undefined && !covers)
|
|
484
|
+
wrapper.href = attribs['href'];
|
|
485
|
+
stack.push(wrapper);
|
|
404
486
|
},
|
|
405
487
|
onclosetag() {
|
|
406
488
|
stack.pop();
|
|
407
489
|
},
|
|
408
490
|
}, { decodeEntities: true });
|
|
409
491
|
parser.write(fragment);
|
|
410
|
-
|
|
411
|
-
return first < 0 ? [] : stack.slice(first);
|
|
492
|
+
return stack;
|
|
412
493
|
}
|
|
413
494
|
/** Strictly normalized text of an HTML fragment as a parser sees it: text nodes only, comments and
|
|
414
495
|
* machinery elements excluded. */
|
|
@@ -419,7 +500,9 @@ function visibleText(fragment) {
|
|
|
419
500
|
if (node instanceof Text)
|
|
420
501
|
parts.push(node.data);
|
|
421
502
|
else if (node instanceof Element) {
|
|
422
|
-
|
|
503
|
+
// The subtrees the HTML side leaves out (script, style, template, noscript, nav, form, dialog, a role such as
|
|
504
|
+
// navigation and the rest of opensExcludedSubtree) are not text that was left unread (MP-04).
|
|
505
|
+
if (opensExcludedSubtree(node.name.toLowerCase(), node.attribs))
|
|
423
506
|
continue;
|
|
424
507
|
if (node.attribs['hidden'] !== undefined || node.attribs['aria-hidden'] === 'true')
|
|
425
508
|
continue;
|
package/dist/src/normalize.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
export declare function strictNormalize(text: string): string;
|
|
2
|
+
/** The key that aligns blocks: everything that is not a letter, a number or white space becomes a space, so two
|
|
3
|
+
* blocks that differ in punctuation, marks or symbols still pair. */
|
|
2
4
|
export declare function looseNormalize(text: string): string;
|
|
5
|
+
/** The key that classifies a text difference: the loose text, except that the marks (\p{M}) and the symbols (\p{S})
|
|
6
|
+
* are kept, because a different vowel sign, check mark, arrow, comparison or plus sign shows the reader something
|
|
7
|
+
* else. Only case, punctuation, typographic quotes and dashes, joiners and invisible code points stay minor
|
|
8
|
+
* (MP-11). Two texts with the same key but different strict text are TEXT_MINOR_CHANGED; with different keys they
|
|
9
|
+
* are TEXT_CHANGED. The key is not used for alignment. */
|
|
10
|
+
export declare function textKey(text: string): string;
|
|
3
11
|
/** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
|
|
4
12
|
* whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
|
|
5
13
|
* Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
|
|
@@ -54,6 +62,11 @@ export declare function hideUrlSecrets(text: string): string;
|
|
|
54
62
|
* by an outside review 2026-09-22).
|
|
55
63
|
*/
|
|
56
64
|
export declare function visibleNumbers(text: string): string[];
|
|
65
|
+
/** An href with only the characters the URL standard strips from its ends removed: the C0 controls and the space
|
|
66
|
+
* (U+0000 to U+0020). JavaScript's trim() also removes the no-break space, the ideographic space and the other
|
|
67
|
+
* Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
|
|
68
|
+
* compared equal (MP-16). */
|
|
69
|
+
export declare function trimHref(href: string): string;
|
|
57
70
|
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
58
71
|
export declare function resolveHref(rawHref: string, base: string | null): string | null;
|
|
59
72
|
/** Masks query values, drops the fragment and removes user information for display in reports and logs.
|
package/dist/src/normalize.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Text normalization. Strict normalization preserves case, applies NFC, removes the characters in ZERO_WIDTH,
|
|
2
|
-
// maps the spaces in NBSP to a plain space and collapses whitespace. Loose normalization aligns blocks
|
|
3
|
-
// classifies minor text differences (TEXT_MINOR_CHANGED)
|
|
2
|
+
// maps the spaces in NBSP to a plain space and collapses whitespace. Loose normalization aligns blocks. The text key
|
|
3
|
+
// (textKey) classifies minor text differences (TEXT_MINOR_CHANGED): it keeps the marks and symbols that loose
|
|
4
|
+
// normalization drops, so a changed mark or symbol is a text change.
|
|
4
5
|
const NBSP = /[\u00a0\u2007\u202f]/g;
|
|
5
6
|
const WS = /[ \t\r\n\f\v]+/g;
|
|
6
7
|
// Zero width space, byte order mark and soft hyphen: invisible artefacts of editing and export. Up to 0.2.12 the
|
|
@@ -17,7 +18,9 @@ export function strictNormalize(text) {
|
|
|
17
18
|
.replace(WS, ' ')
|
|
18
19
|
.trim();
|
|
19
20
|
}
|
|
20
|
-
|
|
21
|
+
/** The folding the loose text and the text key share: joiners out, case folded, typographic quotes, dashes and the
|
|
22
|
+
* ellipsis in their plain forms. */
|
|
23
|
+
function fold(text) {
|
|
21
24
|
return strictNormalize(text)
|
|
22
25
|
.replace(JOINERS, '')
|
|
23
26
|
.toLowerCase()
|
|
@@ -25,11 +28,31 @@ export function looseNormalize(text) {
|
|
|
25
28
|
.replace(/[\u2018\u2019\u201a\u2032]/g, "'")
|
|
26
29
|
.replace(/[\u201c\u201d\u201e\u2033]/g, '"')
|
|
27
30
|
.replace(/[\u2010-\u2015\u2212]/g, '-')
|
|
28
|
-
.replace(/\u2026/g, '...')
|
|
31
|
+
.replace(/\u2026/g, '...');
|
|
32
|
+
}
|
|
33
|
+
/** The key that aligns blocks: everything that is not a letter, a number or white space becomes a space, so two
|
|
34
|
+
* blocks that differ in punctuation, marks or symbols still pair. */
|
|
35
|
+
export function looseNormalize(text) {
|
|
36
|
+
return fold(text)
|
|
29
37
|
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
|
|
30
38
|
.replace(/\s+/g, ' ')
|
|
31
39
|
.trim();
|
|
32
40
|
}
|
|
41
|
+
// Code points that render as nothing by default: variation selectors, the combining grapheme joiner, the word joiner
|
|
42
|
+
// and the like. They are not content, so a difference in them alone is not a text change.
|
|
43
|
+
const IGNORABLE = /\p{Default_Ignorable_Code_Point}/gu;
|
|
44
|
+
/** The key that classifies a text difference: the loose text, except that the marks (\p{M}) and the symbols (\p{S})
|
|
45
|
+
* are kept, because a different vowel sign, check mark, arrow, comparison or plus sign shows the reader something
|
|
46
|
+
* else. Only case, punctuation, typographic quotes and dashes, joiners and invisible code points stay minor
|
|
47
|
+
* (MP-11). Two texts with the same key but different strict text are TEXT_MINOR_CHANGED; with different keys they
|
|
48
|
+
* are TEXT_CHANGED. The key is not used for alignment. */
|
|
49
|
+
export function textKey(text) {
|
|
50
|
+
return fold(text)
|
|
51
|
+
.replace(IGNORABLE, '')
|
|
52
|
+
.replace(/[^\p{L}\p{N}\p{M}\p{S}\s]/gu, ' ')
|
|
53
|
+
.replace(/\s+/g, ' ')
|
|
54
|
+
.trim();
|
|
55
|
+
}
|
|
33
56
|
/** Code with every run of whitespace collapsed to one space, nothing else touched. Whitespace is the ASCII
|
|
34
57
|
* whitespace characters and the Unicode space separators (\p{Zs}, which includes the no-break space). There is no
|
|
35
58
|
* Unicode normalization and no removal of zero width characters. Two code blocks that are equal here differ only in whitespace or indentation;
|
|
@@ -59,9 +82,10 @@ export function stripControlChars(text) {
|
|
|
59
82
|
return text.replace(CONTROL_CHARS, '');
|
|
60
83
|
}
|
|
61
84
|
// A numeric token: optional sign (ASCII hyphen, Unicode minus or plus) that is not preceded by a letter
|
|
62
|
-
// or digit (so the "-09" in 2026-09-10 is a separator, not a sign), digits
|
|
63
|
-
// (decimal, thousands, date, time, version),
|
|
64
|
-
|
|
85
|
+
// or digit (so the "-09" in 2026-09-10 is a separator, not a sign), digits of any script (\p{Nd}, so Arabic-Indic
|
|
86
|
+
// and fullwidth digits carry a sign too, MP-12) with inner separators (decimal, thousands, date, time, version),
|
|
87
|
+
// optional percent or currency sign on either side.
|
|
88
|
+
const NUMBER_RE = /(?<![\p{L}\p{N}])(?:[€$£]\s?)?[-\u2212+]?\p{Nd}+(?:[.,:\/\-\u2010-\u2015\u2212]\p{Nd}+)*\s?(?:%|€|\$|£)?/gu;
|
|
65
89
|
/** Extracts numeric tokens (prices, percentages, dates, versions, signed values) in source order. */
|
|
66
90
|
export function extractNumbers(text) {
|
|
67
91
|
const out = [];
|
|
@@ -444,9 +468,22 @@ export function hideUrlSecrets(text) {
|
|
|
444
468
|
export function visibleNumbers(text) {
|
|
445
469
|
return extractNumbers(hideUrlSecrets(text));
|
|
446
470
|
}
|
|
471
|
+
/** An href with only the characters the URL standard strips from its ends removed: the C0 controls and the space
|
|
472
|
+
* (U+0000 to U+0020). JavaScript's trim() also removes the no-break space, the ideographic space and the other
|
|
473
|
+
* Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
|
|
474
|
+
* compared equal (MP-16). */
|
|
475
|
+
export function trimHref(href) {
|
|
476
|
+
let start = 0;
|
|
477
|
+
let end = href.length;
|
|
478
|
+
while (start < end && href.charCodeAt(start) <= 0x20)
|
|
479
|
+
start++;
|
|
480
|
+
while (end > start && href.charCodeAt(end - 1) <= 0x20)
|
|
481
|
+
end--;
|
|
482
|
+
return href.slice(start, end);
|
|
483
|
+
}
|
|
447
484
|
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
448
485
|
export function resolveHref(rawHref, base) {
|
|
449
|
-
const href = rawHref
|
|
486
|
+
const href = trimHref(rawHref);
|
|
450
487
|
if (href === '')
|
|
451
488
|
return null;
|
|
452
489
|
if (base) {
|
package/dist/src/run.js
CHANGED
|
@@ -36,6 +36,38 @@ export const LIMITATIONS = [
|
|
|
36
36
|
function meta(e) {
|
|
37
37
|
return { strategy: e.strategy, confidence: e.confidence, blockCount: e.blocks.length, notes: e.notes };
|
|
38
38
|
}
|
|
39
|
+
/** The body after any comments, processing instructions (an XML declaration among them) and declarations other than
|
|
40
|
+
* a doctype html that come before its first content (MP-19). An unclosed comment or instruction leaves the rest as it is. */
|
|
41
|
+
function afterPrologue(body) {
|
|
42
|
+
let i = 0;
|
|
43
|
+
for (;;) {
|
|
44
|
+
while (i < body.length && /\s/.test(body[i]))
|
|
45
|
+
i++;
|
|
46
|
+
let end;
|
|
47
|
+
if (body.startsWith('<!--', i)) {
|
|
48
|
+
end = body.indexOf('-->', i + 4);
|
|
49
|
+
if (end < 0)
|
|
50
|
+
break;
|
|
51
|
+
i = end + 3;
|
|
52
|
+
}
|
|
53
|
+
else if (body.startsWith('<?', i)) {
|
|
54
|
+
end = body.indexOf('>', i + 2);
|
|
55
|
+
if (end < 0)
|
|
56
|
+
break;
|
|
57
|
+
i = end + 1;
|
|
58
|
+
}
|
|
59
|
+
else if (body.startsWith('<!', i) && !/^<!doctype\s+html/i.test(body.slice(i, i + 32))) {
|
|
60
|
+
end = body.indexOf('>', i + 2);
|
|
61
|
+
if (end < 0)
|
|
62
|
+
break;
|
|
63
|
+
i = end + 1;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return body.slice(i);
|
|
70
|
+
}
|
|
39
71
|
/** Findings about how the Markdown was delivered, produced by the URL mode before extraction. */
|
|
40
72
|
export function deliveryFindings(md, body) {
|
|
41
73
|
const out = [];
|
|
@@ -43,7 +75,7 @@ export function deliveryFindings(md, body) {
|
|
|
43
75
|
return out;
|
|
44
76
|
const ct = (md.contentType ?? '').toLowerCase();
|
|
45
77
|
const type = ct.split(';')[0].trim();
|
|
46
|
-
const looksHtml = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(body);
|
|
78
|
+
const looksHtml = /^\s*(?:<!doctype\s+html|<html[\s>])/i.test(afterPrologue(body));
|
|
47
79
|
if (md.status !== undefined && md.status >= 400) {
|
|
48
80
|
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) });
|
|
49
81
|
return out;
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const TOOL_NAME = "markdown-parity-check";
|
|
2
|
-
export declare const TOOL_VERSION = "0.2.
|
|
2
|
+
export declare const TOOL_VERSION = "0.2.34";
|
package/dist/src/version.js
CHANGED
|
@@ -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.
|
|
5
|
+
export const TOOL_VERSION = '0.2.34';
|
package/package.json
CHANGED