markdown-parity-check 0.1.2 → 0.2.0
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 +14 -1
- package/dist/src/align.d.ts +52 -0
- package/dist/src/align.js +33 -11
- package/dist/src/cli.d.ts +33 -0
- package/dist/src/compare.d.ts +19 -0
- package/dist/src/compare.js +1 -1
- package/dist/src/core.d.ts +11 -0
- package/dist/src/core.js +12 -0
- package/dist/src/fetch.d.ts +46 -0
- package/dist/src/html.d.ts +20 -0
- package/dist/src/html.js +25 -0
- package/dist/src/markdown.d.ts +15 -0
- package/dist/src/markdown.js +46 -8
- package/dist/src/model.d.ts +69 -0
- package/dist/src/netguard.d.ts +17 -0
- package/dist/src/netguard.js +48 -4
- package/dist/src/normalize.d.ts +19 -0
- package/dist/src/report.d.ts +6 -0
- package/dist/src/run.d.ts +83 -0
- package/dist/src/run.js +24 -8
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +5 -5
- package/package.json +10 -1
package/README.md
CHANGED
|
@@ -56,7 +56,20 @@ The comparison covers headings, paragraphs, lists, tables, code and links. It de
|
|
|
56
56
|
|
|
57
57
|
HTML content selection prefers the main content container. A fallback to the page body produces a warning. JavaScript is not executed. Block matching is heuristic and some complex layouts need an explicit selector.
|
|
58
58
|
|
|
59
|
-
URL fetching blocks non-public network targets and checks redirects. Request deadlines and response size limits bound network work. The comparison itself is bounded too: the product of the HTML and Markdown block counts may not exceed 4 000 000, which is 2 000 blocks on each side. Above that the tool exits with code 2 and an error instead of allocating memory without limit. Reports mask URL query values, but content excerpts may still contain private information. Review reports before sharing them.
|
|
59
|
+
URL fetching blocks non-public network targets and checks redirects. Request deadlines and response size limits bound network work. The comparison itself is bounded too: the product of the HTML and Markdown block counts may not exceed 4 000 000, which is 2 000 blocks on each side. Above that the tool exits with code 2 and an error instead of allocating memory without limit. HTML or Markdown nested deeper than 1 024 levels also ends with code 2, before the extraction can exhaust the call stack. Reports mask URL query values, but content excerpts may still contain private information. Review reports before sharing them.
|
|
60
|
+
|
|
61
|
+
## Library use
|
|
62
|
+
|
|
63
|
+
The package has a library entry as well. It runs the same comparison as the command, without the command-line interface, the file reader or the network code. It uses no Node.js built-in modules, so it can also be bundled for Cloudflare Workers.
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
import { run, renderJson } from 'markdown-parity-check';
|
|
67
|
+
|
|
68
|
+
const report = run(htmlSource, markdownSource, { strict: false, mode: 'url' });
|
|
69
|
+
console.log(renderJson(report));
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Each source is an object with the document text, a base URL for links and the source details the report shows. The report is the same object that `--format json` prints. A host with a smaller CPU or memory budget can pass lower limits in the `limits` option, and a run that exceeds one ends with an error. Fetching the pages and deciding which addresses may be fetched stays with the caller. The address policy the command applies is exported as `assertPublicHost` and `isPublicAddress`.
|
|
60
73
|
|
|
61
74
|
## Run from source
|
|
62
75
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Block } from './model.js';
|
|
2
|
+
export interface Pair {
|
|
3
|
+
a: number;
|
|
4
|
+
b: number;
|
|
5
|
+
kind: 'exact' | 'moved' | 'loose' | 'similar';
|
|
6
|
+
similarity: number;
|
|
7
|
+
}
|
|
8
|
+
export interface Alignment {
|
|
9
|
+
pairs: Pair[];
|
|
10
|
+
unmatchedA: number[];
|
|
11
|
+
unmatchedB: number[];
|
|
12
|
+
}
|
|
13
|
+
/** paragraph and listItem are one group for alignment: a list rendered as paragraphs is a structure
|
|
14
|
+
* difference, not missing content. */
|
|
15
|
+
export declare function typeGroup(b: Block): string;
|
|
16
|
+
export declare function strictKey(b: Block): string;
|
|
17
|
+
export declare const SIMILARITY_THRESHOLD = 0.6;
|
|
18
|
+
export declare const UNCERTAIN_THRESHOLD = 0.8;
|
|
19
|
+
/** Upper bound on the alignment work, as the product of the HTML and Markdown block counts. The LCS
|
|
20
|
+
* table holds (n+1)*(m+1) Uint32 cells, 16 MiB at the limit (2 000 by 2 000 blocks), and the similarity
|
|
21
|
+
* search visits at most n*m block pairs. Above the limit the comparison stops with an error before any
|
|
22
|
+
* table is allocated, instead of growing without bound with the page size. */
|
|
23
|
+
export declare const MAX_ALIGNMENT_PAIRS = 4000000;
|
|
24
|
+
/** Upper bound on the similarity candidates kept for the greedy best-match pass. Only pairs at or above
|
|
25
|
+
* SIMILARITY_THRESHOLD are kept, so this is reached only when a large share of the free blocks on both
|
|
26
|
+
* sides resemble each other. */
|
|
27
|
+
export declare const MAX_SIMILARITY_CANDIDATES = 1000000;
|
|
28
|
+
/** Resource limits of the alignment. The defaults are the CLI's. A host with a smaller CPU or memory
|
|
29
|
+
* budget, such as a Cloudflare Worker, passes lower values through RunOptions.limits. Exceeding any of
|
|
30
|
+
* them is an AlignmentLimitError, reported as an error result, never as a pass or a truncated
|
|
31
|
+
* comparison. */
|
|
32
|
+
export interface AlignmentLimits {
|
|
33
|
+
/** Upper bound on the product of the HTML and Markdown block counts. */
|
|
34
|
+
maxAlignmentPairs: number;
|
|
35
|
+
/** Upper bound on the similarity candidates kept for the greedy best-match pass. */
|
|
36
|
+
maxSimilarityCandidates: number;
|
|
37
|
+
/** Upper bound on token lookups in the similarity search, summed over every block pair it visits.
|
|
38
|
+
* Unbounded by default; the block pair limit already bounds it for the CLI. */
|
|
39
|
+
maxSimilarityWork: number;
|
|
40
|
+
}
|
|
41
|
+
export declare const DEFAULT_LIMITS: Readonly<AlignmentLimits>;
|
|
42
|
+
/** Thrown when the comparison would exceed a documented resource limit. The caller reports it as an
|
|
43
|
+
* error result (exit 2), never as a pass or a silently truncated comparison. */
|
|
44
|
+
export declare class AlignmentLimitError extends Error {
|
|
45
|
+
constructor(message: string);
|
|
46
|
+
}
|
|
47
|
+
/** Dice coefficient over word tokens of the loose text. */
|
|
48
|
+
export declare function similarity(a: Block, b: Block): number;
|
|
49
|
+
/** Checks the block counts against the block pair limit (MAX_ALIGNMENT_PAIRS by default) before any
|
|
50
|
+
* work is done. */
|
|
51
|
+
export declare function checkAlignmentLimit(htmlBlocks: number, markdownBlocks: number, maxPairs?: number): void;
|
|
52
|
+
export declare function align(a: Block[], b: Block[], limits?: Partial<AlignmentLimits>): Alignment;
|
package/dist/src/align.js
CHANGED
|
@@ -26,6 +26,19 @@ export const MAX_ALIGNMENT_PAIRS = 4_000_000;
|
|
|
26
26
|
* SIMILARITY_THRESHOLD are kept, so this is reached only when a large share of the free blocks on both
|
|
27
27
|
* sides resemble each other. */
|
|
28
28
|
export const MAX_SIMILARITY_CANDIDATES = 1_000_000;
|
|
29
|
+
export const DEFAULT_LIMITS = Object.freeze({
|
|
30
|
+
maxAlignmentPairs: MAX_ALIGNMENT_PAIRS,
|
|
31
|
+
maxSimilarityCandidates: MAX_SIMILARITY_CANDIDATES,
|
|
32
|
+
maxSimilarityWork: Number.POSITIVE_INFINITY,
|
|
33
|
+
});
|
|
34
|
+
function resolveLimits(limits) {
|
|
35
|
+
const out = { ...DEFAULT_LIMITS, ...(limits ?? {}) };
|
|
36
|
+
for (const [k, v] of Object.entries(out)) {
|
|
37
|
+
if (typeof v !== 'number' || Number.isNaN(v) || v <= 0)
|
|
38
|
+
throw new TypeError(`Alignment limit ${k} must be a positive number (got ${String(v)}).`);
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
29
42
|
/** Thrown when the comparison would exceed a documented resource limit. The caller reports it as an
|
|
30
43
|
* error result (exit 2), never as a pass or a silently truncated comparison. */
|
|
31
44
|
export class AlignmentLimitError extends Error {
|
|
@@ -59,17 +72,18 @@ export function similarity(a, b) {
|
|
|
59
72
|
return 0;
|
|
60
73
|
return dice(tokens(a.loose), tokens(b.loose));
|
|
61
74
|
}
|
|
62
|
-
/** Checks the block counts against
|
|
63
|
-
|
|
75
|
+
/** Checks the block counts against the block pair limit (MAX_ALIGNMENT_PAIRS by default) before any
|
|
76
|
+
* work is done. */
|
|
77
|
+
export function checkAlignmentLimit(htmlBlocks, markdownBlocks, maxPairs = MAX_ALIGNMENT_PAIRS) {
|
|
64
78
|
const pairs = htmlBlocks * markdownBlocks;
|
|
65
|
-
if (pairs >
|
|
66
|
-
throw new AlignmentLimitError(`Comparison limit exceeded: ${htmlBlocks} HTML blocks by ${markdownBlocks} Markdown blocks is ${pairs} block pairs, above the limit of ${
|
|
79
|
+
if (pairs > maxPairs) {
|
|
80
|
+
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.`);
|
|
67
81
|
}
|
|
68
82
|
}
|
|
69
|
-
function lcs(keysA, keysB) {
|
|
83
|
+
function lcs(keysA, keysB, maxPairs) {
|
|
70
84
|
const n = keysA.length;
|
|
71
85
|
const m = keysB.length;
|
|
72
|
-
checkAlignmentLimit(n, m);
|
|
86
|
+
checkAlignmentLimit(n, m, maxPairs);
|
|
73
87
|
const dp = [];
|
|
74
88
|
for (let i = 0; i <= n; i++)
|
|
75
89
|
dp.push(new Uint32Array(m + 1));
|
|
@@ -96,14 +110,15 @@ function lcs(keysA, keysB) {
|
|
|
96
110
|
}
|
|
97
111
|
return out;
|
|
98
112
|
}
|
|
99
|
-
export function align(a, b) {
|
|
100
|
-
|
|
113
|
+
export function align(a, b, limits) {
|
|
114
|
+
const lim = resolveLimits(limits);
|
|
115
|
+
checkAlignmentLimit(a.length, b.length, lim.maxAlignmentPairs);
|
|
101
116
|
const pairs = [];
|
|
102
117
|
const usedA = new Set();
|
|
103
118
|
const usedB = new Set();
|
|
104
119
|
const keysA = a.map(strictKey);
|
|
105
120
|
const keysB = b.map(strictKey);
|
|
106
|
-
for (const [i, j] of lcs(keysA, keysB)) {
|
|
121
|
+
for (const [i, j] of lcs(keysA, keysB, lim.maxAlignmentPairs)) {
|
|
107
122
|
pairs.push({ a: i, b: j, kind: 'exact', similarity: 1 });
|
|
108
123
|
usedA.add(i);
|
|
109
124
|
usedB.add(j);
|
|
@@ -168,6 +183,9 @@ export function align(a, b) {
|
|
|
168
183
|
for (const j of freeBs)
|
|
169
184
|
tokensB.set(j, tokens(b[j].loose));
|
|
170
185
|
const candidates = [];
|
|
186
|
+
// Token lookups so far. dice() walks the HTML block's distinct tokens once per visited pair, so this
|
|
187
|
+
// is the work the search does, and a host with a small CPU budget bounds it through the limits.
|
|
188
|
+
let work = 0;
|
|
171
189
|
for (const i of freeA) {
|
|
172
190
|
const ta = tokensA.get(i);
|
|
173
191
|
if (ta.total === 0)
|
|
@@ -176,11 +194,15 @@ export function align(a, b) {
|
|
|
176
194
|
for (const j of freeBs) {
|
|
177
195
|
if (typeGroup(b[j]) !== ga)
|
|
178
196
|
continue;
|
|
197
|
+
work += ta.counts.size;
|
|
198
|
+
if (work > lim.maxSimilarityWork) {
|
|
199
|
+
throw new AlignmentLimitError(`Comparison limit exceeded: the similarity search among ${freeA.length} unmatched HTML blocks and ${freeBs.length} unmatched Markdown blocks needs more than ${lim.maxSimilarityWork} token comparisons. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
200
|
+
}
|
|
179
201
|
const s = dice(ta, tokensB.get(j));
|
|
180
202
|
if (s < SIMILARITY_THRESHOLD)
|
|
181
203
|
continue;
|
|
182
|
-
if (candidates.length >=
|
|
183
|
-
throw new AlignmentLimitError(`Comparison limit exceeded: more than ${
|
|
204
|
+
if (candidates.length >= lim.maxSimilarityCandidates) {
|
|
205
|
+
throw new AlignmentLimitError(`Comparison limit exceeded: more than ${lim.maxSimilarityCandidates} similar block pairs among ${freeA.length} unmatched HTML blocks and ${freeBs.length} unmatched Markdown blocks. Narrow the HTML content with --selector or compare a smaller page.`);
|
|
184
206
|
}
|
|
185
207
|
candidates.push({ i, j, s });
|
|
186
208
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type FetchOptions, type FetchResult } from './fetch.js';
|
|
3
|
+
export declare const HELP = "markdown-parity-check 0.2.0\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 --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
|
+
export declare class CliError extends Error {
|
|
5
|
+
}
|
|
6
|
+
export interface CliArgs {
|
|
7
|
+
url?: string;
|
|
8
|
+
markdownUrl?: string;
|
|
9
|
+
htmlFile?: string;
|
|
10
|
+
markdownFile?: string;
|
|
11
|
+
baseUrl?: string;
|
|
12
|
+
selector?: string;
|
|
13
|
+
frontMatter: 'keep' | 'strip';
|
|
14
|
+
format: 'text' | 'json';
|
|
15
|
+
output?: string;
|
|
16
|
+
timeoutMs: number;
|
|
17
|
+
maxBytes: number;
|
|
18
|
+
strict: boolean;
|
|
19
|
+
help: boolean;
|
|
20
|
+
version: boolean;
|
|
21
|
+
}
|
|
22
|
+
export declare function parseCliArgs(argv: string[]): CliArgs;
|
|
23
|
+
export type FetchFn = (url: string, options: FetchOptions) => Promise<FetchResult>;
|
|
24
|
+
export interface CliIo {
|
|
25
|
+
stdout: (s: string) => void;
|
|
26
|
+
stderr: (s: string) => void;
|
|
27
|
+
}
|
|
28
|
+
export interface CliDeps {
|
|
29
|
+
/** Injectable fetch for tests. Production always uses fetchUrl with its default address policy. */
|
|
30
|
+
fetch?: FetchFn;
|
|
31
|
+
}
|
|
32
|
+
/** Runs the CLI and returns the exit code. Throws nothing; every failure becomes exit 2. */
|
|
33
|
+
export declare function main(argv: string[], io?: CliIo, deps?: CliDeps): Promise<0 | 1 | 2>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type AlignmentLimits } from './align.js';
|
|
2
|
+
import type { Extraction, Finding } from './model.js';
|
|
3
|
+
export interface Coverage {
|
|
4
|
+
htmlBlocks: number;
|
|
5
|
+
markdownBlocks: number;
|
|
6
|
+
htmlMatched: number;
|
|
7
|
+
markdownMatched: number;
|
|
8
|
+
/** Matched share of HTML blocks, 0..1. */
|
|
9
|
+
htmlRatio: number;
|
|
10
|
+
markdownRatio: number;
|
|
11
|
+
}
|
|
12
|
+
export interface CompareResult {
|
|
13
|
+
findings: Finding[];
|
|
14
|
+
coverage: Coverage;
|
|
15
|
+
}
|
|
16
|
+
export declare function compare(html: Extraction, markdown: Extraction, options?: {
|
|
17
|
+
bothBases?: boolean;
|
|
18
|
+
limits?: Partial<AlignmentLimits>;
|
|
19
|
+
}): CompareResult;
|
package/dist/src/compare.js
CHANGED
|
@@ -141,7 +141,7 @@ const SEVERITY_ORDER = { error: 0, warning: 1, info: 2 };
|
|
|
141
141
|
export function compare(html, markdown, options = {}) {
|
|
142
142
|
const a = html.blocks;
|
|
143
143
|
const b = markdown.blocks;
|
|
144
|
-
const al = align(a, b);
|
|
144
|
+
const al = align(a, b, options.limits);
|
|
145
145
|
const findings = [];
|
|
146
146
|
const bothBases = options.bothBases ?? false;
|
|
147
147
|
if (html.confidence === 'low') {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { run, errorReport, deliveryFindings, RunError, LIMITATIONS } from './run.js';
|
|
2
|
+
export type { Report, RunOptions, RunLimits, SourceInput, SourceMeta, ExtractionMeta } from './run.js';
|
|
3
|
+
export { MAX_NESTING_DEPTH } from './run.js';
|
|
4
|
+
export { renderJson, renderText, redactReport } from './report.js';
|
|
5
|
+
export { AlignmentLimitError, DEFAULT_LIMITS, MAX_ALIGNMENT_PAIRS, MAX_SIMILARITY_CANDIDATES, checkAlignmentLimit } from './align.js';
|
|
6
|
+
export type { AlignmentLimits } from './align.js';
|
|
7
|
+
export type { Coverage } from './compare.js';
|
|
8
|
+
export type { Finding, FindingSide, Severity, Direction } from './model.js';
|
|
9
|
+
export { maskUrl, maskHref, redactText } from './normalize.js';
|
|
10
|
+
export { ipVersion, isPublicAddress, isPublicIPv4, isPublicIPv6, assertPublicHost, assertPublicResolved, BlockedAddressError } from './netguard.js';
|
|
11
|
+
export { TOOL_NAME, TOOL_VERSION } from './version.js';
|
package/dist/src/core.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Library entry point, and the one a Cloudflare Worker bundles: the comparison core without the
|
|
2
|
+
// command-line interface, file access or network transport. Nothing reachable from here imports a
|
|
3
|
+
// Node.js built-in module; test/core.test.ts walks the import graph and fails the build if one appears.
|
|
4
|
+
// Fetching the two documents, and deciding which addresses may be fetched, stays with the caller; the
|
|
5
|
+
// address policy the CLI applies is exported so a caller can apply the same one.
|
|
6
|
+
export { run, errorReport, deliveryFindings, RunError, LIMITATIONS } from './run.js';
|
|
7
|
+
export { MAX_NESTING_DEPTH } from './run.js';
|
|
8
|
+
export { renderJson, renderText, redactReport } from './report.js';
|
|
9
|
+
export { AlignmentLimitError, DEFAULT_LIMITS, MAX_ALIGNMENT_PAIRS, MAX_SIMILARITY_CANDIDATES, checkAlignmentLimit } from './align.js';
|
|
10
|
+
export { maskUrl, maskHref, redactText } from './normalize.js';
|
|
11
|
+
export { ipVersion, isPublicAddress, isPublicIPv4, isPublicIPv6, assertPublicHost, assertPublicResolved, BlockedAddressError } from './netguard.js';
|
|
12
|
+
export { TOOL_NAME, TOOL_VERSION } from './version.js';
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import https from 'node:https';
|
|
3
|
+
export type FetchErrorKind = 'invalid_url' | 'blocked' | 'timeout' | 'too_large' | 'redirect_loop' | 'too_many_redirects' | 'network' | 'protocol';
|
|
4
|
+
export declare class FetchError extends Error {
|
|
5
|
+
kind: FetchErrorKind;
|
|
6
|
+
url: string;
|
|
7
|
+
constructor(kind: FetchErrorKind, url: string, message: string);
|
|
8
|
+
}
|
|
9
|
+
export type Resolver = (hostname: string) => Promise<Array<{
|
|
10
|
+
address: string;
|
|
11
|
+
family: 4 | 6;
|
|
12
|
+
}>>;
|
|
13
|
+
export interface FetchOptions {
|
|
14
|
+
accept: string;
|
|
15
|
+
timeoutMs: number;
|
|
16
|
+
/** Cap on decoded (decompressed) body bytes. */
|
|
17
|
+
maxBytes: number;
|
|
18
|
+
maxRedirects?: number;
|
|
19
|
+
userAgent?: string;
|
|
20
|
+
/** Injectable resolver for tests. Defaults to dns.lookup with all addresses. */
|
|
21
|
+
resolver?: Resolver;
|
|
22
|
+
/**
|
|
23
|
+
* Test harness only: exact host names whose address policy check is skipped, so that a loopback
|
|
24
|
+
* test server can be reached. Not reachable from the CLI; the production default is an empty list.
|
|
25
|
+
*/
|
|
26
|
+
testAllowHosts?: string[];
|
|
27
|
+
/** Test harness only: agent for TLS tests. */
|
|
28
|
+
agent?: http.Agent | https.Agent;
|
|
29
|
+
}
|
|
30
|
+
export interface FetchResult {
|
|
31
|
+
requestedUrl: string;
|
|
32
|
+
finalUrl: string;
|
|
33
|
+
status: number;
|
|
34
|
+
contentType: string | null;
|
|
35
|
+
body: string;
|
|
36
|
+
/** Decoded body size in bytes. */
|
|
37
|
+
bytes: number;
|
|
38
|
+
redirects: number;
|
|
39
|
+
accept: string;
|
|
40
|
+
}
|
|
41
|
+
export declare function validateUrl(input: string): URL;
|
|
42
|
+
/**
|
|
43
|
+
* Fetches one URL with the given Accept header, following at most maxRedirects redirects. Every hop is
|
|
44
|
+
* validated by the address policy. Returns the decoded body; the raw response is not stored.
|
|
45
|
+
*/
|
|
46
|
+
export declare function fetchUrl(input: string, options: FetchOptions): Promise<FetchResult>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ParentNode } from 'domhandler';
|
|
2
|
+
import type { Extraction } from './model.js';
|
|
3
|
+
export interface HtmlExtractOptions {
|
|
4
|
+
/** User supplied CSS selector for the main content. */
|
|
5
|
+
selector?: string;
|
|
6
|
+
/** Base URL for resolving relative links; a <base href> in the document takes precedence. */
|
|
7
|
+
baseUrl?: string | null;
|
|
8
|
+
/** Deepest element nesting accepted, counted from the document root. Default MAX_NESTING_DEPTH. */
|
|
9
|
+
maxDepth?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare class HtmlExtractError extends Error {
|
|
12
|
+
}
|
|
13
|
+
/** Default nesting limit for both extractors. The extraction walks the tree recursively, and a document
|
|
14
|
+
* nested a few thousand levels deep exhausts the call stack (measured 2026-09-11: 5 000 nested div
|
|
15
|
+
* elements under Node.js 24). Real pages stay far below this. */
|
|
16
|
+
export declare const MAX_NESTING_DEPTH = 1024;
|
|
17
|
+
/** Deepest element nesting under a node, counted with an explicit stack so the count itself cannot
|
|
18
|
+
* exhaust the call stack. */
|
|
19
|
+
export declare function nestingDepth(node: ParentNode): number;
|
|
20
|
+
export declare function extractHtml(source: string, options?: HtmlExtractOptions): Extraction;
|
package/dist/src/html.js
CHANGED
|
@@ -7,6 +7,26 @@ import { textContent } from 'domutils';
|
|
|
7
7
|
import { extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
|
|
8
8
|
export class HtmlExtractError extends Error {
|
|
9
9
|
}
|
|
10
|
+
/** Default nesting limit for both extractors. The extraction walks the tree recursively, and a document
|
|
11
|
+
* nested a few thousand levels deep exhausts the call stack (measured 2026-09-11: 5 000 nested div
|
|
12
|
+
* elements under Node.js 24). Real pages stay far below this. */
|
|
13
|
+
export const MAX_NESTING_DEPTH = 1024;
|
|
14
|
+
/** Deepest element nesting under a node, counted with an explicit stack so the count itself cannot
|
|
15
|
+
* exhaust the call stack. */
|
|
16
|
+
export function nestingDepth(node) {
|
|
17
|
+
let max = 0;
|
|
18
|
+
const stack = node.children.map((c) => [c, 1]);
|
|
19
|
+
while (stack.length > 0) {
|
|
20
|
+
const [n, d] = stack.pop();
|
|
21
|
+
if (!(n instanceof Element))
|
|
22
|
+
continue;
|
|
23
|
+
if (d > max)
|
|
24
|
+
max = d;
|
|
25
|
+
for (const c of n.children)
|
|
26
|
+
stack.push([c, d + 1]);
|
|
27
|
+
}
|
|
28
|
+
return max;
|
|
29
|
+
}
|
|
10
30
|
const SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'nav', 'iframe', 'svg', 'canvas', 'object', 'embed', 'map', 'form', 'button', 'input', 'select', 'textarea', 'dialog']);
|
|
11
31
|
const SKIP_ROLES = new Set(['navigation', 'banner', 'contentinfo', 'complementary', 'search', 'menu', 'menubar', 'dialog']);
|
|
12
32
|
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']);
|
|
@@ -296,6 +316,11 @@ function pickRoot(doc, selector, notes) {
|
|
|
296
316
|
}
|
|
297
317
|
export function extractHtml(source, options = {}) {
|
|
298
318
|
const doc = parseDocument(source, { withStartIndices: true, withEndIndices: true, decodeEntities: true });
|
|
319
|
+
// Before any selector runs: the selector engine and the extraction below both recurse over the tree.
|
|
320
|
+
const maxDepth = options.maxDepth ?? MAX_NESTING_DEPTH;
|
|
321
|
+
const depth = nestingDepth(doc);
|
|
322
|
+
if (depth > maxDepth)
|
|
323
|
+
throw new HtmlExtractError(`HTML nesting depth ${depth} exceeds the limit of ${maxDepth} levels; the comparison was not run.`);
|
|
299
324
|
const notes = [];
|
|
300
325
|
const baseEl = selectOne('base[href]', doc.children);
|
|
301
326
|
let base = options.baseUrl ?? null;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Extraction } from './model.js';
|
|
2
|
+
export interface MarkdownExtractOptions {
|
|
3
|
+
baseUrl?: string | null;
|
|
4
|
+
/**
|
|
5
|
+
* 'keep' (default): nothing is removed; a document that starts with a fence that looks like YAML front
|
|
6
|
+
* matter is compared as written and flagged with a warning. 'strip': the user has said the document
|
|
7
|
+
* carries front matter, so the leading fenced block is removed and reported as info.
|
|
8
|
+
*/
|
|
9
|
+
frontMatter?: 'keep' | 'strip';
|
|
10
|
+
/** Deepest node nesting accepted in the parsed Markdown tree. Default MAX_NESTING_DEPTH. */
|
|
11
|
+
maxDepth?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare class MarkdownExtractError extends Error {
|
|
14
|
+
}
|
|
15
|
+
export declare function extractMarkdown(source: string, options?: MarkdownExtractOptions): Extraction;
|
package/dist/src/markdown.js
CHANGED
|
@@ -2,10 +2,26 @@
|
|
|
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 } from './html.js';
|
|
5
|
+
import { extractHtml, MAX_NESTING_DEPTH } from './html.js';
|
|
6
6
|
import { parseDocument } from 'htmlparser2';
|
|
7
|
-
import { Element } from 'domhandler';
|
|
7
|
+
import { Element, Text } from 'domhandler';
|
|
8
8
|
import { excerpt, extractNumbers, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
|
|
9
|
+
export class MarkdownExtractError extends Error {
|
|
10
|
+
}
|
|
11
|
+
/** Deepest node nesting of a Markdown tree, counted with an explicit stack. */
|
|
12
|
+
function treeDepth(tree) {
|
|
13
|
+
let max = 0;
|
|
14
|
+
const stack = [[tree, 0]];
|
|
15
|
+
while (stack.length > 0) {
|
|
16
|
+
const [n, d] = stack.pop();
|
|
17
|
+
if (d > max)
|
|
18
|
+
max = d;
|
|
19
|
+
if ('children' in n)
|
|
20
|
+
for (const c of n.children)
|
|
21
|
+
stack.push([c, d + 1]);
|
|
22
|
+
}
|
|
23
|
+
return max;
|
|
24
|
+
}
|
|
9
25
|
/** Parses one inline HTML node (a single tag, per micromark) with htmlparser2. Returns null for comments,
|
|
10
26
|
* processing instructions or anything that is not exactly one tag. */
|
|
11
27
|
function parseInlineTag(value) {
|
|
@@ -229,14 +245,13 @@ function handle(ctx, node, listItem = false) {
|
|
|
229
245
|
/** A raw HTML block in Markdown is parsed with the HTML extractor so its content takes part in the
|
|
230
246
|
* comparison; the report shows that this happened. Comments and bare tags without text yield nothing. */
|
|
231
247
|
function handleRawHtml(ctx, value, line) {
|
|
232
|
-
|
|
233
|
-
//
|
|
234
|
-
//
|
|
235
|
-
const
|
|
236
|
-
const textOnly = strictNormalize(visibleSource.replace(/<[^>]*>/g, ' '));
|
|
248
|
+
// Text check for the fallback warning, taken from the parsed DOM rather than from regex stripping:
|
|
249
|
+
// comments are not text, and script, style, template and noscript are page machinery on both sides,
|
|
250
|
+
// so their content does not count as skipped text.
|
|
251
|
+
const textOnly = visibleText(value);
|
|
237
252
|
let parsed = null;
|
|
238
253
|
try {
|
|
239
|
-
parsed = extractHtml(`<body>${
|
|
254
|
+
parsed = extractHtml(`<body>${value}</body>`, { selector: 'body', baseUrl: ctx.base });
|
|
240
255
|
}
|
|
241
256
|
catch {
|
|
242
257
|
parsed = null;
|
|
@@ -256,6 +271,25 @@ function handleRawHtml(ctx, value, line) {
|
|
|
256
271
|
ctx.issues.push({ code: 'MARKDOWN_RAW_HTML_SKIPPED', severity: 'warning', message: 'A raw HTML block in the Markdown carries text that could not be parsed into blocks; it was not compared.', line, excerpt: excerpt(textOnly) });
|
|
257
272
|
}
|
|
258
273
|
}
|
|
274
|
+
const MACHINERY = new Set(['script', 'style', 'template', 'noscript']);
|
|
275
|
+
/** Strictly normalized text of an HTML fragment as a parser sees it: text nodes only, comments and
|
|
276
|
+
* machinery elements excluded. */
|
|
277
|
+
function visibleText(fragment) {
|
|
278
|
+
const parts = [];
|
|
279
|
+
const walk = (nodes) => {
|
|
280
|
+
for (const node of nodes) {
|
|
281
|
+
if (node instanceof Text)
|
|
282
|
+
parts.push(node.data);
|
|
283
|
+
else if (node instanceof Element) {
|
|
284
|
+
if (MACHINERY.has(node.name.toLowerCase()))
|
|
285
|
+
continue;
|
|
286
|
+
walk(node.children);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
walk(parseDocument(fragment).children);
|
|
291
|
+
return strictNormalize(parts.join(' '));
|
|
292
|
+
}
|
|
259
293
|
const YAML_LINE = /^(?:[A-Za-z0-9_.-]+\s*:(?:\s|$)|\s+\S|-\s|#)/;
|
|
260
294
|
const FENCE_RE = /^(?:\ufeff)?---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;
|
|
261
295
|
/**
|
|
@@ -294,6 +328,10 @@ export function extractMarkdown(source, options = {}) {
|
|
|
294
328
|
const mode = options.frontMatter ?? 'keep';
|
|
295
329
|
const fm = scanFrontMatter(source, mode);
|
|
296
330
|
const tree = fromMarkdown(fm.text, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
|
|
331
|
+
const maxDepth = options.maxDepth ?? MAX_NESTING_DEPTH;
|
|
332
|
+
const depth = treeDepth(tree);
|
|
333
|
+
if (depth > maxDepth)
|
|
334
|
+
throw new MarkdownExtractError(`Markdown nesting depth ${depth} exceeds the limit of ${maxDepth} levels; the comparison was not run.`);
|
|
297
335
|
const ctx = { base: options.baseUrl ?? null, blocks: [], notes: [], issues: [], definitions: collectDefinitions(tree) };
|
|
298
336
|
const fmExcerpt = () => excerpt(fm.body.replace(/\s+/g, ' '));
|
|
299
337
|
if (mode === 'strip' && fm.skippedLines > 0) {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export type BlockType = 'heading' | 'paragraph' | 'listItem' | 'table' | 'code';
|
|
2
|
+
export interface Link {
|
|
3
|
+
/** Visible anchor text, strictly normalized. */
|
|
4
|
+
text: string;
|
|
5
|
+
/** Href exactly as written in the source. */
|
|
6
|
+
rawHref: string;
|
|
7
|
+
/** Href resolved against the document base, or null when it could not be resolved. */
|
|
8
|
+
resolved: string | null;
|
|
9
|
+
}
|
|
10
|
+
export interface Location {
|
|
11
|
+
/** 1-based line in the source text when the parser supplied a position. */
|
|
12
|
+
line?: number;
|
|
13
|
+
/** For HTML: a tag path such as main > p:nth-of-type(3). */
|
|
14
|
+
path?: string;
|
|
15
|
+
/** 0-based index of the block within the extracted block list. */
|
|
16
|
+
blockIndex: number;
|
|
17
|
+
}
|
|
18
|
+
export interface Block {
|
|
19
|
+
type: BlockType;
|
|
20
|
+
/** Strictly normalized comparison text (case and content characters preserved). */
|
|
21
|
+
text: string;
|
|
22
|
+
/** Loosely normalized text used only for alignment. */
|
|
23
|
+
loose: string;
|
|
24
|
+
/** Heading depth 1..6 for headings. */
|
|
25
|
+
depth?: number;
|
|
26
|
+
/** Table cells row by row, strictly normalized. Only for type 'table'. */
|
|
27
|
+
cells?: string[][];
|
|
28
|
+
/** Raw code content with whitespace preserved. Only for type 'code'. */
|
|
29
|
+
code?: string;
|
|
30
|
+
links: Link[];
|
|
31
|
+
numbers: string[];
|
|
32
|
+
location: Location;
|
|
33
|
+
}
|
|
34
|
+
export interface Extraction {
|
|
35
|
+
blocks: Block[];
|
|
36
|
+
/** How the main content was selected. */
|
|
37
|
+
strategy: string;
|
|
38
|
+
/** high: user selector / main / article. low: body fallback. */
|
|
39
|
+
confidence: 'high' | 'low';
|
|
40
|
+
/** Non-fatal notes from the extractor. */
|
|
41
|
+
notes: string[];
|
|
42
|
+
/** Coverage issues that must be visible in the report: content the extractor parsed unusually or skipped. */
|
|
43
|
+
issues: ExtractionIssue[];
|
|
44
|
+
}
|
|
45
|
+
export interface ExtractionIssue {
|
|
46
|
+
code: string;
|
|
47
|
+
severity: 'warning' | 'info';
|
|
48
|
+
message: string;
|
|
49
|
+
line?: number;
|
|
50
|
+
excerpt?: string;
|
|
51
|
+
}
|
|
52
|
+
export type Severity = 'error' | 'warning' | 'info';
|
|
53
|
+
export type Direction = 'html_only' | 'markdown_only' | 'both';
|
|
54
|
+
export interface FindingSide {
|
|
55
|
+
line?: number;
|
|
56
|
+
path?: string;
|
|
57
|
+
blockIndex?: number;
|
|
58
|
+
excerpt?: string;
|
|
59
|
+
}
|
|
60
|
+
export interface Finding {
|
|
61
|
+
code: string;
|
|
62
|
+
severity: Severity;
|
|
63
|
+
direction: Direction;
|
|
64
|
+
message: string;
|
|
65
|
+
html?: FindingSide;
|
|
66
|
+
markdown?: FindingSide;
|
|
67
|
+
before?: string;
|
|
68
|
+
after?: string;
|
|
69
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare class BlockedAddressError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* IP version of a literal: 4, 6, or 0 when the string is neither. Dotted-quad IPv4 without leading
|
|
6
|
+
* zeros, and IPv6 with at most one "::", hex groups of one to four digits, an optional dotted-quad
|
|
7
|
+
* tail and an optional zone. test/core.test.ts compares the answers with node:net isIP.
|
|
8
|
+
*/
|
|
9
|
+
export declare function ipVersion(s: string): 0 | 4 | 6;
|
|
10
|
+
export declare function isPublicIPv4(ip: string): boolean;
|
|
11
|
+
/** Expands an IPv6 address into 8 16-bit groups. Returns null when it cannot be parsed. */
|
|
12
|
+
export declare function expandIPv6(ip: string): number[] | null;
|
|
13
|
+
export declare function isPublicIPv6(ip: string): boolean;
|
|
14
|
+
export declare function isPublicAddress(ip: string): boolean;
|
|
15
|
+
/** Throws when the host name itself is a non-public literal or a local name. */
|
|
16
|
+
export declare function assertPublicHost(hostname: string): void;
|
|
17
|
+
export declare function assertPublicResolved(hostname: string, address: string): void;
|
package/dist/src/netguard.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Address policy for the URL mode: only public unicast addresses are fetched. The check runs on the
|
|
2
2
|
// URL host, on every DNS answer and on every redirect target, and the checked address is the one the
|
|
3
|
-
// socket connects to (see fetch.ts).
|
|
4
|
-
|
|
3
|
+
// socket connects to (see fetch.ts). No Node.js import: the same policy is used by hosts that fetch
|
|
4
|
+
// with their own transport, such as a Cloudflare Worker (see core.ts).
|
|
5
5
|
export class BlockedAddressError extends Error {
|
|
6
6
|
constructor(message) {
|
|
7
7
|
super(message);
|
|
@@ -29,6 +29,50 @@ const V4_BLOCKED = [
|
|
|
29
29
|
['224.0.0.0', 4],
|
|
30
30
|
['240.0.0.0', 4],
|
|
31
31
|
];
|
|
32
|
+
const V4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
|
|
33
|
+
const V4_RE = new RegExp(`^(?:${V4_OCTET}\\.){3}${V4_OCTET}$`);
|
|
34
|
+
/**
|
|
35
|
+
* IP version of a literal: 4, 6, or 0 when the string is neither. Dotted-quad IPv4 without leading
|
|
36
|
+
* zeros, and IPv6 with at most one "::", hex groups of one to four digits, an optional dotted-quad
|
|
37
|
+
* tail and an optional zone. test/core.test.ts compares the answers with node:net isIP.
|
|
38
|
+
*/
|
|
39
|
+
export function ipVersion(s) {
|
|
40
|
+
if (V4_RE.test(s))
|
|
41
|
+
return 4;
|
|
42
|
+
if (!s.includes(':'))
|
|
43
|
+
return 0;
|
|
44
|
+
let addr = s;
|
|
45
|
+
const zone = addr.indexOf('%');
|
|
46
|
+
if (zone >= 0) {
|
|
47
|
+
if (!/^[0-9a-zA-Z.:-]+$/.test(addr.slice(zone + 1)))
|
|
48
|
+
return 0;
|
|
49
|
+
addr = addr.slice(0, zone);
|
|
50
|
+
}
|
|
51
|
+
if (!/^[0-9a-fA-F:.]+$/.test(addr))
|
|
52
|
+
return 0;
|
|
53
|
+
const lastColon = addr.lastIndexOf(':');
|
|
54
|
+
const tail = addr.slice(lastColon + 1);
|
|
55
|
+
if (tail.includes('.')) {
|
|
56
|
+
if (!V4_RE.test(tail))
|
|
57
|
+
return 0;
|
|
58
|
+
addr = addr.slice(0, lastColon + 1) + '0:0';
|
|
59
|
+
}
|
|
60
|
+
if (addr.includes('.'))
|
|
61
|
+
return 0;
|
|
62
|
+
const halves = addr.split('::');
|
|
63
|
+
if (halves.length > 2)
|
|
64
|
+
return 0;
|
|
65
|
+
const groups = (h) => (h === '' ? [] : h.split(':'));
|
|
66
|
+
const head = groups(halves[0]);
|
|
67
|
+
const rest = halves.length === 2 ? groups(halves[1]) : [];
|
|
68
|
+
for (const g of [...head, ...rest])
|
|
69
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(g))
|
|
70
|
+
return 0;
|
|
71
|
+
const count = head.length + rest.length;
|
|
72
|
+
if (halves.length === 1)
|
|
73
|
+
return count === 8 ? 6 : 0;
|
|
74
|
+
return count <= 7 ? 6 : 0;
|
|
75
|
+
}
|
|
32
76
|
export function isPublicIPv4(ip) {
|
|
33
77
|
const n = ipv4ToInt(ip);
|
|
34
78
|
for (const [base, bits] of V4_BLOCKED) {
|
|
@@ -103,7 +147,7 @@ function v4FromGroups(hi, lo) {
|
|
|
103
147
|
return `${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}`;
|
|
104
148
|
}
|
|
105
149
|
export function isPublicAddress(ip) {
|
|
106
|
-
const v =
|
|
150
|
+
const v = ipVersion(ip);
|
|
107
151
|
if (v === 4)
|
|
108
152
|
return isPublicIPv4(ip);
|
|
109
153
|
if (v === 6)
|
|
@@ -118,7 +162,7 @@ export function assertPublicHost(hostname) {
|
|
|
118
162
|
if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.home.arpa') || h === '') {
|
|
119
163
|
throw new BlockedAddressError(`Host "${hostname}" is a local name and is not fetched.`);
|
|
120
164
|
}
|
|
121
|
-
if (
|
|
165
|
+
if (ipVersion(h) !== 0 && !isPublicAddress(h)) {
|
|
122
166
|
throw new BlockedAddressError(`Address ${h} is not a public address and is not fetched.`);
|
|
123
167
|
}
|
|
124
168
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare function strictNormalize(text: string): string;
|
|
2
|
+
export declare function looseNormalize(text: string): string;
|
|
3
|
+
/** Code content: normalize line endings and strip a trailing newline only. */
|
|
4
|
+
export declare function normalizeCode(code: string): string;
|
|
5
|
+
/** Extracts numeric tokens (prices, percentages, dates, versions, signed values) in source order. */
|
|
6
|
+
export declare function extractNumbers(text: string): string[];
|
|
7
|
+
/** Report excerpt: URLs inside the text are masked BEFORE truncation, so a cut query value cannot leak. */
|
|
8
|
+
export declare function excerpt(text: string, max?: number): string;
|
|
9
|
+
/** Masks query values and fragments of every URL-like run in a piece of report text. */
|
|
10
|
+
export declare function redactText(text: string): string;
|
|
11
|
+
/** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
|
|
12
|
+
export declare function resolveHref(rawHref: string, base: string | null): string | null;
|
|
13
|
+
/** Masks query values and drops the fragment for display in reports and logs. Never returns the raw
|
|
14
|
+
* query of an unparseable input either. */
|
|
15
|
+
export declare function maskUrl(url: string): string;
|
|
16
|
+
/** Masks query values and drops the fragment of an absolute or relative href for display. */
|
|
17
|
+
export declare function maskHref(href: string): string;
|
|
18
|
+
/** Describes how two hrefs differ without revealing masked parts. */
|
|
19
|
+
export declare function hrefDifference(a: string, b: string): string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Report } from './run.js';
|
|
2
|
+
/** Reporting boundary: every string that leaves the tool goes through redactText. Internal comparison
|
|
3
|
+
* has already happened on the original values. */
|
|
4
|
+
export declare function redactReport(report: Report): Report;
|
|
5
|
+
export declare function renderJson(input: Report): string;
|
|
6
|
+
export declare function renderText(input: Report): string;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type AlignmentLimits } from './align.js';
|
|
2
|
+
import { type Coverage } from './compare.js';
|
|
3
|
+
import { MAX_NESTING_DEPTH } from './html.js';
|
|
4
|
+
import type { Finding } from './model.js';
|
|
5
|
+
import { maskUrl } from './normalize.js';
|
|
6
|
+
export interface SourceMeta {
|
|
7
|
+
kind: 'url' | 'file';
|
|
8
|
+
/** Masked final URL (query values hidden, fragment dropped). */
|
|
9
|
+
url?: string;
|
|
10
|
+
requestedUrl?: string;
|
|
11
|
+
file?: string;
|
|
12
|
+
status?: number;
|
|
13
|
+
contentType?: string | null;
|
|
14
|
+
accept?: string;
|
|
15
|
+
redirects?: number;
|
|
16
|
+
bytes: number;
|
|
17
|
+
/** Masked base URL used for link resolution, when known. */
|
|
18
|
+
baseUrl?: string | null;
|
|
19
|
+
}
|
|
20
|
+
export interface SourceInput {
|
|
21
|
+
meta: SourceMeta;
|
|
22
|
+
body: string;
|
|
23
|
+
/** Unmasked base URL for link resolution; never written to the report. */
|
|
24
|
+
base: string | null;
|
|
25
|
+
}
|
|
26
|
+
export interface RunOptions {
|
|
27
|
+
selector?: string;
|
|
28
|
+
/** Markdown front matter handling; 'keep' by default (nothing removed). */
|
|
29
|
+
frontMatter?: 'keep' | 'strip';
|
|
30
|
+
strict: boolean;
|
|
31
|
+
mode: 'url' | 'offline';
|
|
32
|
+
/** Lower alignment limits for a host with a smaller CPU or memory budget. Omitted: the CLI defaults
|
|
33
|
+
* (DEFAULT_LIMITS). The limits never change a finding; they only decide when the run stops with an
|
|
34
|
+
* error instead of completing. */
|
|
35
|
+
limits?: Partial<RunLimits>;
|
|
36
|
+
}
|
|
37
|
+
/** Every resource limit of a run: the alignment limits plus the nesting depth both extractors accept. */
|
|
38
|
+
export type RunLimits = AlignmentLimits & {
|
|
39
|
+
maxNestingDepth: number;
|
|
40
|
+
};
|
|
41
|
+
export { MAX_NESTING_DEPTH };
|
|
42
|
+
export interface ExtractionMeta {
|
|
43
|
+
strategy: string;
|
|
44
|
+
confidence: 'high' | 'low';
|
|
45
|
+
blockCount: number;
|
|
46
|
+
notes: string[];
|
|
47
|
+
}
|
|
48
|
+
export interface Report {
|
|
49
|
+
schemaVersion: 1;
|
|
50
|
+
toolVersion: string;
|
|
51
|
+
generatedAt: string;
|
|
52
|
+
mode: 'url' | 'offline';
|
|
53
|
+
sources: {
|
|
54
|
+
html: SourceMeta;
|
|
55
|
+
markdown: SourceMeta;
|
|
56
|
+
};
|
|
57
|
+
extraction: {
|
|
58
|
+
html: ExtractionMeta;
|
|
59
|
+
markdown: ExtractionMeta;
|
|
60
|
+
} | null;
|
|
61
|
+
summary: {
|
|
62
|
+
result: 'pass' | 'fail' | 'error';
|
|
63
|
+
strict: boolean;
|
|
64
|
+
errors: number;
|
|
65
|
+
warnings: number;
|
|
66
|
+
infos: number;
|
|
67
|
+
coverage: Coverage | null;
|
|
68
|
+
exitCode: 0 | 1 | 2;
|
|
69
|
+
/** Present when the comparison could not be completed reliably. */
|
|
70
|
+
error?: string;
|
|
71
|
+
};
|
|
72
|
+
findings: Finding[];
|
|
73
|
+
limitations: string[];
|
|
74
|
+
}
|
|
75
|
+
export declare class RunError extends Error {
|
|
76
|
+
constructor(message: string);
|
|
77
|
+
}
|
|
78
|
+
export declare const LIMITATIONS: string[];
|
|
79
|
+
/** Findings about how the Markdown was delivered, produced by the URL mode before extraction. */
|
|
80
|
+
export declare function deliveryFindings(md: SourceMeta, body: string): Finding[];
|
|
81
|
+
export declare function run(html: SourceInput, markdown: SourceInput, options: RunOptions): Report;
|
|
82
|
+
export declare function errorReport(options: RunOptions, html: SourceMeta | null, markdown: SourceMeta | null, message: string): Report;
|
|
83
|
+
export { maskUrl };
|
package/dist/src/run.js
CHANGED
|
@@ -2,10 +2,19 @@
|
|
|
2
2
|
// builds the report object. No argument parsing and no I/O here.
|
|
3
3
|
import { AlignmentLimitError } from './align.js';
|
|
4
4
|
import { compare } from './compare.js';
|
|
5
|
-
import { extractHtml, HtmlExtractError } from './html.js';
|
|
6
|
-
import { extractMarkdown } from './markdown.js';
|
|
5
|
+
import { extractHtml, HtmlExtractError, MAX_NESTING_DEPTH } from './html.js';
|
|
6
|
+
import { extractMarkdown, MarkdownExtractError } from './markdown.js';
|
|
7
7
|
import { maskUrl } from './normalize.js';
|
|
8
8
|
import { TOOL_VERSION } from './version.js';
|
|
9
|
+
export { MAX_NESTING_DEPTH };
|
|
10
|
+
/** Parser stack exhaustion on hostile nesting is reported as a comparison error, never as a crash. */
|
|
11
|
+
function extractionError(side, err) {
|
|
12
|
+
if (err instanceof HtmlExtractError || err instanceof MarkdownExtractError)
|
|
13
|
+
return new RunError(err.message);
|
|
14
|
+
if (err instanceof RangeError)
|
|
15
|
+
return new RunError(`The ${side} could not be parsed within the call stack (${err.message}); it is nested too deeply to compare.`);
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
9
18
|
export class RunError extends Error {
|
|
10
19
|
constructor(message) {
|
|
11
20
|
super(message);
|
|
@@ -82,16 +91,23 @@ export function run(html, markdown, options) {
|
|
|
82
91
|
report.summary = { ...report.summary, ...c, result: 'fail', exitCode: 1 };
|
|
83
92
|
return report;
|
|
84
93
|
}
|
|
94
|
+
const maxDepth = options.limits?.maxNestingDepth ?? MAX_NESTING_DEPTH;
|
|
95
|
+
if (typeof maxDepth !== 'number' || Number.isNaN(maxDepth) || maxDepth <= 0)
|
|
96
|
+
throw new TypeError(`Limit maxNestingDepth must be a positive number (got ${String(maxDepth)}).`);
|
|
85
97
|
let h;
|
|
86
98
|
try {
|
|
87
|
-
h = extractHtml(html.body, { selector: options.selector, baseUrl: html.base });
|
|
99
|
+
h = extractHtml(html.body, { selector: options.selector, baseUrl: html.base, maxDepth });
|
|
88
100
|
}
|
|
89
101
|
catch (err) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
102
|
+
throw extractionError('HTML', err) ?? err;
|
|
103
|
+
}
|
|
104
|
+
let m;
|
|
105
|
+
try {
|
|
106
|
+
m = extractMarkdown(markdown.body, { baseUrl: markdown.base, frontMatter: options.frontMatter ?? 'keep', maxDepth });
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
throw extractionError('Markdown', err) ?? err;
|
|
93
110
|
}
|
|
94
|
-
const m = extractMarkdown(markdown.body, { baseUrl: markdown.base, frontMatter: options.frontMatter ?? 'keep' });
|
|
95
111
|
report.extraction = { html: meta(h), markdown: meta(m) };
|
|
96
112
|
if (h.blocks.length === 0)
|
|
97
113
|
throw new RunError(`HTML main content is empty (strategy ${h.strategy}); nothing to compare.`);
|
|
@@ -99,7 +115,7 @@ export function run(html, markdown, options) {
|
|
|
99
115
|
throw new RunError('Markdown content is empty; nothing to compare.');
|
|
100
116
|
let result;
|
|
101
117
|
try {
|
|
102
|
-
result = compare(h, m, { bothBases: html.base !== null && markdown.base !== null });
|
|
118
|
+
result = compare(h, m, { bothBases: html.base !== null && markdown.base !== null, limits: options.limits });
|
|
103
119
|
}
|
|
104
120
|
catch (err) {
|
|
105
121
|
if (err instanceof AlignmentLimitError)
|
package/dist/src/version.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export const TOOL_NAME =
|
|
5
|
-
export const TOOL_VERSION =
|
|
1
|
+
// Tool name and version as literals, so the comparison core has no Node.js import and runs in a
|
|
2
|
+
// Cloudflare Worker as well as under Node.js. test/version.test.ts fails the build when these differ
|
|
3
|
+
// from package.json, which stays the version the release workflow publishes.
|
|
4
|
+
export const TOOL_NAME = 'markdown-parity-check';
|
|
5
|
+
export const TOOL_VERSION = '0.2.0';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markdown-parity-check",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
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",
|
|
@@ -21,6 +21,15 @@
|
|
|
21
21
|
"url": "https://github.com/erekola/markdown-parity-check/issues"
|
|
22
22
|
},
|
|
23
23
|
"type": "module",
|
|
24
|
+
"main": "./dist/src/core.js",
|
|
25
|
+
"types": "./dist/src/core.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/src/core.d.ts",
|
|
29
|
+
"default": "./dist/src/core.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
24
33
|
"engines": {
|
|
25
34
|
"node": ">=22.0.0"
|
|
26
35
|
},
|