@zeldrisho/pi-web-fetch 0.18.0 → 0.18.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.18.1] - 2026-11-23
11
+
12
+ ### Fixed
13
+
14
+ - Read a page's authored no-JavaScript fallback when script-only markup leaves the extraction empty or sparse, instead of returning stray interface text.
15
+ - Preserve conditional revalidation for stale pages cached under the current Markdown-preference policy while migrating older entries once.
16
+ - Discover documentation indexes from deeper URL ancestors and filter Android BOM pages to the requested version.
17
+ - Preserve HTML representation preferences across redirects, keep Android BOM selections isolated in the cache, and avoid treating readable fallback content as a markup shell.
18
+
10
19
  ## [0.18.0] - 2026-11-20
11
20
 
12
21
  ### Added
@@ -383,7 +392,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
383
392
 
384
393
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
385
394
 
386
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...HEAD
395
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.1...HEAD
396
+ [0.18.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.18.0...pi-web-fetch-v0.18.1
387
397
  [0.18.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.1...pi-web-fetch-v0.18.0
388
398
  [0.17.1]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.17.0...pi-web-fetch-v0.17.1
389
399
  [0.17.0]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...pi-web-fetch-v0.17.0
package/README.md CHANGED
@@ -31,7 +31,7 @@ For example, a URL such as `https://github.com/zeldrisho/pi-packages/blob/main/p
31
31
 
32
32
  ### Page alternatives and bot challenges
33
33
 
34
- The tool prefers Markdown when sites offer it, including advertised alternatives and documented Next.js and Vercel documentation endpoints, and can discover `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
34
+ The tool prefers Markdown when sites offer it, including advertised alternatives and documented Next.js and Vercel documentation endpoints, and can discover `/llms.txt` indexes. An index URL appears in the result when found; follow it if the page is insufficient. Pages that render entirely with JavaScript can return their authored no-JavaScript overview when one exists; the result says so, and script-rendered content remains unavailable. The tool can solve Anubis and supported AWS WAF proof-of-work challenges. If an AWS WAF or Cloudflare challenge remains blocked, it may fall back to the site's documentation index.
35
35
 
36
36
  Supported Reddit challenges can be solved or fall back to its public feed, whose comments may be incomplete and lack thread hierarchy. Comment permalinks do not use the feed fallback. Packit Copr job pages can return their public API data without an API key, and empty Swagger UI pages can return an advertised same-origin specification; result metadata identifies the substitute and its URL. Unsupported challenges and JavaScript CAPTCHAs return a blocked result; there is no browser fallback.
37
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -298,6 +298,7 @@ async function documentFromDecoded(
298
298
  let markdownAlternateUrl: string | undefined = linkHints.markdownAlternate;
299
299
  let sourceLanguage: string | undefined;
300
300
  let githubReadme = false;
301
+ let noscriptFallback = false;
301
302
  const openapiSpec = isOpenapiSource(raw, contentType);
302
303
 
303
304
  if (isHtmlContentType(contentType)) {
@@ -308,6 +309,7 @@ async function documentFromDecoded(
308
309
  surfaceView = extracted.surfaceView;
309
310
  extractor = extracted.extractor;
310
311
  githubReadme = extracted.githubReadme === true;
312
+ noscriptFallback = extracted.noscriptFallback === true;
311
313
  describedBy = describedBy ?? extracted.describedByLink;
312
314
  markdownAlternateUrl = markdownAlternateUrl ?? extracted.markdownAlternateLink;
313
315
  } else if (contentType === "application/json") {
@@ -396,8 +398,17 @@ async function documentFromDecoded(
396
398
  extractionDiagnostics.sparseExtraction = false;
397
399
  }
398
400
 
401
+ // An authored no-JavaScript fallback is readable content, not a shell artifact.
402
+ if (extractionDiagnostics && noscriptFallback && markdown.trim()) {
403
+ extractionDiagnostics.sparseExtraction = false;
404
+ }
405
+
399
406
  const shellSuspected = extractionDiagnostics
400
- ? hasExtractionWarning(extractionDiagnostics)
407
+ ? hasExtractionWarning(
408
+ noscriptFallback
409
+ ? { ...extractionDiagnostics, javascriptRequired: false }
410
+ : extractionDiagnostics,
411
+ )
401
412
  : false;
402
413
 
403
414
  const etag = responseHeader(response, "etag");
@@ -415,9 +426,11 @@ async function documentFromDecoded(
415
426
  extractionDiagnostics,
416
427
  links,
417
428
  validators: etag || lastModified ? { etag, lastModified } : undefined,
429
+ markdownPolicyVersion: 2,
418
430
  cachedAt: Date.now(),
419
431
  llmsTxtDescribedBy: describedBy,
420
432
  markdownAlternateUrl,
433
+ noscriptFallback,
421
434
  sourceLanguage,
422
435
  openapiSpec,
423
436
  swaggerSpecUrl,
@@ -664,6 +677,7 @@ async function fetchDocument(
664
677
  cached?: CompleteDocument,
665
678
  allowEmptyContent = false,
666
679
  retryRepresentationMiss = true,
680
+ preferHtml = false,
667
681
  ): Promise<{ document: CompleteDocument; revalidated: boolean }> {
668
682
  assertAbsoluteHttpUrlForFetch(normalizeGitHubRawUrl(rawUrl));
669
683
  const controller = new AbortController();
@@ -694,6 +708,12 @@ async function fetchDocument(
694
708
  const requestDependencies: FetchRemoteDependencies = {
695
709
  ...dependencies,
696
710
  cookies: dependencies.cookies ?? new CookieJar(),
711
+ persistentHeaders: preferHtml
712
+ ? {
713
+ ...dependencies.persistentHeaders,
714
+ Accept: "text/html, text/plain;q=0.9, */*;q=0.1",
715
+ }
716
+ : dependencies.persistentHeaders,
697
717
  };
698
718
 
699
719
  try {
@@ -704,7 +724,9 @@ async function fetchDocument(
704
724
  requestUrl,
705
725
  controller.signal,
706
726
  requestDependencies,
707
- conditionalHeaders,
727
+ preferHtml
728
+ ? { ...conditionalHeaders, Accept: "text/html, text/plain;q=0.9, */*;q=0.1" }
729
+ : conditionalHeaders,
708
730
  );
709
731
 
710
732
  // Some servers route Markdown negotiation to a missing representation even
@@ -794,6 +816,7 @@ async function fetchDocument(
794
816
  target.url,
795
817
  controller.signal,
796
818
  retryDependencies,
819
+ preferHtml ? { Accept: "text/html, text/plain;q=0.9, */*;q=0.1" } : {},
797
820
  ));
798
821
  }
799
822
  }
@@ -907,6 +930,7 @@ export async function fetchCompleteDocument(
907
930
  dependencies: FetchRemoteDependencies,
908
931
  allowEmptyContent = false,
909
932
  retryRepresentationMiss = true,
933
+ preferHtml = false,
910
934
  ): Promise<CompleteDocument> {
911
935
  return (
912
936
  await fetchDocument(
@@ -916,6 +940,7 @@ export async function fetchCompleteDocument(
916
940
  undefined,
917
941
  allowEmptyContent,
918
942
  retryRepresentationMiss,
943
+ preferHtml,
919
944
  )
920
945
  ).document;
921
946
  }
@@ -31,6 +31,9 @@ function restrictOrigin(
31
31
 
32
32
  const CACHE_TTL_MS = 24 * 60 * 60 * 1_000;
33
33
 
34
+ /** Bounds parallel index probes while allowing substantially deeper paths than two levels. */
35
+ const MAX_LLMS_TXT_CANDIDATES = 16;
36
+
34
37
  const LLMS_TXT_MIN_MARKDOWN_CHARACTERS = 200;
35
38
 
36
39
  const encoder = new TextEncoder();
@@ -44,11 +47,10 @@ function safeUrl(value: string): URL | undefined {
44
47
  }
45
48
 
46
49
  /**
47
- * Builds candidate `/llms.txt` URLs for a page: the site-root index plus each ancestor
48
- * directory index up to `MAX_LLMS_TXT_DIRECTORY_DEPTH` levels deep, mirroring sites that
49
- * publish per-section indexes (for example `developers.cloudflare.com/r2/llms.txt`).
50
- * Returns them ordered shallow → deep, and an empty list for non-HTTP(S) targets or when
51
- * the page itself is already a `llms.txt` path, so a fallback never retries itself.
50
+ * Builds candidate `/llms.txt` URLs for a page: the site-root index plus every ancestor
51
+ * directory index, mirroring sites that publish per-section indexes. Returns them ordered
52
+ * shallow → deep, and an empty list for non-HTTP(S) targets or when the page itself is
53
+ * already a `llms.txt` path, so a fallback never retries itself.
52
54
  */
53
55
  function isGitHubLikeHost(hostname: string): boolean {
54
56
  return (
@@ -79,9 +81,8 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
79
81
 
80
82
  if (url.pathname === "/llms.txt" || url.pathname.endsWith("/llms.txt")) return [];
81
83
 
82
- // Ancestor directories only, one level deep: for `/r2/buckets/x` probe
83
- // `/llms.txt` and `/r2/llms.txt`, never deeper. A trailing slash marks the final
84
- // segment as a directory itself, so `/r2/` still probes `/r2/llms.txt`.
84
+ // A trailing slash marks the final segment as a directory itself, so `/r2/`
85
+ // probes `/r2/llms.txt`.
85
86
  const trimmedDirectory = url.pathname.endsWith("/")
86
87
  ? url.pathname
87
88
  : url.pathname.replace(/\/[^/]*$/, "/");
@@ -89,11 +90,16 @@ export function buildLlmsTxtCandidateUrls(rawUrl: string): URL[] {
89
90
  const directories = ["/"];
90
91
  const parts = trimmedDirectory.split("/").filter(Boolean);
91
92
 
92
- for (let depth = 1; depth <= Math.min(MAX_LLMS_TXT_DIRECTORY_DEPTH, parts.length); depth += 1) {
93
+ for (let depth = 1; depth <= parts.length; depth += 1) {
93
94
  directories.push(`/${parts.slice(0, depth).join("/")}/`);
94
95
  }
95
96
 
96
- return directories.map((pathname) => {
97
+ const selectedDirectories =
98
+ directories.length <= MAX_LLMS_TXT_CANDIDATES
99
+ ? directories
100
+ : [directories[0], ...directories.slice(-(MAX_LLMS_TXT_CANDIDATES - 1))];
101
+
102
+ return selectedDirectories.map((pathname) => {
97
103
  const candidate = new URL(url.origin);
98
104
  candidate.pathname = `${pathname}llms.txt`;
99
105
 
@@ -126,6 +132,9 @@ export function documentationMarkdownUrl(value: string): URL | undefined {
126
132
  }
127
133
 
128
134
  function isLowQualityDocument(document: CompleteDocument): boolean {
135
+ // An authored fallback is readable content, so a site index would be a downgrade.
136
+ if (document.noscriptFallback && !document.extractionDiagnostics?.botWall) return false;
137
+
129
138
  // Sparse extraction alone is not proof of an empty app shell: server-rendered pages
130
139
  // may include useful content in streaming/framework markup that article extraction
131
140
  // does not fully recognize. Keep that page rather than replacing it with a site index.
@@ -144,14 +153,6 @@ interface LlmsTxtProbe {
144
153
 
145
154
  const MAX_LLMS_TXT_PROBE_ENTRIES = 512;
146
155
 
147
- /**
148
- * Deepest ancestor-directory `/llms.txt` probed, e.g. `/a/b/c` also probes
149
- * `/a/b/llms.txt`. Locale-prefixed documentation sites publish their section index
150
- * one level below the locale root, so two levels are needed to reach
151
- * `/en/docs/llms.txt` from `/en/docs/catalog/...`.
152
- */
153
- const MAX_LLMS_TXT_DIRECTORY_DEPTH = 2;
154
-
155
156
  const llmsTxtProbes = new ExpiringLruCache<string, LlmsTxtProbe>(
156
157
  MAX_LLMS_TXT_PROBE_ENTRIES,
157
158
  8 * 1024 * 1024,
@@ -193,21 +194,29 @@ async function ensureLlmsTxtIndex(
193
194
  signal: AbortSignal | undefined,
194
195
  dependencies: FetchRemoteDependencies,
195
196
  ): Promise<{ url: string; document: CompleteDocument; aliases?: string[] } | undefined> {
196
- const documents = await Promise.all(
197
- candidates.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
198
- );
197
+ // Candidates are ordered shallow → deep. Probe from the page upward in small batches:
198
+ // this preserves a preference for the deepest usable index without issuing every
199
+ // ancestor request when a nearby section index already exists.
200
+ const batchSize = 4;
199
201
 
200
- // Candidates are ordered shallow → deep; prefer the deepest usable index because a
201
- // section index is the more relevant table of contents for the requested page.
202
- for (let depth = documents.length - 1; depth >= 0; depth -= 1) {
203
- const document = documents[depth];
202
+ for (let end = candidates.length; end > 0; end -= batchSize) {
203
+ const start = Math.max(0, end - batchSize);
204
+ const batch = candidates.slice(start, end);
204
205
 
205
- if (document) {
206
- const aliases = documents.flatMap((other, i) =>
207
- i !== depth && other && other.markdown === document.markdown ? [candidates[i].href] : [],
208
- );
206
+ const documents = await Promise.all(
207
+ batch.map((candidate) => probeUsableRawText(candidate, signal, dependencies)),
208
+ );
209
+
210
+ for (let index = documents.length - 1; index >= 0; index -= 1) {
211
+ const document = documents[index];
209
212
 
210
- return { url: candidates[depth].href, document, aliases };
213
+ if (document) {
214
+ const aliases = documents.flatMap((other, i) =>
215
+ i !== index && other && other.markdown === document.markdown ? [batch[i].href] : [],
216
+ );
217
+
218
+ return { url: batch[index].href, document, aliases };
219
+ }
211
220
  }
212
221
  }
213
222
 
@@ -300,6 +309,8 @@ export async function fetchDocumentWithLlmsTxtSupport(
300
309
  rawUrl: string,
301
310
  signal: AbortSignal | undefined,
302
311
  dependencies: FetchRemoteDependencies,
312
+ preferHtml = false,
313
+ allowMarkdownAlternates = true,
303
314
  ): Promise<CompleteDocument> {
304
315
  try {
305
316
  const url = new URL(rawUrl);
@@ -345,7 +356,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
345
356
  // A withheld page must not discard an index that is still usable, so the pair is
346
357
  // settled instead of rejected together.
347
358
  const [primarySettled, indexSettled] = await Promise.allSettled([
348
- fetchCompleteDocument(rawUrl, signal, dependencies, true),
359
+ fetchCompleteDocument(rawUrl, signal, dependencies, true, true, preferHtml),
349
360
  candidates.length > 0
350
361
  ? ensureLlmsTxtIndex(candidates, signal, dependencies)
351
362
  : Promise.resolve(undefined),
@@ -405,6 +416,7 @@ export async function fetchDocumentWithLlmsTxtSupport(
405
416
  // Prefer a page-specific Markdown representation even when HTML extraction succeeded.
406
417
  // Restrict the entire redirect chain, and never substitute HTML or arbitrary text.
407
418
  if (
419
+ allowMarkdownAlternates &&
408
420
  !primary.surfaceView &&
409
421
  primary.extractor !== "raw" &&
410
422
  (!primary.markdownAlternateUrl || (!isLowQualityDocument(primary) && primary.markdown.trim()))
@@ -451,7 +463,10 @@ export async function fetchDocumentWithLlmsTxtSupport(
451
463
  : undefined;
452
464
 
453
465
  const alternate =
454
- !primary.surfaceView && markdownAlternate && isSafeToProbe(markdownAlternate, primary.url)
466
+ allowMarkdownAlternates &&
467
+ !primary.surfaceView &&
468
+ markdownAlternate &&
469
+ isSafeToProbe(markdownAlternate, primary.url)
455
470
  ? await probeUsableRawText(markdownAlternate, signal, dependencies)
456
471
  : undefined;
457
472
 
@@ -36,6 +36,8 @@ export interface CompleteDocument {
36
36
  links?: ExtractedLinks;
37
37
  /** HTTP validators retained for stale-cache revalidation. */
38
38
  validators?: { etag?: string; lastModified?: string };
39
+ /** Version of the Markdown-preference cache policy that produced this entry. */
40
+ markdownPolicyVersion?: 2;
39
41
  /** Time at which this representation was fetched or successfully revalidated. */
40
42
  cachedAt?: number;
41
43
  /** True when this document is the site's /llms.txt served instead of a low-quality page. */
@@ -54,6 +56,8 @@ export interface CompleteDocument {
54
56
  markdownAlternateUrl?: string;
55
57
  /** True when this document is a Markdown representation substituted for the requested page. */
56
58
  markdownAlternateFallback?: boolean;
59
+ /** True when this document is the page's authored no-JavaScript fallback content. */
60
+ noscriptFallback?: boolean;
57
61
  /** Why the Markdown representation was selected. */
58
62
  markdownAlternateReason?: "advertised" | "preferred";
59
63
  /** Same-origin OpenAPI document advertised by an otherwise empty Swagger UI. */
@@ -5,6 +5,13 @@ const MAX_LINKS = 16;
5
5
 
6
6
  const MAX_ANCHOR_CHARACTERS = 120;
7
7
 
8
+ /** Raw and extracted sizes below which an HTML page counts as sparsely extracted. */
9
+ const SPARSE_MIN_RAW_CHARACTERS = 4_000;
10
+
11
+ const SPARSE_MAX_MARKDOWN_CHARACTERS = 1_024;
12
+
13
+ const SPARSE_MAX_MARKDOWN_RATIO = 0.008;
14
+
8
15
  /** Bounded, machine-readable reasons that an HTML extraction may be incomplete. */
9
16
  export interface ExtractionDiagnostics {
10
17
  javascriptRequired: boolean;
@@ -78,6 +85,26 @@ const CONSENT_MARKERS = [
78
85
  /we\s+use\s+cookies/i,
79
86
  ];
80
87
 
88
+ /**
89
+ * Reports whether an extraction is too small for the markup it came from.
90
+ *
91
+ * @param rawCharacters - UTF-16 length of the fetched HTML
92
+ * @param markdownCharacters - UTF-16 length of the extracted Markdown
93
+ * @returns True when the extraction looks sparse for a page of this size
94
+ */
95
+ export function isSparseExtraction(rawCharacters: number, markdownCharacters: number): boolean {
96
+ return (
97
+ rawCharacters > SPARSE_MIN_RAW_CHARACTERS &&
98
+ markdownCharacters < SPARSE_MAX_MARKDOWN_CHARACTERS &&
99
+ markdownCharacters < rawCharacters * SPARSE_MAX_MARKDOWN_RATIO
100
+ );
101
+ }
102
+
103
+ /** Reports whether the HTML advertises that JavaScript is required to render the page. */
104
+ export function hasJavaScriptMarkers(raw: string): boolean {
105
+ return JAVASCRIPT_MARKERS.some((marker) => marker.test(raw));
106
+ }
107
+
81
108
  /** Produces explicit, bounded extraction-quality signals instead of one opaque shell flag. */
82
109
  export function diagnoseExtraction(raw: string, markdown: string): ExtractionDiagnostics {
83
110
  const { document } = parseHTML(raw);
@@ -96,7 +123,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
96
123
  CAPTCHA_WIDGET_MARKERS.some((marker) => marker.test(raw)));
97
124
 
98
125
  return {
99
- javascriptRequired: JAVASCRIPT_MARKERS.some((marker) => marker.test(raw)),
126
+ javascriptRequired: hasJavaScriptMarkers(raw),
100
127
  botWall:
101
128
  hasAnubisMarkers(raw) ||
102
129
  BOT_MARKERS.some((marker) => marker.test(raw)) ||
@@ -105,8 +132,7 @@ export function diagnoseExtraction(raw: string, markdown: string): ExtractionDia
105
132
  ANUBIS_PROTECTION_MARKERS.some((marker) => marker.test(anubisText)) &&
106
133
  PROOF_OF_WORK_MARKER.test(anubisText)),
107
134
  consentInterstitial: CONSENT_MARKERS.some((marker) => marker.test(raw)),
108
- sparseExtraction:
109
- raw.length > 4_000 && markdown.length < 1_024 && markdown.length < raw.length * 0.008,
135
+ sparseExtraction: isSparseExtraction(raw.length, markdown.length),
110
136
  rawCharacters: raw.length,
111
137
  extractedCharacters: markdown.length,
112
138
  };
@@ -3,11 +3,18 @@ import type { DefuddleResponse } from "defuddle/node";
3
3
  import { stripExtractedCssCruft } from "./markdown-cleanup.ts";
4
4
  import { buildFragmentOffsets } from "./fragment-index.ts";
5
5
  import { assertConversionDepth } from "./complexity.ts";
6
+ import { hasJavaScriptMarkers, isSparseExtraction } from "./evidence.ts";
6
7
 
7
8
  export { stripExtractedCssCruft } from "./markdown-cleanup.ts";
8
9
 
9
10
  const RAW_ID_SELECTOR_SAFE = /^-?[_a-zA-Z][-_a-zA-Z0-9]*$/;
10
11
 
12
+ /** Minimum authored no-JavaScript fallback length worth showing instead of a shell. */
13
+ const NOSCRIPT_FALLBACK_MIN_CHARACTERS = 200;
14
+
15
+ /** Primary extraction length below which a JavaScript-required page counts as a shell. */
16
+ const NOSCRIPT_PRIMARY_MAX_CHARACTERS = 1_024;
17
+
11
18
  /** Removes schema.org scripts that Defuddle would report directly to the process console. */
12
19
  function removeMalformedSchemaOrgData(document: Document): void {
13
20
  for (const script of document.querySelectorAll<HTMLScriptElement>(
@@ -464,6 +471,7 @@ async function extractHtmlDocument(
464
471
  describedByLink?: string;
465
472
  markdownAlternateLink?: string;
466
473
  githubReadme?: boolean;
474
+ noscriptFallback?: boolean;
467
475
  }> {
468
476
  // Keep refusal outside the catch: the fallback also constructs a DOM.
469
477
  assertConversionDepth(html);
@@ -630,6 +638,103 @@ function selectSurfaceHtml(
630
638
  return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
631
639
  }
632
640
 
641
+ /** Removes non-selected Android Compose BOM rows from the HTML table. */
642
+ export function filterAndroidBomHtml(html: string, version: string): string | undefined {
643
+ const { document } = parseHTML(html);
644
+ const rows = [...document.querySelectorAll<HTMLElement>("tr[filter-value]")];
645
+ const matching = rows.filter((row) => row.getAttribute("filter-value") === version);
646
+
647
+ if (matching.length === 0) return undefined;
648
+
649
+ for (const row of rows) {
650
+ if (row.getAttribute("filter-value") !== version) row.remove();
651
+ }
652
+
653
+ return document.documentElement.outerHTML;
654
+ }
655
+
656
+ /**
657
+ * Builds a standalone document from the page's no-JavaScript fallback blocks, or
658
+ * returns undefined when the page has none. The recovering document is reparsed
659
+ * through the same depth preflight when it is extracted.
660
+ */
661
+ function noscriptFallbackHtml(html: string): string | undefined {
662
+ if (!/<noscript[\s>]/i.test(html)) return undefined;
663
+
664
+ let sections: string[];
665
+
666
+ try {
667
+ const { document } = parseHTML(html);
668
+
669
+ sections = [...document.querySelectorAll("noscript")].flatMap((block) => {
670
+ const inner = block.innerHTML.trim();
671
+
672
+ return inner.length > 0 ? [inner] : [];
673
+ });
674
+ } catch {
675
+ return undefined;
676
+ }
677
+
678
+ return sections.length === 0
679
+ ? undefined
680
+ : `<html><head></head><body>${sections.join("\n")}</body></html>`;
681
+ }
682
+
683
+ /**
684
+ * Reports whether the primary extraction is too weak to represent the page: empty,
685
+ * sparse for its markup, or no more than a JavaScript-required notice.
686
+ */
687
+ function isWeakExtraction(html: string, markdown: string): boolean {
688
+ const length = markdown.trim().length;
689
+ const substantive = length >= NOSCRIPT_FALLBACK_MIN_CHARACTERS;
690
+
691
+ if (length === 0) return true;
692
+
693
+ if (isSparseExtraction(html.length, length) && !substantive) return true;
694
+
695
+ return length < NOSCRIPT_PRIMARY_MAX_CHARACTERS && hasJavaScriptMarkers(html) && !substantive;
696
+ }
697
+
698
+ /**
699
+ * Reads the page's authored no-JavaScript fallback when the primary extraction is
700
+ * empty, sparse, or only a JavaScript-required notice. Readable pages keep their
701
+ * primary content, so fallback navigation or notices never replace real content.
702
+ */
703
+ async function extractNoscriptFallback(
704
+ html: string,
705
+ baseUrl: URL,
706
+ primary: Awaited<ReturnType<typeof extractHtmlDocument>>,
707
+ ): Promise<Awaited<ReturnType<typeof extractHtmlDocument>> | undefined> {
708
+ if (!isWeakExtraction(html, primary.markdown)) return undefined;
709
+
710
+ const fallbackHtml = noscriptFallbackHtml(html);
711
+
712
+ if (!fallbackHtml) return undefined;
713
+
714
+ try {
715
+ const fallback = await extractHtmlDocument(fallbackHtml, baseUrl);
716
+
717
+ if (
718
+ fallback.markdown.length < NOSCRIPT_FALLBACK_MIN_CHARACTERS ||
719
+ fallback.markdown.length <= primary.markdown.length
720
+ )
721
+ return undefined;
722
+
723
+ return {
724
+ ...fallback,
725
+ // The synthesized document has no head metadata of its own.
726
+ title: primary.title ?? fallback.title,
727
+ githubReadme: primary.githubReadme,
728
+ describedByLink: primary.describedByLink ?? fallback.describedByLink,
729
+ markdownAlternateLink: primary.markdownAlternateLink ?? fallback.markdownAlternateLink,
730
+ noscriptFallback: true,
731
+ };
732
+ } catch {
733
+ // A fallback must never make an otherwise readable page unavailable.
734
+ return undefined;
735
+ }
736
+ }
737
+
633
738
  /** Extract the complete page and, when explicitly requested, a separate surface view. */
634
739
  export async function extractHtmlToMarkdown(
635
740
  html: string,
@@ -645,7 +750,8 @@ export async function extractHtmlToMarkdown(
645
750
  }
646
751
  > {
647
752
  assertConversionDepth(html);
648
- const complete = await extractHtmlDocument(html, baseUrl);
753
+ const primary = await extractHtmlDocument(html, baseUrl);
754
+ const complete = (await extractNoscriptFallback(html, baseUrl, primary)) ?? primary;
649
755
 
650
756
  try {
651
757
  const surface = selectSurfaceHtml(html, baseUrl);
@@ -1,9 +1,25 @@
1
- import { parse } from "acorn";
2
- import { simple } from "acorn-walk";
3
- import { parseDocument } from "yaml";
1
+ import { createRequire } from "node:module";
4
2
  import { Type } from "typebox";
5
3
  import { Check } from "typebox/value";
6
4
 
5
+ const require = createRequire(import.meta.url);
6
+
7
+ let parserModules:
8
+ | {
9
+ parse: typeof import("acorn").parse;
10
+ simple: typeof import("acorn-walk").simple;
11
+ parseDocument: typeof import("yaml").parseDocument;
12
+ }
13
+ | undefined;
14
+
15
+ function getParserModules(): NonNullable<typeof parserModules> {
16
+ return (parserModules ??= {
17
+ parse: require("acorn").parse,
18
+ simple: require("acorn-walk").simple,
19
+ parseDocument: require("yaml").parseDocument,
20
+ });
21
+ }
22
+
7
23
  const schema = Type.Union([
8
24
  Type.Object({
9
25
  openapi: Type.String({ pattern: "^3\\.\\d+\\.\\d+$" }),
@@ -24,12 +40,13 @@ export function isOpenapiSource(raw: string, contentType: string): boolean {
24
40
  if (contentType === "application/json") return Check(schema, JSON.parse(raw));
25
41
 
26
42
  if (contentType === "text/yaml") {
27
- const document = parseDocument(raw, { uniqueKeys: true });
43
+ const document = getParserModules().parseDocument(raw, { uniqueKeys: true });
28
44
 
29
45
  return document.errors.length === 0 && Check(schema, document.toJS({ maxAliasCount: 0 }));
30
46
  }
31
47
 
32
48
  if (contentType !== "text/javascript") return false;
49
+ const { parse, simple } = getParserModules();
33
50
  const ast = parse(raw, { ecmaVersion: "latest", sourceType: "module" });
34
51
  let found = false;
35
52
  simple(ast, {
@@ -215,7 +215,7 @@ export async function requestFollowingRedirects(
215
215
  throw new Error("web_fetch followed too many redirects.");
216
216
  target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
217
217
  // Validators describe the originally cached resource and must not leak to a redirect target.
218
- // Challenge handshakes opt into a fixed browser identity instead.
218
+ // Representation preferences and challenge identities are safe to retain.
219
219
  requestHeaders = dependencies.persistentHeaders ?? {};
220
220
  }
221
221
 
package/src/service.ts CHANGED
@@ -12,6 +12,7 @@ import { ExpiringLruCache, stableKeyHash, canonicalKey, type CachePersistence }
12
12
  import { sliceCompleteDocument, type CompleteDocument } from "./document/content.ts";
13
13
  import { revalidateCompleteDocument, type FetchRemoteDependencies } from "./acquisition/fetch.ts";
14
14
  import { fetchDocumentWithLlmsTxtSupport } from "./acquisition/llms.ts";
15
+ import { extractHtmlToMarkdown, filterAndroidBomHtml } from "./document/extract.ts";
15
16
  import { focusMarkdown, type FocusDetails } from "./document/focus.ts";
16
17
  import { isCachedOpenapi } from "./document/openapi.ts";
17
18
  import { resolveFragmentOffset, urlWithoutFragment } from "./document/fragments.ts";
@@ -37,6 +38,27 @@ const CACHE_MAX_MARKDOWN_BYTES = 20 * 1_024 * 1_024;
37
38
 
38
39
  const MAX_INFLIGHT_REQUESTS = 100;
39
40
 
41
+ interface CacheDimensions {
42
+ surfaceExtraction?: number;
43
+ androidBomVersion?: string;
44
+ }
45
+
46
+ function androidBomVersionQuery(url: string, query: string | undefined): string | undefined {
47
+ if (query === undefined || !/^\d{4}\.\d{2}\.\d{2}$/.test(query.trim())) return undefined;
48
+
49
+ try {
50
+ const parsed = new URL(url);
51
+
52
+ return parsed.protocol === "https:" &&
53
+ parsed.hostname === "developer.android.com" &&
54
+ parsed.pathname === "/develop/ui/compose/bom/bom-mapping"
55
+ ? query.trim()
56
+ : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
40
62
  /** Minimum extracted length for both the low-quality trigger and llms.txt acceptance. */
41
63
  const encoder = new TextEncoder();
42
64
 
@@ -212,6 +234,8 @@ export interface WebFetchDetails {
212
234
  llmsTxtFallback: boolean;
213
235
  /** True when the returned content is the page's advertised Markdown version served instead of a low-quality page. */
214
236
  markdownAlternateFallback: boolean;
237
+ /** True when the returned content is the page's authored no-JavaScript fallback. */
238
+ noscriptFallback: boolean;
215
239
  /** Identifies an API or specification used instead of the page. */
216
240
  representationFallback?: CompleteDocument["representationFallback"];
217
241
  /** The site's /llms.txt index URL when one exists and the returned content is not that index itself. */
@@ -252,6 +276,7 @@ export interface WebFetchStructuredOutput {
252
276
  characterCount: number;
253
277
  llmsTxtFallback: boolean;
254
278
  markdownAlternateFallback: boolean;
279
+ noscriptFallback: boolean;
255
280
  representationFallback?: CompleteDocument["representationFallback"];
256
281
  extraction?: CompleteDocument["extractionDiagnostics"];
257
282
  focus?: FocusDetails;
@@ -279,6 +304,7 @@ export const webFetchOutputSchema = Type.Object({
279
304
  characterCount: Type.Integer(),
280
305
  llmsTxtFallback: Type.Boolean(),
281
306
  markdownAlternateFallback: Type.Boolean(),
307
+ noscriptFallback: Type.Boolean(),
282
308
  representationFallback: Type.Optional(
283
309
  Type.Union([Type.Literal("packit-api"), Type.Literal("swagger-spec")]),
284
310
  ),
@@ -369,6 +395,8 @@ const completeDocumentCacheSchema = Type.Object(
369
395
  lastModified: Type.Optional(Type.String()),
370
396
  }),
371
397
  ),
398
+ markdownPolicyVersion: Type.Optional(Type.Literal(2)),
399
+ noscriptFallback: Type.Optional(Type.Boolean()),
372
400
  llmsTxtFallback: Type.Optional(Type.Boolean()),
373
401
  llmsTxtIndexUrl: Type.Optional(Type.String()),
374
402
  llmsTxtDescribedBy: Type.Optional(Type.String()),
@@ -408,6 +436,17 @@ interface FetchAcquisition {
408
436
 
409
437
  const inflightFetches = new InflightCoalescer<string, FetchAcquisition>(MAX_INFLIGHT_REQUESTS);
410
438
 
439
+ /** Returns whether a stale entry predates the Markdown-preference cache policy. */
440
+ export function staleCacheNeedsMarkdownPolicy(document: CompleteDocument): boolean {
441
+ return (
442
+ document.markdownPolicyVersion !== 2 &&
443
+ document.extractor !== "raw" &&
444
+ !document.surfaceView &&
445
+ !document.llmsTxtFallback &&
446
+ !document.representationFallback
447
+ );
448
+ }
449
+
411
450
  /**
412
451
  * Executes a validated web fetch, including caching, focusing, and bounded pagination.
413
452
  *
@@ -469,11 +508,16 @@ export async function executeWebFetch(
469
508
 
470
509
  const displayRequestedUrl = redactUrlForDisplay(params.url);
471
510
  const sourceUrl = urlWithoutFragment(params.url);
511
+ const bomVersion = androidBomVersionQuery(sourceUrl, params.query);
472
512
 
473
513
  // Older persisted entries predate surface views and must not mask explicit selections.
474
- const cacheKey = safeUrl(sourceUrl)?.searchParams.has("tab")
475
- ? canonicalKey({ url: sourceUrl, surfaceExtraction: 1 })
476
- : canonicalKey({ url: sourceUrl });
514
+ const cacheDimensions: CacheDimensions = {};
515
+
516
+ if (safeUrl(sourceUrl)?.searchParams.has("tab")) cacheDimensions.surfaceExtraction = 1;
517
+
518
+ if (bomVersion) cacheDimensions.androidBomVersion = bomVersion;
519
+
520
+ const cacheKey = canonicalKey({ url: sourceUrl, ...cacheDimensions });
477
521
 
478
522
  let document = fetchCache.get(cacheKey);
479
523
  const now = Date.now();
@@ -509,19 +553,16 @@ export async function executeWebFetch(
509
553
  let fetched: CompleteDocument;
510
554
  let acquisitionStatus: FetchAcquisition["cacheStatus"] = "miss";
511
555
 
512
- const staleCanUseMarkdownPolicy =
513
- stale !== undefined &&
514
- stale.extractor !== "raw" &&
515
- !stale.surfaceView &&
516
- !stale.llmsTxtFallback &&
517
- !stale.representationFallback;
556
+ const staleNeedsMarkdownPolicy =
557
+ stale !== undefined && staleCacheNeedsMarkdownPolicy(stale);
518
558
 
519
559
  if (
520
560
  stale?.validators &&
521
- !staleCanUseMarkdownPolicy &&
561
+ !staleNeedsMarkdownPolicy &&
522
562
  !stale.llmsTxtFallback &&
523
563
  !stale.markdownAlternateFallback &&
524
- !stale.representationFallback
564
+ !stale.representationFallback &&
565
+ !bomVersion
525
566
  ) {
526
567
  const outcome = await revalidateCompleteDocument(
527
568
  sourceUrl,
@@ -533,7 +574,27 @@ export async function executeWebFetch(
533
574
  fetched = outcome.document;
534
575
  acquisitionStatus = outcome.revalidated ? "revalidated" : "miss";
535
576
  } else {
536
- fetched = await fetchDocumentWithLlmsTxtSupport(sourceUrl, sharedSignal, dependencies);
577
+ const acquisitionDependencies = bomVersion
578
+ ? {
579
+ ...dependencies,
580
+ extractHtml: async (html: string, url: URL) => {
581
+ const filtered = filterAndroidBomHtml(html, bomVersion);
582
+
583
+ if (filtered === undefined)
584
+ throw new Error(`web_fetch: Android BOM version ${bomVersion} was not found.`);
585
+
586
+ return extractHtmlToMarkdown(filtered, url);
587
+ },
588
+ }
589
+ : dependencies;
590
+
591
+ fetched = await fetchDocumentWithLlmsTxtSupport(
592
+ sourceUrl,
593
+ sharedSignal,
594
+ acquisitionDependencies,
595
+ Boolean(bomVersion),
596
+ !bomVersion,
597
+ );
537
598
  }
538
599
 
539
600
  if (!fetched.extractionDiagnostics?.botWall) {
@@ -627,7 +688,7 @@ export async function executeWebFetch(
627
688
  : document;
628
689
 
629
690
  const focused =
630
- blocked || params.query === undefined
691
+ blocked || params.query === undefined || bomVersion
631
692
  ? undefined
632
693
  : focusMarkdown(fragmentDocument.markdown, params.query);
633
694
 
@@ -700,6 +761,12 @@ export async function executeWebFetch(
700
761
  "",
701
762
  ]
702
763
  : []),
764
+ ...(result.noscriptFallback
765
+ ? [
766
+ "[Showing the page's no-JavaScript fallback; script-rendered content is unavailable.]",
767
+ "",
768
+ ]
769
+ : []),
703
770
  ...(result.llmsTxtFallback
704
771
  ? [
705
772
  "[Showing the site index instead of the requested page. Follow a link for details.]",
@@ -790,6 +857,7 @@ export async function executeWebFetch(
790
857
  characterCount: 0,
791
858
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
792
859
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
860
+ noscriptFallback: Boolean(result.noscriptFallback),
793
861
  representationFallback: result.representationFallback,
794
862
  extraction: result.extractionDiagnostics,
795
863
  focus: focused?.details,
@@ -853,6 +921,7 @@ export async function executeWebFetch(
853
921
  surface,
854
922
  llmsTxtFallback: Boolean(result.llmsTxtFallback),
855
923
  markdownAlternateFallback: Boolean(result.markdownAlternateFallback),
924
+ noscriptFallback: Boolean(result.noscriptFallback),
856
925
  representationFallback: result.representationFallback,
857
926
  llmsTxtUrl:
858
927
  result.llmsTxtIndexUrl === undefined