webforai 1.1.6 → 1.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.
Files changed (37) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +74 -74
  3. package/dist/cjs/extract-hast/readability.js +150 -0
  4. package/dist/cjs/extract-hast/strongly.js +0 -22
  5. package/dist/cjs/extract-hast/utils.js +55 -0
  6. package/dist/cjs/html-to-mdast.js +10 -6
  7. package/dist/cjs/mdast-handlers/custom-a-handler.js +4 -4
  8. package/dist/cjs/mdast-handlers/custom-div-handler.js +35 -31
  9. package/dist/cjs/mdast-handlers/custom-img-handler.js +33 -0
  10. package/dist/cjs/mdast-handlers/custom-table-handler.js +37 -0
  11. package/dist/cjs/utils/detect-code-lang.js +73 -0
  12. package/dist/extract-hast/readability.js +127 -0
  13. package/dist/extract-hast/strongly.js +0 -22
  14. package/dist/extract-hast/utils.js +29 -0
  15. package/dist/html-to-mdast.js +10 -6
  16. package/dist/mdast-handlers/custom-a-handler.js +4 -4
  17. package/dist/mdast-handlers/custom-div-handler.js +35 -31
  18. package/dist/mdast-handlers/custom-img-handler.js +10 -0
  19. package/dist/mdast-handlers/custom-table-handler.js +14 -0
  20. package/dist/types/extract-hast/readability.d.ts +11 -0
  21. package/dist/types/extract-hast/readability.js.map +1 -0
  22. package/dist/types/extract-hast/strongly.js.map +1 -1
  23. package/dist/types/extract-hast/utils.d.ts +5 -0
  24. package/dist/types/extract-hast/utils.js.map +1 -0
  25. package/dist/types/html-to-mdast.d.ts +2 -1
  26. package/dist/types/html-to-mdast.js.map +1 -1
  27. package/dist/types/loaders/cf-puppeteer.d.ts +2 -1
  28. package/dist/types/mdast-handlers/custom-a-handler.js.map +1 -1
  29. package/dist/types/mdast-handlers/custom-div-handler.js.map +1 -1
  30. package/dist/types/mdast-handlers/custom-img-handler.d.ts +4 -0
  31. package/dist/types/mdast-handlers/custom-img-handler.js.map +1 -0
  32. package/dist/types/mdast-handlers/custom-table-handler.d.ts +4 -0
  33. package/dist/types/mdast-handlers/custom-table-handler.js.map +1 -0
  34. package/dist/types/utils/detect-code-lang.d.ts +1 -0
  35. package/dist/types/utils/detect-code-lang.js.map +1 -0
  36. package/dist/utils/detect-code-lang.js +50 -0
  37. package/package.json +8 -5
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 inaridiy
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2023 inaridiy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,74 +1,74 @@
1
- # Web for AI
2
-
3
- ![LOGO](https://github.com/inaridiy/webforai/blob/main/images/logo.webp)
4
-
5
- A library that provides a web interface for AI
6
-
7
- ## Features
8
-
9
- - Ultra-precise HTML2Markdown conversion
10
- - Ultra-precise Markdown segmentation based on AST
11
- - Ultra-precise HTML retrieval functions using headless browsers
12
- - The core functionality is edge-native (runs on Cloudflare Workers!!!)
13
-
14
- ## Demo
15
-
16
- There is a demo API for Html2Markdown deployed on CloudflareWorker. Please access the following link
17
-
18
- - [https://webforai.inaridiy.workers.dev/?url=https://www.npmjs.com/package/webforai](https://webforai.inaridiy.workers.dev/?url=https://www.npmjs.com/package/webforai)
19
- - [https://webforai.inaridiy.workers.dev/?html=%3Ch1%3EHello%20World%3C/h1%3E](https://webforai.inaridiy.workers.dev/?html=%3Ch1%3EHello%20World%3C/h1%3E)
20
-
21
- ## Quick Start
22
-
23
- Just install and execute scripts
24
-
25
- ```bash
26
- pnpm i webforai playwright
27
- ```
28
-
29
- ```js
30
- import { promises as fs } from "fs";
31
- import { htmlToMarkdown, htmlToMdast } from "webforai";
32
- import { loadHtml } from "webforai/loaders/playwright";
33
-
34
- const url = "https://www.npmjs.com/package/webforai";
35
- const html = await loadHtml(url);
36
-
37
- const markdown = htmlToMarkdown(html, { solveLinks: url });
38
-
39
- await fs.writeFile("output.md", markdown);
40
- ```
41
-
42
- other examples are in [examples](./examples/simple/src/index.ts)
43
-
44
- ## Usage
45
-
46
- ### Main Functions
47
-
48
- **`htmlToMarkdown(html: string, options?: HtmlToMarkdownOptions): string`**
49
- Convert HTML to Markdown. By default, unnecessary HTML is excluded and processed.
50
- If `solveLinks` is specified, the relative links in the Mdast will be resolved.
51
- This function just calls htmlToMdast and mdastToMarkdown in that order internally.
52
-
53
- **`htmlToMdast(html: string, options?: HtmlToMdastOptions): Mdast`**
54
- This project uses Hast and Mdast as defined by syntax-tree internally.
55
- This function converts HTML to Mdast, an intermediate representation, which is required when using `mdastSplitter`, etc.
56
-
57
- **`mdastToMarkdown(mdast: Mdast | RootContent[], options?: { solveLinks?: string }): string`**
58
- Convert Mdast to Markdown. If `solveLinks` is specified, the relative links in the Mdast will be resolved.
59
-
60
- ### Loader Functions
61
-
62
- **`loadHtml(url: string, options?: LoadHtmlOptions): Promise<string>`**
63
- Load HTML from the specified URL. This function uses Playwright internally.
64
-
65
- ## Early Users
66
-
67
- ### Voice Genius - Explanatory video generation by AI
68
-
69
- <img src="https://github.com/inaridiy/webforai/blob/main/images/voice-genius.png" width="300px">
70
-
71
- by [@moons14](https://twitter.com/moons_dev)
72
-
73
- AI can be used to automatically generate highly accurate commentary videos.
74
- Supports conversations and presentations using synthesized voice, embedding of images in videos, etc.
1
+ # Web for AI
2
+
3
+ ![LOGO](https://github.com/inaridiy/webforai/blob/main/images/logo.webp)
4
+
5
+ A library that provides a web interface for AI
6
+
7
+ ## Features
8
+
9
+ - Ultra-precise HTML2Markdown conversion
10
+ - Ultra-precise Markdown segmentation based on AST
11
+ - Ultra-precise HTML retrieval functions using headless browsers
12
+ - The core functionality is edge-native (runs on Cloudflare Workers!!!)
13
+
14
+ ## Demo
15
+
16
+ There is a demo API for Html2Markdown deployed on CloudflareWorker. Please access the following link
17
+
18
+ - [https://webforai.inaridiy.workers.dev/?url=https://www.npmjs.com/package/webforai](https://webforai.inaridiy.workers.dev/?url=https://www.npmjs.com/package/webforai)
19
+ - [https://webforai.inaridiy.workers.dev/?html=%3Ch1%3EHello%20World%3C/h1%3E](https://webforai.inaridiy.workers.dev/?html=%3Ch1%3EHello%20World%3C/h1%3E)
20
+
21
+ ## Quick Start
22
+
23
+ Just install and execute scripts
24
+
25
+ ```bash
26
+ pnpm i webforai playwright
27
+ ```
28
+
29
+ ```js
30
+ import { promises as fs } from "fs";
31
+ import { htmlToMarkdown, htmlToMdast } from "webforai";
32
+ import { loadHtml } from "webforai/loaders/playwright";
33
+
34
+ const url = "https://www.npmjs.com/package/webforai";
35
+ const html = await loadHtml(url);
36
+
37
+ const markdown = htmlToMarkdown(html, { solveLinks: url });
38
+
39
+ await fs.writeFile("output.md", markdown);
40
+ ```
41
+
42
+ other examples are in [examples](./examples/simple/src/index.ts)
43
+
44
+ ## Usage
45
+
46
+ ### Main Functions
47
+
48
+ **`htmlToMarkdown(html: string, options?: HtmlToMarkdownOptions): string`**
49
+ Convert HTML to Markdown. By default, unnecessary HTML is excluded and processed.
50
+ If `solveLinks` is specified, the relative links in the Mdast will be resolved.
51
+ This function just calls htmlToMdast and mdastToMarkdown in that order internally.
52
+
53
+ **`htmlToMdast(html: string, options?: HtmlToMdastOptions): Mdast`**
54
+ This project uses Hast and Mdast as defined by syntax-tree internally.
55
+ This function converts HTML to Mdast, an intermediate representation, which is required when using `mdastSplitter`, etc.
56
+
57
+ **`mdastToMarkdown(mdast: Mdast | RootContent[], options?: { solveLinks?: string }): string`**
58
+ Convert Mdast to Markdown. If `solveLinks` is specified, the relative links in the Mdast will be resolved.
59
+
60
+ ### Loader Functions
61
+
62
+ **`loadHtml(url: string, options?: LoadHtmlOptions): Promise<string>`**
63
+ Load HTML from the specified URL. This function uses Playwright internally.
64
+
65
+ ## Early Users
66
+
67
+ ### Voice Genius - Explanatory video generation by AI
68
+
69
+ <img src="https://github.com/inaridiy/webforai/blob/main/images/voice-genius.png" width="300px">
70
+
71
+ by [@moons14](https://twitter.com/moons_dev)
72
+
73
+ AI can be used to automatically generate highly accurate commentary videos.
74
+ Supports conversations and presentations using synthesized voice, embedding of images in videos, etc.
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var readability_exports = {};
20
+ __export(readability_exports, {
21
+ readabilityExtractHast: () => readabilityExtractHast
22
+ });
23
+ module.exports = __toCommonJS(readability_exports);
24
+ var import_hast_util_select = require("hast-util-select");
25
+ var import_hast_util_to_string = require("hast-util-to-string");
26
+ var import_unist_util_filter = require("unist-util-filter");
27
+ var import_unist_util_parents = require("unist-util-parents");
28
+ var import_utils = require("./utils");
29
+ const UNLIKELY_ROLES = ["menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog"];
30
+ const REGEXPS = {
31
+ hidden: /hidden|invisible|fallback-image/i,
32
+ byline: /byline|author|dateline|writtenby|p-author/i,
33
+ unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote|speechify-ignore/i,
34
+ okMaybeItsACandidate: /and|article|body|column|content|main|shadow|code/i
35
+ };
36
+ const BODY_SELECTORS = ["article", "#article", ".article_body", ".article-body", "#content", ".entry", "main"];
37
+ const PARAGRAPH_TAGS = ["p", "div", "section", "article", "main", "ul", "ol", "li"];
38
+ const BASE_MINIMAL_LENGTH = {
39
+ ja: 200,
40
+ en: 500
41
+ };
42
+ const tryGetLang = (node) => {
43
+ if (node.type !== "element")
44
+ return;
45
+ const element = node;
46
+ if (element.tagName !== "html")
47
+ return;
48
+ const langAttr = element.properties.lang || element.properties["xml:lang"];
49
+ if (langAttr)
50
+ return langAttr;
51
+ };
52
+ const metadataFilter = (node) => !["comment", "doctype"].includes(node.type);
53
+ const universalElementFilter = (node) => {
54
+ if (node.type !== "element")
55
+ return true;
56
+ const element = node;
57
+ if (["script", "aside"].includes(element.tagName))
58
+ return false;
59
+ if (["hidden", "aria-hidden"].some((key) => element.properties[key]))
60
+ return false;
61
+ if ((0, import_utils.classnames)(element).some((classname) => REGEXPS.hidden.test(classname)))
62
+ return false;
63
+ if (element.tagName === "dialog")
64
+ return false;
65
+ if (element.properties.role === "dialog" && element.properties["aria-modal"])
66
+ return false;
67
+ if (element.properties.rel === "author" && (0, import_utils.isStrInclude)(element.properties.itemprop, "author"))
68
+ return false;
69
+ if (REGEXPS.byline.test((0, import_utils.matchString)(element)))
70
+ return false;
71
+ if (element.properties.role && UNLIKELY_ROLES.includes(element.properties.role))
72
+ return false;
73
+ return true;
74
+ };
75
+ const unlikelyElementFilter = (node) => {
76
+ if (node.type !== "element")
77
+ return true;
78
+ const element = node;
79
+ const match = (0, import_utils.matchString)(element);
80
+ if (["body", "article", "main", "section", "a"].includes(element.tagName))
81
+ return true;
82
+ if ((0, import_utils.hasAncestors)(element, ["table", "code"], 3))
83
+ return true;
84
+ if (REGEXPS.unlikelyCandidates.test(match) && !REGEXPS.okMaybeItsACandidate.test(match))
85
+ return false;
86
+ return true;
87
+ };
88
+ const removeEmptyFilter = (node) => {
89
+ if (node.type !== "element")
90
+ return true;
91
+ const element = node;
92
+ if (!PARAGRAPH_TAGS.includes(element.tagName))
93
+ return true;
94
+ const text = (0, import_hast_util_to_string.toString)(element);
95
+ if (text.length < 10)
96
+ return false;
97
+ return true;
98
+ };
99
+ const readabilityExtractHast = (hast) => {
100
+ const lang = String((0, import_hast_util_select.select)("html", hast)?.properties.lang || tryGetLang(hast) || "en");
101
+ const body = (0, import_hast_util_select.select)("body", hast) ?? hast;
102
+ const proxiedHast = (0, import_unist_util_parents.parents)(body);
103
+ let baseFilterd = (0, import_unist_util_filter.filter)(proxiedHast, (node) => {
104
+ if (!metadataFilter(node))
105
+ return false;
106
+ if (!universalElementFilter(node))
107
+ return false;
108
+ return true;
109
+ });
110
+ if (!baseFilterd)
111
+ return { type: "root", children: [] };
112
+ const baseText = (0, import_hast_util_to_string.toString)(baseFilterd);
113
+ let minimalLength = lang in BASE_MINIMAL_LENGTH ? BASE_MINIMAL_LENGTH[lang] : 500;
114
+ if (baseText.length > minimalLength) {
115
+ const filterd = (0, import_unist_util_filter.filter)(baseFilterd, (node) => {
116
+ if (!unlikelyElementFilter(node))
117
+ return false;
118
+ return true;
119
+ });
120
+ if (filterd)
121
+ baseFilterd = filterd;
122
+ } else
123
+ minimalLength = Math.max(0, baseText.length - 200);
124
+ let bodyTree = baseFilterd;
125
+ for (const selector of BODY_SELECTORS) {
126
+ const body2 = { type: "root", children: (0, import_hast_util_select.selectAll)(selector, baseFilterd) };
127
+ const bodyText = (0, import_hast_util_to_string.toString)(body2);
128
+ if (bodyText.length < 25)
129
+ continue;
130
+ const links = (0, import_hast_util_select.selectAll)("a", body2);
131
+ const linkText = links.map((link) => (0, import_hast_util_to_string.toString)(link)).join("");
132
+ const linkDensity = linkText.length / bodyText.length;
133
+ if (linkDensity > 0.4)
134
+ continue;
135
+ if (bodyText.length > minimalLength) {
136
+ bodyTree = body2;
137
+ break;
138
+ }
139
+ }
140
+ const finalTree = (0, import_unist_util_filter.filter)(bodyTree, (node) => {
141
+ if (!removeEmptyFilter(node))
142
+ return false;
143
+ return true;
144
+ });
145
+ return finalTree;
146
+ };
147
+ // Annotate the CommonJS export names for ESM import in node:
148
+ 0 && (module.exports = {
149
+ readabilityExtractHast
150
+ });
@@ -22,26 +22,8 @@ __export(strongly_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(strongly_exports);
24
24
  var import_hast_util_select = require("hast-util-select");
25
- var import_hast_util_to_text = require("hast-util-to-text");
26
25
  var import_unist_util_filter = require("unist-util-filter");
27
- const evaluateTextComplexity = (text) => {
28
- const words = text.trim().split(/\s+/);
29
- const wordCount = words.length;
30
- const charCount = text.length;
31
- const avgWordLength = charCount / wordCount;
32
- const uniqueWords = new Set(words);
33
- const uniqueWordCount = uniqueWords.size;
34
- const complexityScore = avgWordLength * 0.4 + uniqueWordCount / wordCount * 100 * 0.6;
35
- return {
36
- wordCount,
37
- charCount,
38
- avgWordLength,
39
- uniqueWordCount,
40
- complexityScore
41
- };
42
- };
43
26
  const REMOVE_REGEX = /fallback|icon|header|nav|speechify-ignore|assist|-ad-|banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|assist|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i;
44
- const HIDDEN_REGEX = /hidden|^hid$| hid$| hid |^hid /i;
45
27
  const stronglyExtractHast = (hast) => {
46
28
  const selectors = ["article", "#article", "#content", "main", "div.container"];
47
29
  let selectedElement = hast;
@@ -61,10 +43,6 @@ const stronglyExtractHast = (hast) => {
61
43
  const elementName = `${element.tagName} ${element.properties.id} ${element.properties.className}`;
62
44
  if (REMOVE_REGEX.test(elementName))
63
45
  return false;
64
- const isHidden = HIDDEN_REGEX.test(elementName);
65
- const complexity = evaluateTextComplexity((0, import_hast_util_to_text.toText)(element));
66
- if (isHidden && complexity.complexityScore < 40)
67
- return false;
68
46
  return true;
69
47
  });
70
48
  return removedElements;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var utils_exports = {};
20
+ __export(utils_exports, {
21
+ classnames: () => classnames,
22
+ hasAncestors: () => hasAncestors,
23
+ isStrInclude: () => isStrInclude,
24
+ matchString: () => matchString
25
+ });
26
+ module.exports = __toCommonJS(utils_exports);
27
+ const matchString = (element) => `${element.tagName} ${element.properties.id} ${classnames(element).join(" ")} }`;
28
+ const classnames = (element) => {
29
+ if (Array.isArray(element.properties.className))
30
+ return element.properties.className;
31
+ return [];
32
+ };
33
+ const isStrInclude = (value, match) => {
34
+ if (typeof value === "string")
35
+ return value.includes(match);
36
+ return false;
37
+ };
38
+ const hasAncestors = (element, tagNames, depth = 3) => {
39
+ let parent = element.parent;
40
+ for (let i = 0; i < depth; i++) {
41
+ if (!parent || parent.type !== "element")
42
+ return false;
43
+ if (tagNames.includes(parent.tagName))
44
+ return true;
45
+ parent = parent.parent;
46
+ }
47
+ return false;
48
+ };
49
+ // Annotate the CommonJS export names for ESM import in node:
50
+ 0 && (module.exports = {
51
+ classnames,
52
+ hasAncestors,
53
+ isStrInclude,
54
+ matchString
55
+ });
@@ -24,13 +24,17 @@ module.exports = __toCommonJS(html_to_mdast_exports);
24
24
  var import_hast_util_from_html = require("hast-util-from-html");
25
25
  var import_hast_util_to_mdast = require("hast-util-to-mdast");
26
26
  var import_extract_hast = require("./extract-hast");
27
+ var import_readability = require("./extract-hast/readability");
27
28
  var import_custom_a_handler = require("./mdast-handlers/custom-a-handler");
28
29
  var import_custom_div_handler = require("./mdast-handlers/custom-div-handler");
30
+ var import_custom_img_handler = require("./mdast-handlers/custom-img-handler");
31
+ var import_custom_table_handler = require("./mdast-handlers/custom-table-handler");
29
32
  var import_math_handler = require("./mdast-handlers/math-handler");
30
33
  const PRESET_EXTRACT_HAST = {
31
- strongly: import_extract_hast.stronglyExtractHast
34
+ strongly: import_extract_hast.stronglyExtractHast,
35
+ readability: import_readability.readabilityExtractHast
32
36
  };
33
- const DEFAULT_EXTRACT_HAST = ["strongly"];
37
+ const DEFAULT_EXTRACT_HAST = ["readability"];
34
38
  const htmlToMdast = (html, options) => {
35
39
  const { extractHast = DEFAULT_EXTRACT_HAST } = options || {};
36
40
  const _extractHast = Array.isArray(extractHast) ? extractHast : [extractHast];
@@ -46,13 +50,13 @@ const htmlToMdast = (html, options) => {
46
50
  }, hast) || hast;
47
51
  const mdast = (0, import_hast_util_to_mdast.toMdast)(extractedHast, {
48
52
  handlers: {
49
- div: import_custom_div_handler.customDivHandler,
50
53
  math: import_math_handler.mathHandler,
54
+ div: import_custom_div_handler.customDivHandler,
51
55
  a: (0, import_custom_a_handler.customAHandler)({ asText: options?.linkAsText }),
56
+ img: (0, import_custom_img_handler.customImgHandler)({ hideImage: options?.hideImage }),
57
+ table: (0, import_custom_table_handler.customTableHandler)({ asText: options?.tableAsText }),
52
58
  br: () => {
53
- },
54
- ...options?.hideImage ? { img: () => {
55
- } } : {}
59
+ }
56
60
  }
57
61
  });
58
62
  return mdast;
@@ -22,12 +22,12 @@ __export(custom_a_handler_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(custom_a_handler_exports);
24
24
  var import_hast_util_to_mdast = require("hast-util-to-mdast");
25
+ var import_hast_util_to_string = require("hast-util-to-string");
25
26
  const customAHandler = (options) => (state, node) => {
26
27
  if (options?.asText) {
27
- const link2 = import_hast_util_to_mdast.defaultHandlers.a(state, node);
28
- if (link2.children?.[0]?.type === "text")
29
- return link2.children[0];
30
- return void 0;
28
+ const link2 = { type: "text", value: (0, import_hast_util_to_string.toString)(node) };
29
+ state.patch(node, link2);
30
+ return link2;
31
31
  }
32
32
  const link = import_hast_util_to_mdast.defaultHandlers.a(state, node);
33
33
  if (link.children.length > 0)
@@ -21,42 +21,46 @@ __export(custom_div_handler_exports, {
21
21
  customDivHandler: () => customDivHandler
22
22
  });
23
23
  module.exports = __toCommonJS(custom_div_handler_exports);
24
+ var import_hast_util_select = require("hast-util-select");
24
25
  var import_hast_util_to_mdast = require("hast-util-to-mdast");
26
+ var import_hast_util_to_string = require("hast-util-to-string");
25
27
  var import_hast_util_to_text = require("hast-util-to-text");
26
28
  var import_trim_trailing_lines = require("trim-trailing-lines");
29
+ var import_detect_code_lang = require("../utils/detect-code-lang");
30
+ const CODE_BLOCK_REGEX = /highlight-source|language-|codegroup|codeblock|code-block/i;
31
+ const CODE_FILENAME_SELECTORS = "[class*='fileName'],[class*='fileName'],[class*='title'],[class*='Title']";
32
+ const LANGUAGE_MATCH_REGEX = /language-(\w+)|highlight-source-(\w+)/;
33
+ const findRecursive = (array, condition, maxDepth = 3) => {
34
+ if (maxDepth <= 0)
35
+ return null;
36
+ for (const value of array) {
37
+ const result = condition(value);
38
+ if (Array.isArray(result))
39
+ return findRecursive(result, condition, maxDepth - 1);
40
+ if (result)
41
+ return value;
42
+ }
43
+ return null;
44
+ };
27
45
  const customDivHandler = (state, node) => {
28
46
  const classNames = Array.isArray(node.properties.className) ? node.properties.className : [];
29
- let highlightLanguage;
30
- for (const className of classNames) {
31
- if (String(className) === "highlight-text-html-basic") {
32
- highlightLanguage = "html";
33
- break;
34
- }
35
- if (String(className).includes("highlight-source-")) {
36
- highlightLanguage = String(className).slice("highlight-source-".length);
37
- break;
38
- }
39
- if (String(className).includes("language-")) {
40
- highlightLanguage = String(className).slice("language-".length);
41
- break;
42
- }
43
- if (String(className).includes("code-block_wrapper")) {
44
- const text = (0, import_hast_util_to_text.toText)(node);
45
- if (!text.includes("."))
46
- break;
47
- const lang = (0, import_hast_util_to_text.toText)(node).split("\n")[0].split(".").slice(-1)[0];
48
- highlightLanguage = lang;
49
- break;
50
- }
51
- }
52
- if (highlightLanguage !== void 0) {
53
- const code = node.children.find((child) => child.type === "element" && child.tagName === "pre") || node;
54
- const result = {
55
- type: "code",
56
- lang: highlightLanguage,
57
- meta: null,
58
- value: (0, import_trim_trailing_lines.trimTrailingLines)((0, import_hast_util_to_text.toText)(code)).trim()
59
- };
47
+ const codeBlock = findRecursive(node.children, (child) => {
48
+ if (child.type !== "element")
49
+ return false;
50
+ if (child.tagName === "pre")
51
+ return true;
52
+ return child.children.filter((child2) => child2.type === "element");
53
+ });
54
+ if (codeBlock && classNames.some((className) => CODE_BLOCK_REGEX.test(className))) {
55
+ const codeValue = (0, import_trim_trailing_lines.trimTrailingLines)((0, import_hast_util_to_text.toText)(codeBlock)).trim();
56
+ const filenameElement = (0, import_hast_util_select.select)(CODE_FILENAME_SELECTORS, node);
57
+ const fileLang = filenameElement ? (0, import_hast_util_to_string.toString)(filenameElement).match(/\.(\w+)$/)?.[1] : null;
58
+ const classLang = classNames.map((className) => {
59
+ const match = className.match(LANGUAGE_MATCH_REGEX);
60
+ return match?.[1] || match?.[2];
61
+ }).find((className) => className);
62
+ const lang = fileLang || classLang || (0, import_detect_code_lang.detectLanguage)(codeValue) || null;
63
+ const result = { type: "code", lang, meta: null, value: codeValue };
60
64
  state.patch(node, result);
61
65
  return result;
62
66
  }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var custom_img_handler_exports = {};
20
+ __export(custom_img_handler_exports, {
21
+ customImgHandler: () => customImgHandler
22
+ });
23
+ module.exports = __toCommonJS(custom_img_handler_exports);
24
+ var import_hast_util_to_mdast = require("hast-util-to-mdast");
25
+ const customImgHandler = (options) => (state, node) => {
26
+ if (options?.hideImage)
27
+ return void 0;
28
+ return import_hast_util_to_mdast.defaultHandlers.image(state, node);
29
+ };
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ customImgHandler
33
+ });
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var custom_table_handler_exports = {};
20
+ __export(custom_table_handler_exports, {
21
+ customTableHandler: () => customTableHandler
22
+ });
23
+ module.exports = __toCommonJS(custom_table_handler_exports);
24
+ var import_hast_util_to_mdast = require("hast-util-to-mdast");
25
+ var import_hast_util_to_text = require("hast-util-to-text");
26
+ const customTableHandler = (options) => (state, node) => {
27
+ if (options?.asText) {
28
+ const paragraph = { type: "paragraph", children: [{ type: "text", value: (0, import_hast_util_to_text.toText)(node) }] };
29
+ state.patch(node, paragraph);
30
+ return paragraph;
31
+ }
32
+ return import_hast_util_to_mdast.defaultHandlers.table(state, node);
33
+ };
34
+ // Annotate the CommonJS export names for ESM import in node:
35
+ 0 && (module.exports = {
36
+ customTableHandler
37
+ });