page-markdown 0.1.5 → 0.3.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/src/extract.js CHANGED
@@ -1,10 +1,33 @@
1
1
  // Stage 3: pick the readable content. Default: Mozilla Readability on a copy
2
2
  // of the standardized clone, falling back to the whole body when it finds
3
- // nothing or too little.
3
+ // nothing or too little, and to the page's main content when it keeps only a
4
+ // small share of that (forum threads, product grids), brings the site's menu
5
+ // along, or keeps too few of its sections (product pages).
4
6
  // The class only: skips isProbablyReaderable, which the pipeline does not use.
5
7
  import Readability from "@mozilla/readability/Readability.js";
8
+ import { htmlText } from "./refine.js";
6
9
 
7
10
  export const DEFAULT_MIN_EXTRACT_CHARS = 100;
11
+ export const DEFAULT_MIN_EXTRACT_SHARE = 0.4;
12
+ // A small share of a short page may be all there is: don't fall back for less.
13
+ const MIN_MISSED_CHARS = 500;
14
+ export const PAGE_CHROME = "nav, footer, form, [role='navigation'], [role='banner'], [role='contentinfo'], [role='search']";
15
+ const MAIN = "main, [role='main']";
16
+ const COMMENTS = "#comments, #disqus_thread, .comments, .commentlist, .comment-list, .comment, [id^='comment-']";
17
+ const HIDDEN_STYLE = /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)/i;
18
+ const TOGGLE = "button, summary, [aria-expanded]";
19
+ // Shorter hidden text beside a button is a status message ("Added"), not an answer.
20
+ const MIN_ANSWER_CHARS = 40;
21
+ const MENU_SAMPLE_CHARS = 30;
22
+ // Fewer h2s than this, and a page has no sections to lose.
23
+ const MIN_SECTIONS = 3;
24
+ const SECTION_SHARE_FACTOR = 1.5;
25
+
26
+ // As far as a clone can tell, with no stylesheets. Not aria-hidden: shops put
27
+ // the price people see in it, beside a longer one for screen readers.
28
+ export function isHiddenElement(el) {
29
+ return el.hasAttribute("hidden") || HIDDEN_STYLE.test(el.getAttribute("style") || "");
30
+ }
8
31
 
9
32
  function textLength(html = "") {
10
33
  return String(html).replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim().length;
@@ -14,6 +37,121 @@ function bodyHtml(doc) {
14
37
  return (doc.body || doc.documentElement)?.innerHTML || "";
15
38
  }
16
39
 
40
+ // An accordion's answer, hidden until its button is pressed: FAQs on shop pages.
41
+ export function isCollapsedAnswer(el) {
42
+ return Boolean(el.previousElementSibling?.matches(TOGGLE)) && (el.textContent || "").trim().length >= MIN_ANSWER_CHARS;
43
+ }
44
+
45
+ // <main> or else the body, without navigation, other page chrome or anything
46
+ // hidden, except code behind a "Show code" toggle and collapsed answers. A header
47
+ // inside <main> usually belongs to the content; one in the body doesn't.
48
+ function mainContentRoot(doc) {
49
+ const main = doc.querySelector(MAIN);
50
+ const root = (main || doc.body || doc.documentElement).cloneNode(true);
51
+ for (const el of Array.from(root.querySelectorAll(`${PAGE_CHROME}, aside, template, [role='complementary']${main ? "" : ", header"}`))) el.remove();
52
+ for (const el of Array.from(root.querySelectorAll("[hidden], [style]"))) {
53
+ if (isHiddenElement(el) && !el.querySelector("pre") && !isCollapsedAnswer(el)) el.remove();
54
+ }
55
+ for (const link of Array.from(root.querySelectorAll("a[href^='#']"))) {
56
+ if (/^\s*skip\b/i.test(link.textContent || "")) link.remove();
57
+ }
58
+ return removeSkippableBoxes(root);
59
+ }
60
+
61
+ const withoutSpaces = (text) => text.replace(/\s+/g, "");
62
+
63
+ // Embedded posts and media sit in a skippable box too, and are part of the text.
64
+ const SKIP_KEPT = "blockquote, iframe, video, audio, pre, table, h1";
65
+ const MAX_END_MARKER_CHARS = 60;
66
+ const MAX_SKIPPED_SHARE = 0.25;
67
+
68
+ // "Skip Most read and continue reading": a box that opens with a link to the end
69
+ // marker it closes with. The page itself says it interrupts the text (BBC's
70
+ // most-read and podcast boxes), in whatever language.
71
+ function removeSkippableBoxes(root) {
72
+ const size = (el) => withoutSpaces(el.textContent || "");
73
+ const total = size(root).length;
74
+ for (const link of Array.from(root.querySelectorAll("a[href^='#']"))) {
75
+ const id = link.getAttribute("href").slice(1).replace(/["\\]/g, "\\$&");
76
+ const label = size(link);
77
+ if (!id || !label || !root.contains(link)) continue;
78
+ let box = link.parentElement;
79
+ let end = null;
80
+ while (box && box !== root && !(end = box.querySelector(`[id="${id}"]`))) box = box.parentElement;
81
+ if (!end || end.contains(link) || box.matches("main, article, body")) continue;
82
+ const marker = size(end);
83
+ const text = size(box);
84
+ if (marker && marker.length <= MAX_END_MARKER_CHARS && text.length > label.length + marker.length
85
+ && text.length <= total * MAX_SKIPPED_SHARE && text.startsWith(label) && text.endsWith(marker)
86
+ && !box.querySelector(SKIP_KEPT)) box.remove();
87
+ }
88
+ return root;
89
+ }
90
+
91
+ // An article above its comments, where Readability kept the article: what's left
92
+ // without them. null for a thread, where what Readability kept is itself a comment.
93
+ function articleWithoutComments(root, articleHtml) {
94
+ const comments = Array.from(root.querySelectorAll(COMMENTS));
95
+ if (!comments.length) return null;
96
+ const kept = withoutSpaces(htmlText(articleHtml));
97
+ const sample = kept.slice(kept.length >> 1, (kept.length >> 1) + 60);
98
+ if (comments.some((el) => withoutSpaces(el.textContent || "").includes(sample))) return null;
99
+ for (const el of comments) el.remove();
100
+ return root;
101
+ }
102
+
103
+ // Readability chose a container above <main>, and the site's menu came with it.
104
+ function keptSiteMenu(doc, kept) {
105
+ const main = doc.querySelector(MAIN);
106
+ if (!main) return false;
107
+ const text = withoutSpaces(main.textContent || "");
108
+ if (!kept.includes(text.slice(text.length >> 1, (text.length >> 1) + MENU_SAMPLE_CHARS))) return false;
109
+ return Array.from(doc.querySelectorAll("nav, [role='navigation']")).some((nav) => {
110
+ const menu = withoutSpaces(nav.textContent || "").slice(0, MENU_SAMPLE_CHARS);
111
+ return !main.contains(nav) && menu.length === MENU_SAMPLE_CHARS && kept.includes(menu);
112
+ });
113
+ }
114
+
115
+ // A heading that is one link names another page, not a section of this one.
116
+ function isStoryCardTitle(h2) {
117
+ const text = withoutSpaces(h2.textContent || "");
118
+ return Boolean(h2.closest("a")) || Array.from(h2.querySelectorAll("a:not([href^='#'])")).some((a) => withoutSpaces(a.textContent || "") === text);
119
+ }
120
+
121
+ function lostMostSections(root, kept) {
122
+ const headings = Array.from(root.querySelectorAll("h2")).filter((h2) => !isStoryCardTitle(h2)).map((h2) => withoutSpaces(h2.textContent || "")).filter(Boolean);
123
+ return headings.length >= MIN_SECTIONS && headings.filter((heading) => !kept.includes(heading)).length * 2 > headings.length;
124
+ }
125
+
126
+ // Layout utilities, which say nothing about content: Tailwind's scroll-mt-2 and
127
+ // overflow-hidden, md:hidden.
128
+ const LAYOUT_CLASS = /^(?:\S+:)?(?:-?scroll-[mp][a-z]?-\S+|overflow(?:-[xy])?-(?:hidden|scroll)|(?<=:)hidden)$/;
129
+
130
+ // Readability scores class and id names, and removes what looks like clutter:
131
+ // Docusaurus's heading "anchorTargetHideOnScrollNavbar" matches "scroll", and so
132
+ // does the scroll-mt-2 on every code block of Docker's docs.
133
+ function withoutMisleadingNames(doc) {
134
+ // Single-paragraph FAQ wrappers can fail Readability's link-density check.
135
+ for (const el of Array.from(doc.querySelectorAll("details div")).reverse()) {
136
+ const p = el.firstElementChild;
137
+ if (p?.localName === "p" && el.children.length === 1 && el.textContent === p.textContent
138
+ && !isHiddenElement(el) && el.getAttribute("aria-hidden") !== "true") el.replaceWith(...Array.from(el.childNodes));
139
+ }
140
+ for (const heading of Array.from(doc.querySelectorAll("h1, h2, h3, h4, h5, h6"))) {
141
+ heading.removeAttribute("class");
142
+ heading.removeAttribute("id");
143
+ }
144
+ for (const el of Array.from(doc.querySelectorAll("[class]"))) {
145
+ const names = String(el.getAttribute("class")).split(/\s+/);
146
+ const kept = names.filter((name) => !LAYOUT_CLASS.test(name));
147
+ if (kept.length < names.length) el.setAttribute("class", kept.join(" "));
148
+ }
149
+ // Readability removes what's aria-hidden, and icons in table cells usually are.
150
+ for (const icon of Array.from(doc.querySelectorAll("td svg[aria-hidden], th svg[aria-hidden]"))) icon.removeAttribute("aria-hidden");
151
+ if (doc.body) removeSkippableBoxes(doc.body);
152
+ return doc;
153
+ }
154
+
17
155
  function copyDocument(doc) {
18
156
  const copy = doc.cloneNode(true);
19
157
  if (copy && copy.nodeType === 9 && copy.documentElement) return copy;
@@ -23,8 +161,8 @@ function copyDocument(doc) {
23
161
  }
24
162
 
25
163
  /**
26
- * @typedef {{ html: string, method: "readability"|"full_page"|(string & {}), fallbackReason?: string, title?: string,
27
- * byline?: string, published?: string, siteName?: string, lang?: string, excerpt?: string }} Extraction
164
+ * @typedef {{ html: string, method: "readability"|"main_content"|"full_page"|(string & {}), fallbackReason?: string, title?: string,
165
+ * byline?: string, published?: string, siteName?: string, lang?: string, excerpt?: string, commentsOmitted?: boolean }} Extraction
28
166
  */
29
167
 
30
168
  /**
@@ -36,7 +174,7 @@ function copyDocument(doc) {
36
174
  /**
37
175
  * @param {Document} doc standardized inert document (not mutated)
38
176
  * @param {{ extract?: "readable"|"full"|Extractor,
39
- * minExtractChars?: number, readability?: import("./types.js").ReadabilityOptions }} [options]
177
+ * minExtractChars?: number, minExtractShare?: number, readability?: import("./types.js").ReadabilityOptions }} [options]
40
178
  * @returns {Extraction}
41
179
  */
42
180
  export function extractContent(doc, options = {}) {
@@ -52,7 +190,7 @@ export function extractContent(doc, options = {}) {
52
190
  if (typeof mode === "function") {
53
191
  result = mode(copyDocument(doc));
54
192
  } else {
55
- const article = new Readability(copyDocument(doc), { keepClasses: true, ...options.readability }).parse();
193
+ const article = new Readability(withoutMisleadingNames(copyDocument(doc)), { keepClasses: true, ...options.readability }).parse();
56
194
  result = article && {
57
195
  html: article.content || "",
58
196
  method: "readability",
@@ -68,9 +206,41 @@ export function extractContent(doc, options = {}) {
68
206
  failure = `extractor_error: ${/** @type {any} */ (error)?.message || error}`;
69
207
  }
70
208
 
71
- if (!result?.html) return { ...full(), fallbackReason: failure || "extractor_found_nothing" };
72
- if (textLength(result.html) < minChars) {
73
- return { ...full(), fallbackReason: "extracted_text_below_minimum", title: result.title };
209
+ // Too little from the default extractor: the page's own <main>, if it marks
210
+ // one and it holds enough, beats a full page that opens with site navigation.
211
+ const tooLittle = (fallbackReason, title) => {
212
+ if (typeof mode !== "function" && doc.querySelector(MAIN)) {
213
+ const html = mainContentRoot(doc).innerHTML || "";
214
+ if (textLength(html) >= minChars) return { html, method: "main_content", fallbackReason, title };
215
+ }
216
+ return { ...full(), fallbackReason, ...(title === undefined ? {} : { title }) };
217
+ };
218
+
219
+ if (!result?.html) return tooLittle(failure || "extractor_found_nothing");
220
+ if (textLength(result.html) < minChars) return tooLittle("extracted_text_below_minimum", result.title);
221
+ if (result.method === "readability") {
222
+ const share = options.minExtractShare ?? DEFAULT_MIN_EXTRACT_SHARE;
223
+ const kept = textLength(result.html);
224
+ const isSmall = (html) => {
225
+ const available = textLength(html);
226
+ return kept < available * share && available - kept >= MIN_MISSED_CHARS;
227
+ };
228
+ const keptText = withoutSpaces(htmlText(result.html));
229
+ // Section loss counts only where it takes more of the page than a related-links block.
230
+ const misses = (el) => {
231
+ const available = el.innerHTML || "";
232
+ return isSmall(available) || (kept < textLength(available) * share * SECTION_SHARE_FACTOR && lostMostSections(el, keptText));
233
+ };
234
+ const root = mainContentRoot(doc);
235
+ const html = root.innerHTML || "";
236
+ const reason = keptSiteMenu(doc, keptText) && textLength(html) >= minChars ? "extracted_site_menu"
237
+ : isSmall(html) ? "extracted_small_share_of_page"
238
+ : misses(root) ? "extracted_few_sections_of_page" : "";
239
+ if (reason) {
240
+ const article = reason === "extracted_site_menu" ? null : articleWithoutComments(root, result.html);
241
+ if (article && !misses(article)) return { ...result, commentsOmitted: true };
242
+ return { ...result, html, method: "main_content", fallbackReason: reason };
243
+ }
74
244
  }
75
245
  return result;
76
246
  }
package/src/facts.js CHANGED
@@ -2,12 +2,13 @@
2
2
  // license, downloads), price and spec boxes, definition lists, two-column
3
3
  // tables. Readability keeps the article and drops these asides, which is right
4
4
  // for reading and wrong when the question is "which version?". Opt-in.
5
+ import { PAGE_CHROME } from "./extract.js";
5
6
  import { htmlText } from "./refine.js";
6
7
 
7
8
  const MAX_FACTS = 24;
8
9
  const MAX_LABEL_CHARS = 40;
9
10
  const MAX_VALUE_CHARS = 100;
10
- const CHROME = "nav, footer, header, form, [role='navigation'], [role='contentinfo'], [role='banner'], [role='search']";
11
+ const CHROME = `${PAGE_CHROME}, header, [id*='cookie'], [class*='cookie'], [id*='consent'], [class*='consent'], [id*='onetrust'], [class*='onetrust']`;
11
12
 
12
13
  function squash(text) {
13
14
  return String(text || "").replace(/\s+/g, " ").trim();
@@ -19,7 +20,7 @@ function isSentence(text) {
19
20
  }
20
21
 
21
22
  function shortValue(el) {
22
- if (!el || el.querySelector("h1, h2, h3, h4, h5, h6, table, pre")) return "";
23
+ if (!el || el.querySelector("h1, h2, h3, h4, h5, h6, table, pre, form, button, input, select, textarea")) return "";
23
24
  // A list of links is navigation, not a fact.
24
25
  const links = el.tagName === "A" ? [el] : el.querySelectorAll("a");
25
26
  if (links.length > 1) return "";
@@ -32,6 +33,8 @@ function shortValue(el) {
32
33
  function* candidatePairs(doc) {
33
34
  // Heading followed by a short value: <h3>Version</h3><p>1.2.3</p>.
34
35
  for (const h of doc.querySelectorAll("h2, h3, h4, h5, h6")) {
36
+ // A linked heading titles something else: another story's teaser, a card.
37
+ if (h.closest("a") || h.querySelector("a")) continue;
35
38
  yield [h.textContent, shortValue(h.nextElementSibling), h];
36
39
  }
37
40
  for (const dt of doc.querySelectorAll("dt")) {
@@ -84,7 +87,7 @@ export function collectPageFacts(doc, articleHtml) {
84
87
  return facts;
85
88
  }
86
89
 
87
- function escapeMarkdown(text) {
90
+ export function escapeMarkdown(text) {
88
91
  return text.replace(/([\\`*_[\]<>|])/g, "\\$1");
89
92
  }
90
93