@arabold/docs-mcp-server 3.3.0 → 3.4.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/dist/{HtmlDefuddleMiddleware-BNIv3ibo.js → HtmlDefuddleMiddleware-DxjoyIFY.js} +4 -5
- package/dist/{HtmlDefuddleMiddleware-BNIv3ibo.js.map → HtmlDefuddleMiddleware-DxjoyIFY.js.map} +1 -1
- package/dist/assets/index-DR-3PGgZ.js +70 -0
- package/dist/assets/index-DR-3PGgZ.js.map +1 -0
- package/dist/{env-DONvEfR5.js → env-DAfCMXx2.js} +2 -3
- package/dist/{env-DONvEfR5.js.map → env-DAfCMXx2.js.map} +1 -1
- package/dist/index.html +1 -1
- package/dist/index.js +4 -5
- package/dist/{logger-BBxstTD7.js → logger-DtB7mX3u.js} +2 -3
- package/dist/{logger-BBxstTD7.js.map → logger-DtB7mX3u.js.map} +1 -1
- package/dist/{main-BoABX2b0.js → main-BTCYUUTU.js} +617 -2172
- package/dist/main-BTCYUUTU.js.map +1 -0
- package/dist/{string-B3iUfzt2.js → string-n2Z12tl6.js} +2 -3
- package/dist/{string-B3iUfzt2.js.map → string-n2Z12tl6.js.map} +1 -1
- package/dist/utils-1UoDzw8s.js +1 -0
- package/dist/utils-7a9aMv8E.js +1866 -0
- package/dist/utils-7a9aMv8E.js.map +1 -0
- package/package.json +58 -61
- package/public/assets/index-DR-3PGgZ.js +70 -0
- package/public/assets/index-DR-3PGgZ.js.map +1 -0
- package/public/index.html +1 -1
- package/dist/assets/index-JESalFJu.js +0 -70
- package/dist/assets/index-JESalFJu.js.map +0 -1
- package/dist/main-BoABX2b0.js.map +0 -1
- package/dist/utils-CjF4IsxT.js +0 -2
- package/dist/utils-DXo1A54z.js +0 -675
- package/dist/utils-DXo1A54z.js.map +0 -1
- package/public/assets/index-JESalFJu.js +0 -70
- package/public/assets/index-JESalFJu.js.map +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { r as logger } from "./logger-
|
|
2
|
-
import { t as escapeHtml } from "./string-
|
|
1
|
+
import { r as logger } from "./logger-DtB7mX3u.js";
|
|
2
|
+
import { t as escapeHtml } from "./string-n2Z12tl6.js";
|
|
3
3
|
import * as cheerio from "cheerio";
|
|
4
4
|
import { Defuddle } from "defuddle/node";
|
|
5
5
|
import { parseHTML } from "linkedom";
|
|
6
|
-
|
|
6
|
+
// src/scraper/middleware/HtmlDefuddleMiddleware.ts
|
|
7
7
|
var DEFAULT_MIN_RETENTION = .01;
|
|
8
8
|
/**
|
|
9
9
|
* Middleware that runs Defuddle as a drop-in replacement for
|
|
@@ -140,7 +140,6 @@ function detectLanguageFromClass(className) {
|
|
|
140
140
|
if (lang === "text" || lang === "highlighted" || lang === "wrap") return "";
|
|
141
141
|
return lang;
|
|
142
142
|
}
|
|
143
|
-
//#endregion
|
|
144
143
|
export { HtmlDefuddleMiddleware };
|
|
145
144
|
|
|
146
|
-
//# sourceMappingURL=HtmlDefuddleMiddleware-
|
|
145
|
+
//# sourceMappingURL=HtmlDefuddleMiddleware-DxjoyIFY.js.map
|
package/dist/{HtmlDefuddleMiddleware-BNIv3ibo.js.map → HtmlDefuddleMiddleware-DxjoyIFY.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HtmlDefuddleMiddleware-BNIv3ibo.js","names":[],"sources":["../src/scraper/middleware/HtmlDefuddleMiddleware.ts"],"sourcesContent":["import * as cheerio from \"cheerio\";\nimport { Defuddle } from \"defuddle/node\";\nimport { parseHTML } from \"linkedom\";\nimport { logger } from \"../../utils/logger\";\nimport { escapeHtml } from \"../../utils/string\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Options for HtmlDefuddleMiddleware.\n */\nexport interface HtmlDefuddleOptions {\n /**\n * If Defuddle's extracted content drops below this fraction of the original\n * *visible* text length (script/style/noscript excluded), fall back to the\n * pre-extraction DOM. Set very low by default — Defuddle is intentionally\n * aggressive, and the more useful safety net is the empty-output check\n * below. The ratio is here mainly to catch catastrophic mis-extraction\n * (Defuddle latches onto a tiny element on a content-rich page).\n */\n minTextRetentionRatio?: number;\n}\n\nconst DEFAULT_MIN_RETENTION = 0.01;\n\n/**\n * Middleware that runs Defuddle as a drop-in replacement for\n * {@link HtmlSanitizerMiddleware}. It extracts the main article content,\n * removing navigation, footers, ads, and other boilerplate using Defuddle's\n * heuristics rather than a hand-maintained selector list.\n *\n * Pipeline contract:\n * - Reads HTML from `context.dom` (populated by HtmlCheerioParserMiddleware).\n * - Runs Defuddle via linkedom and replaces `context.dom` with a fresh Cheerio\n * DOM containing only the cleaned content (wrapped in `<html><body>…`).\n * - Honours `context.options.excludeSelectors` by stripping them from the\n * *source* DOM before Defuddle runs. Defuddle's standardise step unwraps\n * class/id hooks, so post-extraction selector matching is unreliable;\n * filtering on the source DOM matches the Cheerio sanitiser's behaviour\n * and the user's mental model.\n * - Updates `context.title` if Defuddle found a non-empty title and the\n * previous extractor left it empty.\n * - Falls back to the original DOM if Defuddle returns empty output or removes\n * substantially all text (see {@link minTextRetentionRatio}).\n */\nexport class HtmlDefuddleMiddleware implements ContentProcessorMiddleware {\n private readonly minTextRetentionRatio: number;\n\n constructor(options: HtmlDefuddleOptions = {}) {\n this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;\n }\n\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n const originalHtml = $.html();\n // Measure *visible* text, excluding script/style content. SPA pages\n // (Next.js, Nuxt, etc.) embed huge hydration payloads inside <script>\n // tags whose textContent inflates the body text length by orders of\n // magnitude, which would otherwise trip the retention-ratio fallback.\n const $bodyClone = cheerio.load(`<body>${$(\"body\").html() ?? \"\"}</body>`);\n $bodyClone(\"script, style, noscript, template\").remove();\n const textLengthBefore = $bodyClone(\"body\").text().trim().length;\n\n const { document } = parseHTML(originalHtml);\n\n // Apply user-supplied excludeSelectors *before* Defuddle. Defuddle\n // standardises markup (e.g. unwrapping divs into <p>), which strips the\n // class/id hooks the user supplied — so post-extraction removal often\n // misses. Filtering on the source DOM matches the user's mental model\n // (same as the Cheerio sanitiser path).\n this.applyExcludePreDefuddle(document, context);\n\n // Defuddle's `standardize` step unwraps the language-bearing ancestor\n // divs that highlighters like Pygments/Sphinx and GitHub use (e.g.\n // `<div class=\"highlight-python3\"><pre>...</pre></div>`). Push the\n // detected language onto the inner `<code>` as `class=\"language-X\"` so\n // Defuddle preserves it and our Turndown rule can recover the fenced\n // code-block language.\n this.propagateLanguageHints(document);\n\n const result = await Defuddle(document, context.source, {\n // We do markdown conversion downstream (HtmlToMarkdownMiddleware), so\n // ask Defuddle for cleaned HTML, not markdown.\n markdown: false,\n });\n\n const cleanedContent = typeof result?.content === \"string\" ? result.content : \"\";\n\n // Build the cleaned Cheerio DOM *first*, then measure retention on the\n // post-sanitisation text. Doing the regex-strip-then-measure dance in\n // the other order let `<script>` *contents* (e.g. Next.js `__next_f`\n // hydration payloads) inflate the \"kept\" character count so the ratio\n // check passed, after which removing the script tags emptied the page.\n //\n // Note on H1 handling: Defuddle's standardize step deliberately drops\n // the first H1/H2 when it matches the extracted title (and converts\n // remaining H1s to H2s). The dropped headline text is preserved on\n // `context.title`, which the indexer attaches to every chunk as\n // metadata — so it's still searchable, just not duplicated inside the\n // chunk body. Defuddle exposes no granular flag to opt out of this\n // single behaviour (only the coarse `standardize: false` which would\n // also disable code-block / footnote standardisation).\n const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || \"\")}</title></head><body>${cleanedContent}</body></html>`;\n const cleaned$ = cheerio.load(wrappedHtml);\n\n // Strip dangerous / non-content tags. Defuddle can leak these (Next.js\n // hydration payloads being the worst offender) and they're never useful\n // in indexed markdown.\n cleaned$(\"script, style, noscript, iframe, svg, link, meta\").remove();\n\n // Measure retention on the post-strip text so the ratio reflects what\n // actually survives into the chunked output.\n const cleanedText = cleaned$(\"body\").text().trim();\n const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;\n\n if (!cleanedText || ratio < this.minTextRetentionRatio) {\n logger.warn(\n `⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`,\n );\n // Strip script/style/iframe defensively even on fallback — without\n // these the markdown converter renders hydration payloads (e.g.\n // Next.js __next_f) as multi-hundred-KB blobs.\n $(\"script, style, noscript, iframe, svg, link, meta\").remove();\n await next();\n return;\n }\n\n context.dom = cleaned$;\n if (!context.title && result.title) {\n context.title = result.title;\n }\n\n logger.debug(\n `Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`Defuddle extraction failed: ${String(error)}`),\n );\n }\n\n await next();\n }\n\n /**\n * Normalise each `<pre>` so Defuddle preserves its language hint.\n *\n * Defuddle's standardise step strips `class=\"language-X\"` unless `X` is one\n * of its allow-listed canonical language names (so `language-python3`,\n * `language-py`, etc. get dropped). It also unwraps highlighter ancestors\n * like `<div class=\"highlight-python3\">`, losing that context entirely.\n *\n * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and\n * promotes them to `class=\"language-X\"` on the inner `<code>`. So this\n * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby\n * ancestor classes and writes it back as `data-language` on `<pre>`. Our\n * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a\n * fenced code block with the correct language.\n */\n private propagateLanguageHints(document: Document): void {\n const pres = document.querySelectorAll(\"pre\");\n for (const pre of Array.from(pres)) {\n const existingCode = pre.querySelector(\"code\");\n\n // Already set explicitly — leave alone.\n if (pre.getAttribute(\"data-language\")) continue;\n\n let lang =\n detectLanguageFromClass(pre.getAttribute(\"class\")) ||\n detectLanguageFromClass(existingCode?.getAttribute(\"class\") ?? null);\n\n if (!lang) {\n let ancestor: Element | null = pre.parentElement;\n let depth = 0;\n while (ancestor && depth < 5) {\n const found = detectLanguageFromClass(ancestor.getAttribute(\"class\"));\n if (found) {\n lang = found;\n break;\n }\n ancestor = ancestor.parentElement;\n depth++;\n }\n }\n\n if (!lang) continue;\n\n pre.setAttribute(\"data-language\", lang);\n\n // Unwrap any highlighter wrapper divs around this <pre>. Defuddle's\n // standardise step rewrites the `<pre>` (stripping its attributes,\n // including our data-language) when it sees this wrapped structure.\n // Replacing the wrapper with the bare <pre> sidesteps that path.\n let wrapper: Element | null = pre.parentElement;\n let depth = 0;\n while (wrapper && depth < 5) {\n const cls = wrapper.getAttribute(\"class\") ?? \"\";\n const isHighlightWrapper =\n /(?:^|\\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\\s|$)/.test(\n cls,\n );\n if (\n isHighlightWrapper &&\n wrapper.children.length === 1 &&\n wrapper.parentElement\n ) {\n wrapper.parentElement.replaceChild(pre, wrapper);\n wrapper = pre.parentElement;\n } else {\n break;\n }\n depth++;\n }\n }\n }\n\n private applyExcludePreDefuddle(document: Document, context: MiddlewareContext): void {\n const selectors = context.options.excludeSelectors ?? [];\n if (selectors.length === 0) return;\n\n for (const selector of selectors) {\n try {\n const matches = document.querySelectorAll(selector);\n for (const node of Array.from(matches)) {\n const tag = node.tagName?.toLowerCase();\n if (tag === \"html\" || tag === \"body\") continue;\n node.remove();\n }\n } catch (selectorError) {\n logger.warn(\n `⚠️ Invalid excludeSelector \"${selector}\" before Defuddle: ${selectorError}`,\n );\n context.errors.push(\n new Error(`Invalid selector \"${selector}\": ${selectorError}`),\n );\n }\n }\n }\n}\n\nconst LANGUAGE_CLASS_RE =\n /(?:^|\\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;\n\nfunction detectLanguageFromClass(className: string | null | undefined): string {\n if (!className) return \"\";\n const match = LANGUAGE_CLASS_RE.exec(className);\n if (!match) return \"\";\n const lang = match[1].toLowerCase();\n // Skip generic non-language tokens that show up under `highlight-` prefix.\n if (lang === \"text\" || lang === \"highlighted\" || lang === \"wrap\") return \"\";\n return lang;\n}\n"],"mappings":";;;;;;AAsBA,IAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;AAsB9B,IAAa,yBAAb,MAA0E;CACxE;CAEA,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,wBAAwB,QAAQ,yBAAyB;CAChE;CAEA,MAAM,QAAQ,SAA4B,MAA0C;EAClF,MAAM,IAAI,QAAQ;EAClB,IAAI,CAAC,GAAG;GACN,OAAO,KACL,eAAe,KAAK,YAAY,KAAK,+EACvC;GACA,MAAM,KAAK;GACX;EACF;EAEA,IAAI;GACF,MAAM,eAAe,EAAE,KAAK;GAK5B,MAAM,aAAa,QAAQ,KAAK,SAAS,EAAE,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,QAAQ;GACxE,WAAW,mCAAmC,CAAC,CAAC,OAAO;GACvD,MAAM,mBAAmB,WAAW,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAE1D,MAAM,EAAE,aAAa,UAAU,YAAY;GAO3C,KAAK,wBAAwB,UAAU,OAAO;GAQ9C,KAAK,uBAAuB,QAAQ;GAEpC,MAAM,SAAS,MAAM,SAAS,UAAU,QAAQ,QAAQ,EAGtD,UAAU,MACZ,CAAC;GAED,MAAM,iBAAiB,OAAO,QAAQ,YAAY,WAAW,OAAO,UAAU;GAgB9E,MAAM,cAAc,qCAAqC,WAAW,OAAO,SAAS,QAAQ,SAAS,EAAE,EAAE,uBAAuB,eAAe;GAC/I,MAAM,WAAW,QAAQ,KAAK,WAAW;GAKzC,SAAS,kDAAkD,CAAC,CAAC,OAAO;GAIpE,MAAM,cAAc,SAAS,MA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GACF;GAEA,IAAI,CAAC,MAAM;GAEX,IAAI,aAAa,iBAAiB,IAAI;GAMtC,IAAI,UAA0B,IAAI;GAClC,IAAI,QAAQ;GACZ,OAAO,WAAW,QAAQ,GAAG;IAC3B,MAAM,MAAM,QAAQ,aAAa,OAAO,KAAK;IAK7C,IAHE,2FAA2F,KACzF,GAGF,KACA,QAAQ,SAAS,WAAW,KAC5B,QAAQ,eACR;KACA,QAAQ,cAAc,aAAa,KAAK,OAAO;KAC/C,UAAU,IAAI;IAChB,OACE;IAEF;GACF;EACF;CACF;CAEA,wBAAgC,UAAoB,SAAkC;EACpF,MAAM,YAAY,QAAQ,QAAQ,oBAAoB,CAAC;EACvD,IAAI,UAAU,WAAW,GAAG;EAE5B,KAAK,MAAM,YAAY,WACrB,IAAI;GACF,MAAM,UAAU,SAAS,iBAAiB,QAAQ;GAClD,KAAK,MAAM,QAAQ,MAAM,KAAK,OAAO,GAAG;IACtC,MAAM,MAAM,KAAK,SAAS,YAAY;IACtC,IAAI,QAAQ,UAAU,QAAQ,QAAQ;IACtC,KAAK,OAAO;GACd;EACF,SAAS,eAAe;GACtB,OAAO,KACL,gCAAgC,SAAS,qBAAqB,eAChE;GACA,QAAQ,OAAO,qBACb,IAAI,MAAM,qBAAqB,SAAS,KAAK,eAAe,CAC9D;EACF;CAEJ;AACF;AAEA,IAAM,oBACJ;AAEF,SAAS,wBAAwB,WAA8C;CAC7E,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,QAAQ,kBAAkB,KAAK,SAAS;CAC9C,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,OAAO,MAAM,EAAE,CAAC,YAAY;CAElC,IAAI,SAAS,UAAU,SAAS,iBAAiB,SAAS,QAAQ,OAAO;CACzE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"HtmlDefuddleMiddleware-DxjoyIFY.js","names":[],"sources":["../src/scraper/middleware/HtmlDefuddleMiddleware.ts"],"sourcesContent":["import * as cheerio from \"cheerio\";\nimport { Defuddle } from \"defuddle/node\";\nimport { parseHTML } from \"linkedom\";\nimport { logger } from \"../../utils/logger\";\nimport { escapeHtml } from \"../../utils/string\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Options for HtmlDefuddleMiddleware.\n */\nexport interface HtmlDefuddleOptions {\n /**\n * If Defuddle's extracted content drops below this fraction of the original\n * *visible* text length (script/style/noscript excluded), fall back to the\n * pre-extraction DOM. Set very low by default — Defuddle is intentionally\n * aggressive, and the more useful safety net is the empty-output check\n * below. The ratio is here mainly to catch catastrophic mis-extraction\n * (Defuddle latches onto a tiny element on a content-rich page).\n */\n minTextRetentionRatio?: number;\n}\n\nconst DEFAULT_MIN_RETENTION = 0.01;\n\n/**\n * Middleware that runs Defuddle as a drop-in replacement for\n * {@link HtmlSanitizerMiddleware}. It extracts the main article content,\n * removing navigation, footers, ads, and other boilerplate using Defuddle's\n * heuristics rather than a hand-maintained selector list.\n *\n * Pipeline contract:\n * - Reads HTML from `context.dom` (populated by HtmlCheerioParserMiddleware).\n * - Runs Defuddle via linkedom and replaces `context.dom` with a fresh Cheerio\n * DOM containing only the cleaned content (wrapped in `<html><body>…`).\n * - Honours `context.options.excludeSelectors` by stripping them from the\n * *source* DOM before Defuddle runs. Defuddle's standardise step unwraps\n * class/id hooks, so post-extraction selector matching is unreliable;\n * filtering on the source DOM matches the Cheerio sanitiser's behaviour\n * and the user's mental model.\n * - Updates `context.title` if Defuddle found a non-empty title and the\n * previous extractor left it empty.\n * - Falls back to the original DOM if Defuddle returns empty output or removes\n * substantially all text (see {@link minTextRetentionRatio}).\n */\nexport class HtmlDefuddleMiddleware implements ContentProcessorMiddleware {\n private readonly minTextRetentionRatio: number;\n\n constructor(options: HtmlDefuddleOptions = {}) {\n this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;\n }\n\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n const originalHtml = $.html();\n // Measure *visible* text, excluding script/style content. SPA pages\n // (Next.js, Nuxt, etc.) embed huge hydration payloads inside <script>\n // tags whose textContent inflates the body text length by orders of\n // magnitude, which would otherwise trip the retention-ratio fallback.\n const $bodyClone = cheerio.load(`<body>${$(\"body\").html() ?? \"\"}</body>`);\n $bodyClone(\"script, style, noscript, template\").remove();\n const textLengthBefore = $bodyClone(\"body\").text().trim().length;\n\n const { document } = parseHTML(originalHtml);\n\n // Apply user-supplied excludeSelectors *before* Defuddle. Defuddle\n // standardises markup (e.g. unwrapping divs into <p>), which strips the\n // class/id hooks the user supplied — so post-extraction removal often\n // misses. Filtering on the source DOM matches the user's mental model\n // (same as the Cheerio sanitiser path).\n this.applyExcludePreDefuddle(document, context);\n\n // Defuddle's `standardize` step unwraps the language-bearing ancestor\n // divs that highlighters like Pygments/Sphinx and GitHub use (e.g.\n // `<div class=\"highlight-python3\"><pre>...</pre></div>`). Push the\n // detected language onto the inner `<code>` as `class=\"language-X\"` so\n // Defuddle preserves it and our Turndown rule can recover the fenced\n // code-block language.\n this.propagateLanguageHints(document);\n\n const result = await Defuddle(document, context.source, {\n // We do markdown conversion downstream (HtmlToMarkdownMiddleware), so\n // ask Defuddle for cleaned HTML, not markdown.\n markdown: false,\n });\n\n const cleanedContent = typeof result?.content === \"string\" ? result.content : \"\";\n\n // Build the cleaned Cheerio DOM *first*, then measure retention on the\n // post-sanitisation text. Doing the regex-strip-then-measure dance in\n // the other order let `<script>` *contents* (e.g. Next.js `__next_f`\n // hydration payloads) inflate the \"kept\" character count so the ratio\n // check passed, after which removing the script tags emptied the page.\n //\n // Note on H1 handling: Defuddle's standardize step deliberately drops\n // the first H1/H2 when it matches the extracted title (and converts\n // remaining H1s to H2s). The dropped headline text is preserved on\n // `context.title`, which the indexer attaches to every chunk as\n // metadata — so it's still searchable, just not duplicated inside the\n // chunk body. Defuddle exposes no granular flag to opt out of this\n // single behaviour (only the coarse `standardize: false` which would\n // also disable code-block / footnote standardisation).\n const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || \"\")}</title></head><body>${cleanedContent}</body></html>`;\n const cleaned$ = cheerio.load(wrappedHtml);\n\n // Strip dangerous / non-content tags. Defuddle can leak these (Next.js\n // hydration payloads being the worst offender) and they're never useful\n // in indexed markdown.\n cleaned$(\"script, style, noscript, iframe, svg, link, meta\").remove();\n\n // Measure retention on the post-strip text so the ratio reflects what\n // actually survives into the chunked output.\n const cleanedText = cleaned$(\"body\").text().trim();\n const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;\n\n if (!cleanedText || ratio < this.minTextRetentionRatio) {\n logger.warn(\n `⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`,\n );\n // Strip script/style/iframe defensively even on fallback — without\n // these the markdown converter renders hydration payloads (e.g.\n // Next.js __next_f) as multi-hundred-KB blobs.\n $(\"script, style, noscript, iframe, svg, link, meta\").remove();\n await next();\n return;\n }\n\n context.dom = cleaned$;\n if (!context.title && result.title) {\n context.title = result.title;\n }\n\n logger.debug(\n `Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`Defuddle extraction failed: ${String(error)}`),\n );\n }\n\n await next();\n }\n\n /**\n * Normalise each `<pre>` so Defuddle preserves its language hint.\n *\n * Defuddle's standardise step strips `class=\"language-X\"` unless `X` is one\n * of its allow-listed canonical language names (so `language-python3`,\n * `language-py`, etc. get dropped). It also unwraps highlighter ancestors\n * like `<div class=\"highlight-python3\">`, losing that context entirely.\n *\n * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and\n * promotes them to `class=\"language-X\"` on the inner `<code>`. So this\n * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby\n * ancestor classes and writes it back as `data-language` on `<pre>`. Our\n * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a\n * fenced code block with the correct language.\n */\n private propagateLanguageHints(document: Document): void {\n const pres = document.querySelectorAll(\"pre\");\n for (const pre of Array.from(pres)) {\n const existingCode = pre.querySelector(\"code\");\n\n // Already set explicitly — leave alone.\n if (pre.getAttribute(\"data-language\")) continue;\n\n let lang =\n detectLanguageFromClass(pre.getAttribute(\"class\")) ||\n detectLanguageFromClass(existingCode?.getAttribute(\"class\") ?? null);\n\n if (!lang) {\n let ancestor: Element | null = pre.parentElement;\n let depth = 0;\n while (ancestor && depth < 5) {\n const found = detectLanguageFromClass(ancestor.getAttribute(\"class\"));\n if (found) {\n lang = found;\n break;\n }\n ancestor = ancestor.parentElement;\n depth++;\n }\n }\n\n if (!lang) continue;\n\n pre.setAttribute(\"data-language\", lang);\n\n // Unwrap any highlighter wrapper divs around this <pre>. Defuddle's\n // standardise step rewrites the `<pre>` (stripping its attributes,\n // including our data-language) when it sees this wrapped structure.\n // Replacing the wrapper with the bare <pre> sidesteps that path.\n let wrapper: Element | null = pre.parentElement;\n let depth = 0;\n while (wrapper && depth < 5) {\n const cls = wrapper.getAttribute(\"class\") ?? \"\";\n const isHighlightWrapper =\n /(?:^|\\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\\s|$)/.test(\n cls,\n );\n if (\n isHighlightWrapper &&\n wrapper.children.length === 1 &&\n wrapper.parentElement\n ) {\n wrapper.parentElement.replaceChild(pre, wrapper);\n wrapper = pre.parentElement;\n } else {\n break;\n }\n depth++;\n }\n }\n }\n\n private applyExcludePreDefuddle(document: Document, context: MiddlewareContext): void {\n const selectors = context.options.excludeSelectors ?? [];\n if (selectors.length === 0) return;\n\n for (const selector of selectors) {\n try {\n const matches = document.querySelectorAll(selector);\n for (const node of Array.from(matches)) {\n const tag = node.tagName?.toLowerCase();\n if (tag === \"html\" || tag === \"body\") continue;\n node.remove();\n }\n } catch (selectorError) {\n logger.warn(\n `⚠️ Invalid excludeSelector \"${selector}\" before Defuddle: ${selectorError}`,\n );\n context.errors.push(\n new Error(`Invalid selector \"${selector}\": ${selectorError}`),\n );\n }\n }\n }\n}\n\nconst LANGUAGE_CLASS_RE =\n /(?:^|\\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;\n\nfunction detectLanguageFromClass(className: string | null | undefined): string {\n if (!className) return \"\";\n const match = LANGUAGE_CLASS_RE.exec(className);\n if (!match) return \"\";\n const lang = match[1].toLowerCase();\n // Skip generic non-language tokens that show up under `highlight-` prefix.\n if (lang === \"text\" || lang === \"highlighted\" || lang === \"wrap\") return \"\";\n return lang;\n}\n"],"mappings":";;;;;;AAsBA,IAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;AAsB9B,IAAa,yBAAb,MAA0E;CACxE;CAEA,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,wBAAwB,QAAQ,yBAAyB;CAChE;CAEA,MAAM,QAAQ,SAA4B,MAA0C;EAClF,MAAM,IAAI,QAAQ;EAClB,IAAI,CAAC,GAAG;GACN,OAAO,KACL,eAAe,KAAK,YAAY,KAAK,+EACvC;GACA,MAAM,KAAK;GACX;EACF;EAEA,IAAI;GACF,MAAM,eAAe,EAAE,KAAK;GAK5B,MAAM,aAAa,QAAQ,KAAK,SAAS,EAAE,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,QAAQ;GACxE,WAAW,mCAAmC,CAAC,CAAC,OAAO;GACvD,MAAM,mBAAmB,WAAW,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAE1D,MAAM,EAAE,aAAa,UAAU,YAAY;GAO3C,KAAK,wBAAwB,UAAU,OAAO;GAQ9C,KAAK,uBAAuB,QAAQ;GAEpC,MAAM,SAA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