@v1nvn/readability 0.44.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +3 -3
  2. package/package.json +7 -9
  3. package/src/cli.js +99 -0
  4. package/src/cli.ts +134 -0
  5. package/src/config.js +29 -0
  6. package/src/config.ts +42 -0
  7. package/src/dev.js +55 -0
  8. package/src/dev.ts +77 -0
  9. package/src/errors.js +16 -0
  10. package/src/errors.ts +19 -0
  11. package/src/handler.js +4 -0
  12. package/src/handler.ts +8 -0
  13. package/src/host-sampling.js +57 -0
  14. package/src/host-sampling.ts +86 -0
  15. package/src/index.js +23 -0
  16. package/src/index.ts +27 -0
  17. package/src/logger.js +2 -0
  18. package/src/logger.ts +3 -0
  19. package/src/output/format.js +92 -0
  20. package/src/output/format.ts +132 -0
  21. package/src/pipeline/cell-text.js +51 -0
  22. package/src/pipeline/cell-text.ts +56 -0
  23. package/src/pipeline/context.js +1 -0
  24. package/src/pipeline/context.ts +88 -0
  25. package/src/pipeline/dom.js +16 -0
  26. package/src/pipeline/dom.ts +23 -0
  27. package/src/pipeline/footnotes.js +148 -0
  28. package/src/pipeline/footnotes.ts +181 -0
  29. package/src/pipeline/math.js +113 -0
  30. package/src/pipeline/math.ts +130 -0
  31. package/src/pipeline/normalize.js +507 -0
  32. package/src/pipeline/normalize.ts +594 -0
  33. package/src/pipeline/readability.js +10 -0
  34. package/src/pipeline/readability.ts +36 -0
  35. package/src/pipeline/resolver.js +113 -0
  36. package/src/pipeline/resolver.ts +143 -0
  37. package/src/pipeline/sanitize.js +26 -0
  38. package/src/pipeline/sanitize.ts +42 -0
  39. package/src/pipeline/tables.js +239 -0
  40. package/src/pipeline/tables.ts +286 -0
  41. package/src/pipeline/turndown.js +153 -0
  42. package/src/pipeline/turndown.ts +191 -0
  43. package/src/pipeline/urls.js +14 -0
  44. package/src/pipeline/urls.ts +13 -0
  45. package/src/policy/chunk.js +365 -0
  46. package/src/policy/chunk.ts +482 -0
  47. package/src/policy/diagnostics.js +53 -0
  48. package/src/policy/diagnostics.ts +96 -0
  49. package/src/policy/explain.js +104 -0
  50. package/src/policy/explain.ts +182 -0
  51. package/src/policy/fallback.js +68 -0
  52. package/src/policy/fallback.ts +110 -0
  53. package/src/policy/gating.js +90 -0
  54. package/src/policy/gating.ts +106 -0
  55. package/src/policy/grid-detector.js +207 -0
  56. package/src/policy/grid-detector.ts +313 -0
  57. package/src/policy/identifiers.js +62 -0
  58. package/src/policy/identifiers.ts +75 -0
  59. package/src/policy/images.js +49 -0
  60. package/src/policy/images.ts +64 -0
  61. package/src/policy/list-detector.js +232 -0
  62. package/src/policy/list-detector.ts +308 -0
  63. package/src/policy/lost-signal.js +44 -0
  64. package/src/policy/lost-signal.ts +69 -0
  65. package/src/policy/markdown.js +58 -0
  66. package/src/policy/markdown.ts +76 -0
  67. package/src/policy/metadata.js +216 -0
  68. package/src/policy/metadata.ts +312 -0
  69. package/src/policy/outline-chains.js +165 -0
  70. package/src/policy/outline-chains.ts +215 -0
  71. package/src/policy/outline.js +71 -0
  72. package/src/policy/outline.ts +89 -0
  73. package/src/policy/pagination.js +79 -0
  74. package/src/policy/pagination.ts +104 -0
  75. package/src/policy/presets.js +100 -0
  76. package/src/policy/presets.ts +142 -0
  77. package/src/policy/section.js +111 -0
  78. package/src/policy/section.ts +127 -0
  79. package/src/policy/selector-lint.js +143 -0
  80. package/src/policy/selector-lint.ts +186 -0
  81. package/src/policy/sibling-scan.js +92 -0
  82. package/src/policy/sibling-scan.ts +99 -0
  83. package/src/policy/text.js +18 -0
  84. package/src/policy/text.ts +36 -0
  85. package/src/policy/truncate.js +45 -0
  86. package/src/policy/truncate.ts +59 -0
  87. package/src/preset-cache.js +165 -0
  88. package/src/preset-cache.ts +221 -0
  89. package/src/resources.js +227 -0
  90. package/src/resources.ts +317 -0
  91. package/src/sampling.js +45 -0
  92. package/src/sampling.ts +74 -0
  93. package/src/server.js +73 -0
  94. package/src/server.ts +85 -0
  95. package/src/tools/chunk_text.js +40 -0
  96. package/src/tools/chunk_text.ts +65 -0
  97. package/src/tools/explain.js +200 -0
  98. package/src/tools/explain.ts +299 -0
  99. package/src/tools/extract.js +263 -0
  100. package/src/tools/extract.ts +368 -0
  101. package/src/tools/extract_grid.js +56 -0
  102. package/src/tools/extract_grid.ts +90 -0
  103. package/src/tools/extract_links.js +98 -0
  104. package/src/tools/extract_links.ts +138 -0
  105. package/src/tools/extract_list.js +66 -0
  106. package/src/tools/extract_list.ts +97 -0
  107. package/src/tools/extract_metadata.js +67 -0
  108. package/src/tools/extract_metadata.ts +102 -0
  109. package/src/tools/extract_section.js +56 -0
  110. package/src/tools/extract_section.ts +84 -0
  111. package/src/tools/extract_tables.js +59 -0
  112. package/src/tools/extract_tables.ts +101 -0
  113. package/src/tools/html-source.js +30 -0
  114. package/src/tools/html-source.ts +40 -0
  115. package/src/tools/html_to_markdown.js +113 -0
  116. package/src/tools/html_to_markdown.ts +180 -0
  117. package/src/tools/outline.js +47 -0
  118. package/src/tools/outline.ts +77 -0
  119. package/src/tools/output-schema.js +504 -0
  120. package/src/tools/output-schema.ts +715 -0
  121. package/src/tools/schemas.js +288 -0
  122. package/src/tools/schemas.ts +442 -0
  123. package/src/tools/suggest-preset.js +504 -0
  124. package/src/tools/suggest-preset.ts +708 -0
  125. package/src/types/jsdom.d.ts +15 -0
  126. package/src/types/turndown-plugin-gfm.d.ts +11 -0
  127. package/dist/assets/cli-Dfjg7dOQ.js +0 -76
  128. package/dist/assets/cli-Dfjg7dOQ.js.map +0 -1
  129. package/dist/assets/extract-CdDp-KwX.js +0 -2880
  130. package/dist/assets/extract-CdDp-KwX.js.map +0 -1
  131. package/dist/index.js +0 -2267
  132. package/dist/index.js.map +0 -1
@@ -0,0 +1,127 @@
1
+ import { isElement } from '../pipeline/dom.ts';
2
+ import { normalizeHeadingText } from './outline.ts';
3
+
4
+ interface HeadingMatch {
5
+ readonly heading: Element;
6
+ readonly level: number;
7
+ }
8
+
9
+ // Match the first heading by normalized text. Exact equality wins; otherwise
10
+ // fall back to the first substring match so a short query ("auth") still
11
+ // lands on a longer heading ("Authentication") without forcing an exact match.
12
+ function findHeading(
13
+ document: Document,
14
+ query: string,
15
+ ): HeadingMatch | undefined {
16
+ const needle = normalizeHeadingText(query).toLowerCase();
17
+ if (!needle) {
18
+ return undefined;
19
+ }
20
+ const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
21
+ let substring: HeadingMatch | undefined;
22
+ for (const heading of headings) {
23
+ const text = normalizeHeadingText(heading.textContent).toLowerCase();
24
+ if (!text) {
25
+ continue;
26
+ }
27
+ const level = Number.parseInt(heading.tagName.slice(1), 10);
28
+ if (text === needle) {
29
+ return { heading, level };
30
+ }
31
+ if (!substring && text.includes(needle)) {
32
+ substring = { heading, level };
33
+ }
34
+ }
35
+ return substring;
36
+ }
37
+
38
+ // Elements whose direct children form the section flow. The matched heading's
39
+ // nearest such ancestor is the level at which the section's content lives as
40
+ // siblings: on docs sites (GitHub markdown, etc.) the heading is wrapped in
41
+ // <div class="markdown-heading">, so the body <p> is a sibling of the wrapper
42
+ // div, not of the <h2>. Walking the <h2>'s own siblings would capture only the
43
+ // permalink anchor and miss the body.
44
+ const FLOW_CONTAINERS = new Set([
45
+ 'ARTICLE',
46
+ 'ASIDE',
47
+ 'BLOCKQUOTE',
48
+ 'BODY',
49
+ 'DD',
50
+ 'DETAILS',
51
+ 'DT',
52
+ 'FOOTER',
53
+ 'HEADER',
54
+ 'LI',
55
+ 'MAIN',
56
+ 'NAV',
57
+ 'SECTION',
58
+ 'TD',
59
+ ]);
60
+
61
+ function findFlowContainer(heading: Element): Element {
62
+ let ancestor: Element | null = heading.parentElement;
63
+ while (ancestor) {
64
+ if (FLOW_CONTAINERS.has(ancestor.tagName)) {
65
+ return ancestor;
66
+ }
67
+ ancestor = ancestor.parentElement;
68
+ }
69
+ // BODY is in FLOW_CONTAINERS, so the loop reaches it for any attached
70
+ // heading; this fallback only covers a detached heading.
71
+ return heading.ownerDocument.body;
72
+ }
73
+
74
+ // Level of the first heading at or inside `el`, or undefined when `el` is
75
+ // neither a heading nor a wrapper around one. Used to test whether a following
76
+ // sibling terminates the section.
77
+ function firstHeadingLevel(el: Element): number | undefined {
78
+ const direct = /^H([1-6])$/.exec(el.tagName);
79
+ if (direct) {
80
+ return Number.parseInt(direct[1], 10);
81
+ }
82
+ const inner = el.querySelector('h1, h2, h3, h4, h5, h6');
83
+ if (inner) {
84
+ return Number.parseInt(inner.tagName.slice(1), 10);
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ // Wraps the matched heading and its subtree in a `<section data-rdrm-section-scope>`
90
+ // so the existing selectors.include path can isolate it. Returns false (and
91
+ // leaves the document untouched) when no heading matches.
92
+ export function scopeToHeading(
93
+ document: Document,
94
+ headingText: string,
95
+ ): boolean {
96
+ const match = findHeading(document, headingText);
97
+ if (!match) {
98
+ return false;
99
+ }
100
+ const { heading, level } = match;
101
+ const container = findFlowContainer(heading);
102
+ let startChild: Element = heading;
103
+ while (startChild.parentElement && startChild.parentElement !== container) {
104
+ startChild = startChild.parentElement;
105
+ }
106
+ const wrap = document.createElement('section');
107
+ wrap.setAttribute('data-rdrm-section-scope', '');
108
+ container.insertBefore(wrap, startChild);
109
+ let node: Node | null = startChild;
110
+ while (node) {
111
+ const next: Node | null = node.nextSibling;
112
+ wrap.appendChild(node);
113
+ // A section ends at the next same-or-higher-level heading (level <= L):
114
+ // deeper headings (h3 under an h2) belong to this section, peers and
115
+ // shallower headings start the next one. The terminating sibling may be a
116
+ // wrapper around the heading (e.g. <div class="markdown-heading">), so the
117
+ // check looks for a heading at OR inside the sibling.
118
+ if (next !== null && isElement(next)) {
119
+ const nextLevel = firstHeadingLevel(next);
120
+ if (nextLevel !== undefined && nextLevel <= level) {
121
+ break;
122
+ }
123
+ }
124
+ node = next;
125
+ }
126
+ return true;
127
+ }
@@ -0,0 +1,143 @@
1
+ import { isGeneratedIdentifier } from "./identifiers.js";
2
+ import { selectorMisses } from "./presets.js";
3
+ // nwsapi/jsdom accept `:contains` and silently apply it, so an engine error can
4
+ // reject nothing — the rejection has to happen here, before any selector
5
+ // reaches querySelector. Positional pseudos are rejected as a family: they
6
+ // describe this render's child order, not the site's structure.
7
+ const POSITIONAL_PSEUDO_RE = /:(?:nth(?:-last)?(?:-child|-of-type)|first(?:-child|-of-type)|last(?:-child|-of-type)|only(?:-child|-of-type))\b/i;
8
+ const CONTAINS_PSEUDO_RE = /:contains\s*\(/i;
9
+ function quotedSegmentsOut(selector) {
10
+ return selector.replace(/(["'])(?:\\.|(?!\1)[\s\S])*\1/g, '""');
11
+ }
12
+ // `.class` and `#id` tokens are identifiers; `[attr="value"]` values are
13
+ // substring matches against whatever the site emitted and are exempt.
14
+ function identifierTokens(selector) {
15
+ return [...quotedSegmentsOut(selector).matchAll(/[.#]([A-Za-z0-9_-]+)/g)].map(match => match[1]);
16
+ }
17
+ export function lintSelectorText(selector) {
18
+ if (CONTAINS_PSEUDO_RE.test(selector)) {
19
+ return {
20
+ kind: 'contains-pseudo',
21
+ selector,
22
+ detail: ':contains is not standard CSS and changes the result silently',
23
+ };
24
+ }
25
+ const positional = POSITIONAL_PSEUDO_RE.exec(selector);
26
+ if (positional) {
27
+ return {
28
+ kind: 'positional-pseudo',
29
+ selector,
30
+ detail: `${positional[0]} depends on this page's child order, not the site's layout`,
31
+ };
32
+ }
33
+ for (const token of identifierTokens(selector)) {
34
+ if (isGeneratedIdentifier(token)) {
35
+ return {
36
+ kind: 'generated-identifier',
37
+ selector,
38
+ detail: `"${token}" reads as a generated hash that changes on deploy`,
39
+ };
40
+ }
41
+ }
42
+ return undefined;
43
+ }
44
+ // Propose-time validation for a preset a suggester wants stored. Stricter than
45
+ // presetMatches: an exclude that matches nothing is tolerated at runtime (the
46
+ // debris is absent from some pages) but at propose time it is a mistake — the
47
+ // proposal names debris that is not there.
48
+ export function lintProposal({ document, detectors, scope, }) {
49
+ const violations = [];
50
+ const selectors = [
51
+ ...detectors,
52
+ ...(scope.include ? [scope.include] : []),
53
+ ...(scope.exclude ?? []),
54
+ ];
55
+ for (const selector of selectors) {
56
+ const violation = lintSelectorText(selector);
57
+ if (violation) {
58
+ violations.push(violation);
59
+ }
60
+ }
61
+ let includeRoot;
62
+ if (scope.include &&
63
+ !violations.some(violation => violation.selector === scope.include)) {
64
+ try {
65
+ includeRoot = document.body.querySelector(scope.include) ?? undefined;
66
+ }
67
+ catch {
68
+ violations.push({
69
+ kind: 'unparseable',
70
+ selector: scope.include,
71
+ detail: 'the selector engine rejects this selector',
72
+ });
73
+ }
74
+ }
75
+ for (const detector of detectors) {
76
+ if (violations.some(violation => violation.selector === detector)) {
77
+ continue;
78
+ }
79
+ if (selectorMisses(document, detector)) {
80
+ violations.push({
81
+ kind: 'no-match',
82
+ selector: detector,
83
+ detail: 'detector matches nothing on this page',
84
+ });
85
+ }
86
+ }
87
+ if (scope.include &&
88
+ !includeRoot &&
89
+ !violations.some(violation => violation.selector === scope.include)) {
90
+ violations.push({
91
+ kind: 'no-match',
92
+ selector: scope.include,
93
+ detail: 'include matches nothing inside <body>, where applySelectors searches',
94
+ });
95
+ }
96
+ for (const selector of scope.exclude ?? []) {
97
+ if (violations.some(violation => violation.selector === selector)) {
98
+ continue;
99
+ }
100
+ try {
101
+ if (document.querySelectorAll(selector).length === 0) {
102
+ violations.push({
103
+ kind: 'no-match',
104
+ selector,
105
+ detail: 'exclude matches nothing on this page',
106
+ });
107
+ }
108
+ }
109
+ catch {
110
+ violations.push({
111
+ kind: 'unparseable',
112
+ selector,
113
+ detail: 'the selector engine rejects this selector',
114
+ });
115
+ }
116
+ }
117
+ // Excludes are removed document-wide before the include is applied, so an
118
+ // exclude matching an ancestor of the include root (or the root itself)
119
+ // deletes it, and the include then quietly no-ops over a damaged body.
120
+ if (includeRoot) {
121
+ for (const selector of scope.exclude ?? []) {
122
+ if (violations.some(violation => violation.selector === selector)) {
123
+ continue;
124
+ }
125
+ try {
126
+ for (const match of document.querySelectorAll(selector)) {
127
+ if (match.contains(includeRoot)) {
128
+ violations.push({
129
+ kind: 'exclude-shadows-include',
130
+ selector,
131
+ detail: 'this exclude removes the include root itself',
132
+ });
133
+ break;
134
+ }
135
+ }
136
+ }
137
+ catch {
138
+ // Already reported as unparseable.
139
+ }
140
+ }
141
+ }
142
+ return violations;
143
+ }
@@ -0,0 +1,186 @@
1
+ import { isGeneratedIdentifier } from './identifiers.ts';
2
+ import { selectorMisses } from './presets.ts';
3
+
4
+ export type SelectorViolationKind =
5
+ | 'contains-pseudo'
6
+ | 'exclude-shadows-include'
7
+ | 'generated-identifier'
8
+ | 'no-match'
9
+ | 'positional-pseudo'
10
+ | 'unparseable';
11
+
12
+ export interface SelectorViolation {
13
+ readonly detail: string;
14
+ readonly kind: SelectorViolationKind;
15
+ readonly selector: string;
16
+ }
17
+
18
+ export interface ProposalInput {
19
+ readonly detectors: readonly string[];
20
+ readonly document: Document;
21
+ readonly scope: {
22
+ readonly exclude?: readonly string[];
23
+ readonly include?: string;
24
+ };
25
+ }
26
+
27
+ // nwsapi/jsdom accept `:contains` and silently apply it, so an engine error can
28
+ // reject nothing — the rejection has to happen here, before any selector
29
+ // reaches querySelector. Positional pseudos are rejected as a family: they
30
+ // describe this render's child order, not the site's structure.
31
+ const POSITIONAL_PSEUDO_RE =
32
+ /:(?:nth(?:-last)?(?:-child|-of-type)|first(?:-child|-of-type)|last(?:-child|-of-type)|only(?:-child|-of-type))\b/i;
33
+ const CONTAINS_PSEUDO_RE = /:contains\s*\(/i;
34
+
35
+ function quotedSegmentsOut(selector: string): string {
36
+ return selector.replace(/(["'])(?:\\.|(?!\1)[\s\S])*\1/g, '""');
37
+ }
38
+
39
+ // `.class` and `#id` tokens are identifiers; `[attr="value"]` values are
40
+ // substring matches against whatever the site emitted and are exempt.
41
+ function identifierTokens(selector: string): string[] {
42
+ return [...quotedSegmentsOut(selector).matchAll(/[.#]([A-Za-z0-9_-]+)/g)].map(
43
+ match => match[1],
44
+ );
45
+ }
46
+
47
+ export function lintSelectorText(
48
+ selector: string,
49
+ ): SelectorViolation | undefined {
50
+ if (CONTAINS_PSEUDO_RE.test(selector)) {
51
+ return {
52
+ kind: 'contains-pseudo',
53
+ selector,
54
+ detail: ':contains is not standard CSS and changes the result silently',
55
+ };
56
+ }
57
+ const positional = POSITIONAL_PSEUDO_RE.exec(selector);
58
+ if (positional) {
59
+ return {
60
+ kind: 'positional-pseudo',
61
+ selector,
62
+ detail: `${positional[0]} depends on this page's child order, not the site's layout`,
63
+ };
64
+ }
65
+ for (const token of identifierTokens(selector)) {
66
+ if (isGeneratedIdentifier(token)) {
67
+ return {
68
+ kind: 'generated-identifier',
69
+ selector,
70
+ detail: `"${token}" reads as a generated hash that changes on deploy`,
71
+ };
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ // Propose-time validation for a preset a suggester wants stored. Stricter than
78
+ // presetMatches: an exclude that matches nothing is tolerated at runtime (the
79
+ // debris is absent from some pages) but at propose time it is a mistake — the
80
+ // proposal names debris that is not there.
81
+ export function lintProposal({
82
+ document,
83
+ detectors,
84
+ scope,
85
+ }: ProposalInput): readonly SelectorViolation[] {
86
+ const violations: SelectorViolation[] = [];
87
+ const selectors = [
88
+ ...detectors,
89
+ ...(scope.include ? [scope.include] : []),
90
+ ...(scope.exclude ?? []),
91
+ ];
92
+ for (const selector of selectors) {
93
+ const violation = lintSelectorText(selector);
94
+ if (violation) {
95
+ violations.push(violation);
96
+ }
97
+ }
98
+
99
+ let includeRoot: Element | undefined;
100
+ if (
101
+ scope.include &&
102
+ !violations.some(violation => violation.selector === scope.include)
103
+ ) {
104
+ try {
105
+ includeRoot = document.body.querySelector(scope.include) ?? undefined;
106
+ } catch {
107
+ violations.push({
108
+ kind: 'unparseable',
109
+ selector: scope.include,
110
+ detail: 'the selector engine rejects this selector',
111
+ });
112
+ }
113
+ }
114
+
115
+ for (const detector of detectors) {
116
+ if (violations.some(violation => violation.selector === detector)) {
117
+ continue;
118
+ }
119
+ if (selectorMisses(document, detector)) {
120
+ violations.push({
121
+ kind: 'no-match',
122
+ selector: detector,
123
+ detail: 'detector matches nothing on this page',
124
+ });
125
+ }
126
+ }
127
+ if (
128
+ scope.include &&
129
+ !includeRoot &&
130
+ !violations.some(violation => violation.selector === scope.include)
131
+ ) {
132
+ violations.push({
133
+ kind: 'no-match',
134
+ selector: scope.include,
135
+ detail:
136
+ 'include matches nothing inside <body>, where applySelectors searches',
137
+ });
138
+ }
139
+ for (const selector of scope.exclude ?? []) {
140
+ if (violations.some(violation => violation.selector === selector)) {
141
+ continue;
142
+ }
143
+ try {
144
+ if (document.querySelectorAll(selector).length === 0) {
145
+ violations.push({
146
+ kind: 'no-match',
147
+ selector,
148
+ detail: 'exclude matches nothing on this page',
149
+ });
150
+ }
151
+ } catch {
152
+ violations.push({
153
+ kind: 'unparseable',
154
+ selector,
155
+ detail: 'the selector engine rejects this selector',
156
+ });
157
+ }
158
+ }
159
+
160
+ // Excludes are removed document-wide before the include is applied, so an
161
+ // exclude matching an ancestor of the include root (or the root itself)
162
+ // deletes it, and the include then quietly no-ops over a damaged body.
163
+ if (includeRoot) {
164
+ for (const selector of scope.exclude ?? []) {
165
+ if (violations.some(violation => violation.selector === selector)) {
166
+ continue;
167
+ }
168
+ try {
169
+ for (const match of document.querySelectorAll(selector)) {
170
+ if (match.contains(includeRoot)) {
171
+ violations.push({
172
+ kind: 'exclude-shadows-include',
173
+ selector,
174
+ detail: 'this exclude removes the include root itself',
175
+ });
176
+ break;
177
+ }
178
+ }
179
+ } catch {
180
+ // Already reported as unparseable.
181
+ }
182
+ }
183
+ }
184
+
185
+ return violations;
186
+ }
@@ -0,0 +1,92 @@
1
+ import { isElement } from "../pipeline/dom.js";
2
+ // Shared pre-pass for the sibling-cluster detectors (list-detector,
3
+ // grid-detector). Both walk the document for a container whose direct children
4
+ // form a same-shape sibling group; the constants and helpers here are the
5
+ // heuristic-agnostic infrastructure that scan shares. Detector-specific scoring
6
+ // (anchor/pathname signals vs data-cell text) stays in each detector.
7
+ // Direct children are scanned only at these container levels. <tbody> covers
8
+ // HN's <table>-based layout; the rest cover semantic (<main>/<article>) and
9
+ // generic (<div>/<section>) wrappers. <table> is included for HTML that skips
10
+ // <tbody>; jsdom synthesizes one anyway, so this is mostly defensive.
11
+ export const CONTAINER_TAGS = new Set([
12
+ 'ARTICLE',
13
+ 'DIV',
14
+ 'MAIN',
15
+ 'OL',
16
+ 'SECTION',
17
+ 'TABLE',
18
+ 'TBODY',
19
+ 'UL',
20
+ ]);
21
+ // Subtrees that never carry a page's primary repeated structure. Stripping them
22
+ // is the false-positive guard: without it, an article's <nav> menu or footer
23
+ // link list would look identical to a feed/grid and the detectors would mis-fire
24
+ // on every page with chrome. Distinct from normalize.ts's stripChrome (which
25
+ // removes consent/overlay banners) — this is landmark chrome only.
26
+ const LANDMARK_CHROME_SELECTOR = 'nav, header, footer, aside, [role="navigation"], [role="banner"], ' +
27
+ '[role="contentinfo"], [role="complementary"], [role="search"], ' +
28
+ '[role="menu"], [role="menubar"]';
29
+ export function stripLandmarkChrome(document) {
30
+ for (const el of document.querySelectorAll(LANDMARK_CHROME_SELECTOR)) {
31
+ el.remove();
32
+ }
33
+ for (const el of document.querySelectorAll('script, style, template')) {
34
+ el.remove();
35
+ }
36
+ }
37
+ // Composite of tag + class signature so mixed siblings — e.g. HN's
38
+ // <tr class="athing"> title row vs classless <tr> subtext row, or a grid's
39
+ // header row vs data rows — split into separate candidate groups instead of
40
+ // blending into one ragged group.
41
+ export function shapeKey(el) {
42
+ const raw = el.getAttribute('class');
43
+ if (!raw) {
44
+ return el.tagName;
45
+ }
46
+ const normalized = raw.trim().split(/\s+/).sort().join(' ');
47
+ return normalized ? `${el.tagName}|${normalized}` : el.tagName;
48
+ }
49
+ // Group a container's direct element-children by shape so a homogeneous
50
+ // cluster surfaces as one candidate and mixed-shape siblings (header row vs
51
+ // data rows, HN's athing + subtext) split apart rather than blending.
52
+ export function groupChildrenByShape(container) {
53
+ const groups = new Map();
54
+ for (const child of Array.from(container.childNodes)) {
55
+ if (!isElement(child)) {
56
+ continue;
57
+ }
58
+ const key = shapeKey(child);
59
+ const bucket = groups.get(key);
60
+ if (bucket) {
61
+ bucket.push(child);
62
+ }
63
+ else {
64
+ groups.set(key, [child]);
65
+ }
66
+ }
67
+ return groups;
68
+ }
69
+ // tag#id.class hint for the winning container. Best-effort, not a unique
70
+ // locator — used only for diagnostics so a human can see which subtree won.
71
+ // `maxClasses` caps the class list for compact diagnostic output.
72
+ export function describeSelector(el, maxClasses) {
73
+ const parts = [el.tagName.toLowerCase()];
74
+ const id = el.getAttribute('id');
75
+ if (id) {
76
+ parts.push(`#${id}`);
77
+ }
78
+ const cls = el.getAttribute('class');
79
+ if (cls) {
80
+ let used = 0;
81
+ for (const token of cls.trim().split(/\s+/)) {
82
+ if (token) {
83
+ parts.push(`.${token}`);
84
+ used += 1;
85
+ }
86
+ if (maxClasses !== undefined && used >= maxClasses) {
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ return parts.join('');
92
+ }
@@ -0,0 +1,99 @@
1
+ import { isElement } from '../pipeline/dom.ts';
2
+
3
+ // Shared pre-pass for the sibling-cluster detectors (list-detector,
4
+ // grid-detector). Both walk the document for a container whose direct children
5
+ // form a same-shape sibling group; the constants and helpers here are the
6
+ // heuristic-agnostic infrastructure that scan shares. Detector-specific scoring
7
+ // (anchor/pathname signals vs data-cell text) stays in each detector.
8
+
9
+ // Direct children are scanned only at these container levels. <tbody> covers
10
+ // HN's <table>-based layout; the rest cover semantic (<main>/<article>) and
11
+ // generic (<div>/<section>) wrappers. <table> is included for HTML that skips
12
+ // <tbody>; jsdom synthesizes one anyway, so this is mostly defensive.
13
+ export const CONTAINER_TAGS = new Set([
14
+ 'ARTICLE',
15
+ 'DIV',
16
+ 'MAIN',
17
+ 'OL',
18
+ 'SECTION',
19
+ 'TABLE',
20
+ 'TBODY',
21
+ 'UL',
22
+ ]);
23
+
24
+ // Subtrees that never carry a page's primary repeated structure. Stripping them
25
+ // is the false-positive guard: without it, an article's <nav> menu or footer
26
+ // link list would look identical to a feed/grid and the detectors would mis-fire
27
+ // on every page with chrome. Distinct from normalize.ts's stripChrome (which
28
+ // removes consent/overlay banners) — this is landmark chrome only.
29
+ const LANDMARK_CHROME_SELECTOR =
30
+ 'nav, header, footer, aside, [role="navigation"], [role="banner"], ' +
31
+ '[role="contentinfo"], [role="complementary"], [role="search"], ' +
32
+ '[role="menu"], [role="menubar"]';
33
+
34
+ export function stripLandmarkChrome(document: Document): void {
35
+ for (const el of document.querySelectorAll(LANDMARK_CHROME_SELECTOR)) {
36
+ el.remove();
37
+ }
38
+ for (const el of document.querySelectorAll('script, style, template')) {
39
+ el.remove();
40
+ }
41
+ }
42
+
43
+ // Composite of tag + class signature so mixed siblings — e.g. HN's
44
+ // <tr class="athing"> title row vs classless <tr> subtext row, or a grid's
45
+ // header row vs data rows — split into separate candidate groups instead of
46
+ // blending into one ragged group.
47
+ export function shapeKey(el: Element): string {
48
+ const raw = el.getAttribute('class');
49
+ if (!raw) {
50
+ return el.tagName;
51
+ }
52
+ const normalized = raw.trim().split(/\s+/).sort().join(' ');
53
+ return normalized ? `${el.tagName}|${normalized}` : el.tagName;
54
+ }
55
+
56
+ // Group a container's direct element-children by shape so a homogeneous
57
+ // cluster surfaces as one candidate and mixed-shape siblings (header row vs
58
+ // data rows, HN's athing + subtext) split apart rather than blending.
59
+ export function groupChildrenByShape(container: Node): Map<string, Element[]> {
60
+ const groups = new Map<string, Element[]>();
61
+ for (const child of Array.from(container.childNodes)) {
62
+ if (!isElement(child)) {
63
+ continue;
64
+ }
65
+ const key = shapeKey(child);
66
+ const bucket = groups.get(key);
67
+ if (bucket) {
68
+ bucket.push(child);
69
+ } else {
70
+ groups.set(key, [child]);
71
+ }
72
+ }
73
+ return groups;
74
+ }
75
+
76
+ // tag#id.class hint for the winning container. Best-effort, not a unique
77
+ // locator — used only for diagnostics so a human can see which subtree won.
78
+ // `maxClasses` caps the class list for compact diagnostic output.
79
+ export function describeSelector(el: Element, maxClasses?: number): string {
80
+ const parts = [el.tagName.toLowerCase()];
81
+ const id = el.getAttribute('id');
82
+ if (id) {
83
+ parts.push(`#${id}`);
84
+ }
85
+ const cls = el.getAttribute('class');
86
+ if (cls) {
87
+ let used = 0;
88
+ for (const token of cls.trim().split(/\s+/)) {
89
+ if (token) {
90
+ parts.push(`.${token}`);
91
+ used += 1;
92
+ }
93
+ if (maxClasses !== undefined && used >= maxClasses) {
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ return parts.join('');
99
+ }
@@ -0,0 +1,18 @@
1
+ export const TOKEN_ESTIMATOR = 'chars/4';
2
+ export function estimateTokens(textContent) {
3
+ return {
4
+ tokenEstimate: Math.round(textContent.length / 4),
5
+ estimator: TOKEN_ESTIMATOR,
6
+ };
7
+ }
8
+ export function countWords(text) {
9
+ return (text.match(/\S+/g) ?? []).length;
10
+ }
11
+ export function nonEmpty(value) {
12
+ return value?.trim() ? value : undefined;
13
+ }
14
+ export function computeTextMetrics(text, wordsPerMinute) {
15
+ const wordCount = countWords(text);
16
+ const readingTimeMin = wordCount === 0 ? 0 : Math.max(1, Math.round(wordCount / wordsPerMinute));
17
+ return { wordCount, readingTimeMin, ...estimateTokens(text) };
18
+ }