@zeldrisho/pi-web-fetch 0.18.1 → 0.18.2

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.
@@ -2,6 +2,8 @@ import { parseHTML } from "linkedom";
2
2
  import type { DefuddleResponse } from "defuddle/node";
3
3
  import { stripExtractedCssCruft } from "./markdown-cleanup.ts";
4
4
  import { buildFragmentOffsets } from "./fragment-index.ts";
5
+ import { isFragmentTabId, urlFragment, urlWithoutFragment } from "./fragments.ts";
6
+ import { MAX_CACHED_FRAGMENT_TABS, type CompleteDocument } from "./content.ts";
5
7
  import { assertConversionDepth } from "./complexity.ts";
6
8
  import { hasJavaScriptMarkers, isSparseExtraction } from "./evidence.ts";
7
9
 
@@ -13,7 +15,7 @@ const RAW_ID_SELECTOR_SAFE = /^-?[_a-zA-Z][-_a-zA-Z0-9]*$/;
13
15
  const NOSCRIPT_FALLBACK_MIN_CHARACTERS = 200;
14
16
 
15
17
  /** Primary extraction length below which a JavaScript-required page counts as a shell. */
16
- const NOSCRIPT_PRIMARY_MAX_CHARACTERS = 1_024;
18
+ const NOSCRIPT_PRIMARY_MAX_CHARACTERS = 1024;
17
19
 
18
20
  /** Removes schema.org scripts that Defuddle would report directly to the process console. */
19
21
  function removeMalformedSchemaOrgData(document: Document): void {
@@ -21,9 +23,9 @@ function removeMalformedSchemaOrgData(document: Document): void {
21
23
  'script[type="application/ld+json"]',
22
24
  )) {
23
25
  const jsonContent = (script.textContent || "")
24
- .replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "")
26
+ .replaceAll(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "")
25
27
  .replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1")
26
- .replace(/^\s*(\*\/|\/\*)\s*|\s*(\*\/|\/\*)\s*$/g, "")
28
+ .replaceAll(/^\s*(\*\/|\/\*)\s*|\s*(\*\/|\/\*)\s*$/g, "")
27
29
  .trim();
28
30
 
29
31
  try {
@@ -100,16 +102,11 @@ function normalizeFragmentDocument(document: Document): void {
100
102
 
101
103
  const html = document.createElement("html");
102
104
  const head = document.createElement("head");
103
- const body = document.createElement("body");
105
+ const body = root?.tagName === "BODY" ? root : document.createElement("body");
106
+ const nodes = body === root ? [] : [...document.childNodes];
104
107
  html.appendChild(head);
105
108
  html.appendChild(body);
106
109
 
107
- const nodes = root
108
- ? root.tagName === "BODY"
109
- ? [...root.childNodes]
110
- : [...document.childNodes]
111
- : [...document.childNodes];
112
-
113
110
  for (const node of nodes) {
114
111
  if (node.nodeType === 3) {
115
112
  body.appendChild(node);
@@ -136,6 +133,57 @@ function normalizeFragmentDocument(document: Document): void {
136
133
  document.insertBefore(html, document.firstChild);
137
134
  }
138
135
 
136
+ function isExplicitlyHidden(element: Element): boolean {
137
+ return (
138
+ element.hasAttribute("hidden") ||
139
+ element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
140
+ /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
141
+ element.getAttribute("style") ?? "",
142
+ )
143
+ );
144
+ }
145
+
146
+ /** Removes hidden content, preserving the body element for fallback extraction. */
147
+ function removeHiddenBodyElements(document: Document): boolean {
148
+ const { body } = document;
149
+
150
+ if (isExplicitlyHidden(body)) {
151
+ body.replaceChildren();
152
+ return true;
153
+ }
154
+
155
+ for (const element of body.querySelectorAll("[hidden], [aria-hidden], [style]")) {
156
+ if (isExplicitlyHidden(element)) element.remove();
157
+ }
158
+
159
+ return false;
160
+ }
161
+
162
+ /** Detects an explicitly marked but empty main region with a script in place of content. */
163
+ function hasEmptyScriptedMain(document: Document): boolean {
164
+ const regions = document.body.querySelectorAll('main, [role="main"]');
165
+
166
+ if (regions.length !== 1) return false;
167
+
168
+ const main = regions[0];
169
+
170
+ if (
171
+ !main.querySelector("script") ||
172
+ main.querySelector("img, svg, video, audio, canvas, iframe, object, embed, form")
173
+ ) {
174
+ return false;
175
+ }
176
+
177
+ const copy = document.createElement("div");
178
+ copy.appendChild(main.cloneNode(true));
179
+
180
+ for (const element of copy.querySelectorAll("script, style, template, noscript")) {
181
+ element.remove();
182
+ }
183
+
184
+ return !(copy.textContent ?? "").trim();
185
+ }
186
+
139
187
  /**
140
188
  * Extracts normalized plain text from HTML when structured Markdown extraction is unavailable.
141
189
  *
@@ -154,22 +202,7 @@ export function htmlToMarkdownFallback(html: string): string {
154
202
  element.remove();
155
203
  }
156
204
 
157
- for (const element of document.querySelectorAll("[hidden], [aria-hidden], [style]")) {
158
- const style = element.getAttribute("style") ?? "";
159
-
160
- const hiddenStyle =
161
- /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
162
- style,
163
- );
164
-
165
- if (
166
- element.hasAttribute("hidden") ||
167
- element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
168
- hiddenStyle
169
- ) {
170
- element.remove();
171
- }
172
- }
205
+ removeHiddenBodyElements(document);
173
206
 
174
207
  for (const element of document.body.querySelectorAll(
175
208
  "p, div, section, article, li, blockquote, pre, h1, h2, h3, h4, h5, h6, br, tr",
@@ -178,10 +211,10 @@ export function htmlToMarkdownFallback(html: string): string {
178
211
  }
179
212
 
180
213
  return document.body.textContent
181
- .replace(/[ \t]+\n/g, "\n")
182
- .replace(/\n[ \t]+/g, "\n")
183
- .replace(/[ \t]{2,}/g, " ")
184
- .replace(/\n{3,}/g, "\n\n")
214
+ .replaceAll(/[ \t]+\n/g, "\n")
215
+ .replaceAll(/\n[ \t]+/g, "\n")
216
+ .replaceAll(/[ \t]{2,}/g, " ")
217
+ .replaceAll(/\n{3,}/g, "\n\n")
185
218
  .trim();
186
219
  }
187
220
 
@@ -232,7 +265,6 @@ function resolveDocumentRelativeMetadataUrls(document: Document, pageUrl: URL):
232
265
  * @param value - The value to check
233
266
  * @returns `true` if the value is a string
234
267
  */
235
- // oxlint-disable-next-line anti-slop/no-unknown-parameters -- type-guard helper intentionally narrows unknown at call site
236
268
  function isString(value: unknown): value is string {
237
269
  return typeof value === "string";
238
270
  }
@@ -246,8 +278,7 @@ function isBarePathnameInvalidUrl(cause: unknown): boolean {
246
278
  const input = (cause as NodeJS.ErrnoException & { input?: unknown }).input;
247
279
 
248
280
  if (isString(input) && input.startsWith("/")) return true;
249
- // SAFETY: Error.stack is an optional string populated by V8; we coerce it for pattern matching.
250
- const detail = `${cause.message}\n${(cause as Error).stack ?? ""}`;
281
+ const detail = `${cause.message}\n${cause.stack ?? ""}`;
251
282
 
252
283
  // Node's ERR_INVALID_URL prints `input: '/path'` in the message/stack even when
253
284
  // `input` is not on the error instance in some Node versions.
@@ -274,8 +305,12 @@ function stripChromeWrappers(document: Document, baseUrl: URL): void {
274
305
 
275
306
  /** Restricts GitHub repository roots to their rendered README, when available. */
276
307
  function isolateGitHubReadme(document: Document, baseUrl: URL): boolean {
277
- if (baseUrl.hostname !== "github.com" || baseUrl.pathname.split("/").filter(Boolean).length !== 2)
308
+ if (
309
+ baseUrl.hostname !== "github.com" ||
310
+ baseUrl.pathname.split("/").filter(Boolean).length !== 2
311
+ ) {
278
312
  return false;
313
+ }
279
314
 
280
315
  let readme = document.querySelector("main article.markdown-body.entry-content[itemprop='text']");
281
316
 
@@ -326,7 +361,7 @@ function deduplicateAdjacentLinks(markdown: string): string {
326
361
  }
327
362
 
328
363
  // Also collapse duplicate adjacent blocks like a repeated vite-plus tag link paragraph.
329
- return out.join("\n").replace(/(\[[^\n]+?\([^)]+\)[^\n]*\n)\1/g, "$1");
364
+ return out.join("\n").replaceAll(/(\[[^\n]+?\([^)]+\)[^\n]*\n)\1/g, "$1");
330
365
  }
331
366
 
332
367
  /**
@@ -390,9 +425,11 @@ async function runDefuddle(
390
425
  // Let Defuddle's scheduled microtask/macrotask work settle so a detached
391
426
  // rejection is observed by the guard instead of reaching the harness.
392
427
  await Promise.resolve();
393
- await new Promise<void>((resolve) => setImmediate(resolve));
428
+ await new Promise<void>((resolve) => {
429
+ setImmediate(resolve);
430
+ });
394
431
 
395
- if (escapedRejection !== undefined) throw escapedRejection;
432
+ if (escapedRejection !== undefined) return undefined;
396
433
 
397
434
  return result;
398
435
  } catch {
@@ -478,6 +515,10 @@ async function extractHtmlDocument(
478
515
  let advertised: AdvertisedLinks = {};
479
516
  let fallbackHtml = html;
480
517
  let githubReadme = false;
518
+ let emptyScriptedMain = false;
519
+
520
+ const omitSparseChrome = (markdown: string): string =>
521
+ emptyScriptedMain && isSparseExtraction(html.length, markdown.length) ? "" : markdown;
481
522
 
482
523
  try {
483
524
  assertAbsoluteHttpUrl(baseUrl);
@@ -497,9 +538,14 @@ async function extractHtmlDocument(
497
538
  stripChromeWrappers(document, baseUrl);
498
539
  advertised = readAdvertisedLinks(document, baseUrl);
499
540
 
541
+ if (removeHiddenBodyElements(document)) {
542
+ return { markdown: "", extractor: "basic", ...advertised };
543
+ }
544
+
500
545
  githubReadme = isolateGitHubReadme(document, baseUrl);
501
546
 
502
547
  if (githubReadme) fallbackHtml = document.documentElement.outerHTML;
548
+ emptyScriptedMain = isSparseExtraction(html.length, 0) && hasEmptyScriptedMain(document);
503
549
  normalizeSelectorUnsafeIds(document);
504
550
  // Pass the full absolute URL so Defuddle resolves relative links (e.g.
505
551
  // `/owner/repo/releases`) and metadata against the real origin instead of
@@ -513,12 +559,14 @@ async function extractHtmlDocument(
513
559
  const trimmedTitle = result?.title?.trim();
514
560
 
515
561
  if (markdown) {
562
+ const visibleMarkdown = omitSparseChrome(markdown);
563
+
516
564
  return {
517
- markdown,
565
+ markdown: visibleMarkdown,
518
566
  title: trimmedTitle || undefined,
519
567
  extractor: "defuddle",
520
568
  githubReadme,
521
- fragmentOffsets: buildFragmentOffsets(document, markdown, originalIds),
569
+ fragmentOffsets: buildFragmentOffsets(document, visibleMarkdown, originalIds),
522
570
  ...advertised,
523
571
  };
524
572
  }
@@ -526,7 +574,10 @@ async function extractHtmlDocument(
526
574
  // Fall through to the basic converter for malformed or unsupported pages.
527
575
  }
528
576
 
529
- const fallbackMarkdown = stripExtractedCssCruft(htmlToMarkdownFallback(fallbackHtml));
577
+ const fallbackMarkdown = omitSparseChrome(
578
+ stripExtractedCssCruft(htmlToMarkdownFallback(fallbackHtml)),
579
+ );
580
+
530
581
  let fragmentOffsets: Record<string, number> = {};
531
582
 
532
583
  try {
@@ -544,18 +595,29 @@ async function extractHtmlDocument(
544
595
  };
545
596
  }
546
597
 
598
+ type SurfaceHtml = Pick<
599
+ NonNullable<CompleteDocument["surfaceView"]>,
600
+ "selected" | "omitted" | "fragmentSelected"
601
+ > & { html: string };
602
+
603
+ /** A URL-selected pane may be hidden by the server's default tab state. */
604
+ function revealPane(pane: Element): void {
605
+ pane.removeAttribute("hidden");
606
+ pane.removeAttribute("aria-hidden");
607
+ pane.removeAttribute("style");
608
+ }
609
+
547
610
  /** Select only an explicitly requested, unambiguous surface control and sibling panes. */
548
- function selectSurfaceHtml(
549
- html: string,
550
- url: URL,
551
- ): { html: string; selected: string; omitted: number } | undefined {
611
+ function selectSurfaceHtml(html: string, url: URL): SurfaceHtml | undefined {
552
612
  const values = url.searchParams.getAll("tab");
553
613
 
554
614
  if (values.length !== 1 || !/^[a-z0-9-]{1,40}$/u.test(values[0])) return undefined;
555
615
  const selected = values[0];
556
616
  const { document } = parseHTML(html);
557
617
  normalizeFragmentDocument(document);
558
- const candidates: Array<{ panes: Element[]; chosen: Element }> = [];
618
+
619
+ if (isExplicitlyHidden(document.body)) return undefined;
620
+ const candidates: { panes: Element[]; chosen: Element }[] = [];
559
621
 
560
622
  // Standard ARIA controls identify their panels by ID. The query value must
561
623
  // match a control ID or panel ID exactly; labels are not URL identifiers.
@@ -608,8 +670,9 @@ function selectSurfaceHtml(
608
670
  chosen &&
609
671
  ids.every((id) => id && paneIds.includes(id)) &&
610
672
  surfacePanes.every((pane) => pane.parentElement === surfacePanes[0].parentElement)
611
- )
673
+ ) {
612
674
  candidates.push({ panes: surfacePanes, chosen });
675
+ }
613
676
  }
614
677
 
615
678
  const unique = candidates.filter(
@@ -630,14 +693,101 @@ function selectSurfaceHtml(
630
693
  if (!chosen?.textContent?.trim()) return undefined;
631
694
 
632
695
  for (const pane of panes) if (pane !== chosen) pane.remove();
633
- // The selected pane may be hidden by the server's default inline state.
634
- chosen.removeAttribute("hidden");
635
- chosen.removeAttribute("aria-hidden");
636
- chosen.removeAttribute("style");
696
+ revealPane(chosen);
637
697
 
638
698
  return { html: document.documentElement.outerHTML, selected, omitted: panes.length - 1 };
639
699
  }
640
700
 
701
+ /** Indexes unambiguous same-page tab links so ordinary anchors can reuse the full page. */
702
+ function fragmentTabPanes(html: string, url: URL): Map<string, { pane: Element; omitted: number }> {
703
+ const selections = new Map<string, { pane: Element; omitted: number }>();
704
+ const { document } = parseHTML(html);
705
+ normalizeFragmentDocument(document);
706
+ const groups = document.querySelectorAll('ul.tabs, [role="tablist"]');
707
+
708
+ if (!groups.length || isExplicitlyHidden(document.body)) return selections;
709
+ const baseHref = document.querySelector("base[href]")?.getAttribute("href");
710
+
711
+ if (baseHref) {
712
+ const base = URL.parse(baseHref, url);
713
+
714
+ if (!base || urlWithoutFragment(base.href) !== urlWithoutFragment(url.href)) return selections;
715
+ }
716
+
717
+ const byId = new Map<string, Element | null>();
718
+
719
+ for (const pane of document.querySelectorAll("[id]")) {
720
+ byId.set(pane.id, byId.has(pane.id) ? null : pane);
721
+ }
722
+
723
+ const seen = new Set<string>();
724
+
725
+ for (const group of groups) {
726
+ const materialize = group.matches("ul.tabs");
727
+ const controls = materialize
728
+ ? [...group.children].map((item) =>
729
+ item.matches("li.tab") && item.children.length === 1 ? item.firstElementChild : null,
730
+ )
731
+ : [...group.querySelectorAll('[role="tab"]')].filter(
732
+ (control) => control.closest('[role="tablist"]') === group,
733
+ );
734
+
735
+ if (controls.length < 2 || controls.length > 20) continue;
736
+ const ids = controls.map((control) => {
737
+ const href = control?.matches("a[href]") ? control.getAttribute("href") : undefined;
738
+
739
+ if (!href?.startsWith("#")) return undefined;
740
+ const id = urlFragment(new URL(href, url).href);
741
+ const target = control?.getAttribute("aria-controls");
742
+
743
+ return target === null || target === id ? id : undefined;
744
+ });
745
+ if (new Set(ids).size !== ids.length) continue;
746
+ const panes = ids.map((id) => (id === undefined ? undefined : byId.get(id)));
747
+ const parent = panes[0]?.parentElement;
748
+
749
+ if (
750
+ !parent ||
751
+ panes.some(
752
+ (pane) =>
753
+ !pane ||
754
+ pane.parentElement !== parent ||
755
+ pane.contains(group) ||
756
+ (!materialize && pane.getAttribute("role") !== "tabpanel"),
757
+ )
758
+ ) {
759
+ continue;
760
+ }
761
+
762
+ for (const [index, pane] of panes.entries()) {
763
+ const id = ids[index];
764
+
765
+ if (!pane || !id || !isFragmentTabId(id)) continue;
766
+
767
+ if (seen.has(id)) {
768
+ selections.delete(id);
769
+ } else if (pane.textContent?.trim()) {
770
+ selections.set(id, { pane, omitted: panes.length - 1 });
771
+ }
772
+
773
+ seen.add(id);
774
+ }
775
+ }
776
+
777
+ return selections;
778
+ }
779
+
780
+ function materializeFragmentTab(selected: string, pane: Element, omitted: number): SurfaceHtml {
781
+ revealPane(pane);
782
+
783
+ return {
784
+ html: `<html><head></head><body><main>${pane.outerHTML}</main></body></html>`,
785
+ selected,
786
+ omitted,
787
+ fragmentSelected: true,
788
+ };
789
+ }
790
+
641
791
  /** Removes non-selected Android Compose BOM rows from the HTML table. */
642
792
  export function filterAndroidBomHtml(html: string, version: string): string | undefined {
643
793
  const { document } = parseHTML(html);
@@ -665,6 +815,9 @@ function noscriptFallbackHtml(html: string): string | undefined {
665
815
 
666
816
  try {
667
817
  const { document } = parseHTML(html);
818
+ normalizeFragmentDocument(document);
819
+
820
+ if (isExplicitlyHidden(document.body)) return undefined;
668
821
 
669
822
  sections = [...document.querySelectorAll("noscript")].flatMap((block) => {
670
823
  const inner = block.innerHTML.trim();
@@ -717,8 +870,9 @@ async function extractNoscriptFallback(
717
870
  if (
718
871
  fallback.markdown.length < NOSCRIPT_FALLBACK_MIN_CHARACTERS ||
719
872
  fallback.markdown.length <= primary.markdown.length
720
- )
873
+ ) {
721
874
  return undefined;
875
+ }
722
876
 
723
877
  return {
724
878
  ...fallback,
@@ -739,33 +893,37 @@ async function extractNoscriptFallback(
739
893
  export async function extractHtmlToMarkdown(
740
894
  html: string,
741
895
  baseUrl: URL,
896
+ fragmentTab?: string,
742
897
  ): Promise<
743
- Awaited<ReturnType<typeof extractHtmlDocument>> & {
744
- surfaceView?: {
745
- selected: string;
746
- omitted: number;
747
- markdown: string;
748
- fragmentOffsets?: Record<string, number>;
749
- };
750
- }
898
+ Awaited<ReturnType<typeof extractHtmlDocument>> &
899
+ Pick<CompleteDocument, "surfaceView" | "fragmentTabs">
751
900
  > {
752
901
  assertConversionDepth(html);
753
902
  const primary = await extractHtmlDocument(html, baseUrl);
754
903
  const complete = (await extractNoscriptFallback(html, baseUrl, primary)) ?? primary;
755
904
 
756
905
  try {
757
- const surface = selectSurfaceHtml(html, baseUrl);
906
+ let surface = selectSurfaceHtml(html, baseUrl);
907
+ const tabs = surface ? undefined : fragmentTabPanes(html, baseUrl);
908
+ const pane = fragmentTab ? tabs?.get(fragmentTab) : undefined;
909
+
910
+ if (pane && fragmentTab) surface = materializeFragmentTab(fragmentTab, pane.pane, pane.omitted);
911
+ const view = surface ? await extractHtmlDocument(surface.html, baseUrl) : undefined;
758
912
 
759
- if (!surface) return complete;
760
- const view = await extractHtmlDocument(surface.html, baseUrl);
913
+ if (pane && fragmentTab && !view?.markdown.trim()) tabs?.delete(fragmentTab);
914
+ // Leave oversized inventories unknown rather than misclassifying a valid tab.
915
+ const fragmentTabs =
916
+ (tabs?.size ?? 0) <= MAX_CACHED_FRAGMENT_TABS ? [...(tabs?.keys() ?? [])] : undefined;
761
917
 
762
- if (!view.markdown.trim()) return complete;
918
+ if (!surface || !view?.markdown.trim()) return { ...complete, fragmentTabs };
763
919
 
764
920
  return {
765
921
  ...complete,
922
+ fragmentTabs,
766
923
  surfaceView: {
767
924
  selected: surface.selected,
768
925
  omitted: surface.omitted,
926
+ fragmentSelected: surface.fragmentSelected,
769
927
  markdown: view.markdown,
770
928
  fragmentOffsets: view.fragmentOffsets,
771
929
  },
@@ -31,13 +31,13 @@ interface SplitSections {
31
31
  }
32
32
 
33
33
  /** Target size of one section when a block has no headings and no blank lines. */
34
- const WINDOW_TARGET_CHARACTERS = 8_000;
34
+ const WINDOW_TARGET_CHARACTERS = 8000;
35
35
 
36
36
  /** Fewest lines a headingless block needs before it is split into windows. */
37
37
  const WINDOW_MIN_LINES = 80;
38
38
 
39
39
  /** Fewest characters a headingless block needs before it is split into windows. */
40
- const WINDOW_MIN_CHARACTERS = 6_000;
40
+ const WINDOW_MIN_CHARACTERS = 6000;
41
41
 
42
42
  const STOP_WORDS = new Set([
43
43
  "a",
@@ -60,8 +60,9 @@ function tokens(value: string): string[] {
60
60
  let word = token;
61
61
 
62
62
  if (word.length > 5 && /(?:ss|ch|sh|x|z)es$/.test(word)) word = word.slice(0, -2);
63
- else if (word.length > 4 && word.endsWith("s") && !word.endsWith("ss"))
63
+ else if (word.length > 4 && word.endsWith("s") && !word.endsWith("ss")) {
64
64
  word = word.slice(0, -1);
65
+ }
65
66
 
66
67
  if (word.length > 6 && word.endsWith("ion")) return word.slice(0, -3);
67
68
 
@@ -210,8 +211,13 @@ function splitSections(markdown: string): SplitSections {
210
211
 
211
212
  if (match) {
212
213
  if (!fence) fence = { marker: match[1][0], length: match[1].length };
213
- else if (match[1][0] === fence.marker && match[1].length >= fence.length && !match[2].trim())
214
+ else if (
215
+ match[1][0] === fence.marker &&
216
+ match[1].length >= fence.length &&
217
+ !match[2].trim()
218
+ ) {
214
219
  fence = undefined;
220
+ }
215
221
 
216
222
  return false;
217
223
  }
@@ -237,8 +243,9 @@ function splitSections(markdown: string): SplitSections {
237
243
  match[1][0] === fence.marker &&
238
244
  match[1].length >= fence.length &&
239
245
  !match[2].trim()
240
- )
246
+ ) {
241
247
  fence = undefined;
248
+ }
242
249
  }
243
250
 
244
251
  if (!fence && !line.trim()) {
@@ -287,8 +294,9 @@ function splitSections(markdown: string): SplitSections {
287
294
  // Split oversized sections at blank lines outside fences, so matches do not pull
288
295
  // in an entire chapter. Keep the heading with its first content block.
289
296
  const bounded = sections.flatMap((section, group) => {
290
- if (section.length <= WINDOW_MIN_CHARACTERS)
297
+ if (section.length <= WINDOW_MIN_CHARACTERS) {
291
298
  return [{ markdown: section, tokens: tokens(section) }];
299
+ }
292
300
  const chunks: string[] = [];
293
301
  let current: string[] = [];
294
302
  let size = 0;
@@ -303,8 +311,9 @@ function splitSections(markdown: string): SplitSections {
303
311
  match[1][0] === inFence.marker &&
304
312
  match[1].length >= inFence.length &&
305
313
  !match[2].trim()
306
- )
314
+ ) {
307
315
  inFence = undefined;
316
+ }
308
317
  }
309
318
 
310
319
  if (!inFence && line.length > WINDOW_TARGET_CHARACTERS / 2) {
@@ -334,8 +343,9 @@ function splitSections(markdown: string): SplitSections {
334
343
  return chunks.map((chunk, index) => {
335
344
  const result: Section = { markdown: chunk, tokens: tokens(chunk) };
336
345
 
337
- if (heading.length <= 500 && HEADING_PATTERN.test(heading))
346
+ if (heading.length <= 500 && HEADING_PATTERN.test(heading)) {
338
347
  result.context = { group, heading, continuation: index > 0 };
348
+ }
339
349
 
340
350
  return result;
341
351
  });
@@ -404,8 +414,11 @@ export function focusMarkdown(markdown: string, query: string): FocusResult {
404
414
  const scores = sections.map((section) => {
405
415
  if (literalIdentifier) return containsIdentifier(section.markdown, literalIdentifier) ? 1 : 0;
406
416
 
407
- if (embeddedIdentifiers.some((identifier) => !containsIdentifier(section.markdown, identifier)))
417
+ if (
418
+ embeddedIdentifiers.some((identifier) => !containsIdentifier(section.markdown, identifier))
419
+ ) {
408
420
  return 0;
421
+ }
409
422
  const frequencies = new Map<string, number>();
410
423
 
411
424
  for (const token of section.tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1);
@@ -24,11 +24,11 @@ function stripMarkupForFragmentSlug(value: string): string {
24
24
  function fragmentSlug(value: string): string {
25
25
  return stripMarkupForFragmentSlug(value)
26
26
  .normalize("NFKD")
27
- .replace(/[\u0300-\u036f]/g, "")
27
+ .replaceAll(/[\u0300-\u036f]/g, "")
28
28
  .toLowerCase()
29
- .replace(/[^\p{Letter}\p{Number} _-]/gu, "")
29
+ .replaceAll(/[^\p{Letter}\p{Number} _-]/gu, "")
30
30
  .trim()
31
- .replace(/[ _]+/g, "-");
31
+ .replaceAll(/[ _]+/g, "-");
32
32
  }
33
33
 
34
34
  /** Finds the extracted Markdown position corresponding to HTML fragment IDs. */
@@ -139,7 +139,7 @@ export function buildFragmentOffsets(
139
139
  // Section wrapper IDs often precede headings omitted by extraction. Fall
140
140
  // back to the first retained paragraph/list/code block inside the section.
141
141
  for (const descendant of element.querySelectorAll<HTMLElement>("p, li, pre, blockquote")) {
142
- const content = (descendant.textContent ?? "").replace(/\s+/g, " ").trim();
142
+ const content = (descendant.textContent ?? "").replaceAll(/\s+/g, " ").trim();
143
143
 
144
144
  if (content.length < 12) continue;
145
145
  normalizedMarkdown ??= normalizeMarkdown(markdown);
@@ -1,6 +1,6 @@
1
1
  import type { CompleteDocument } from "./content.ts";
2
2
 
3
- /** Removes a URL fragment before acquisition so fragment variants share cache entries. */
3
+ /** Removes the client-side fragment before network acquisition. */
4
4
  export function urlWithoutFragment(rawUrl: string): string {
5
5
  try {
6
6
  const url = new URL(rawUrl);
@@ -33,32 +33,48 @@ function sourceOffset(markdown: string, lineNumber: number, columnNumber = 1): n
33
33
  return offset + Math.min(columnNumber - 1, lines[lineNumber - 1].length);
34
34
  }
35
35
 
36
- /** Resolves heading and source-location URL fragments against a fetched document. */
37
- export function resolveFragmentOffset(
38
- document: CompleteDocument,
39
- rawUrl: string,
40
- ): ResolvedFragment {
41
- let fragment: string | undefined;
36
+ const SOURCE_LINE_ANCHOR = /^L(\d+)(?:C(\d+))?(?:-L?(\d+)(?:C(\d+))?)?$/i;
37
+
38
+ /** Reads a URL fragment, retaining malformed percent escapes as literal text. */
39
+ export function urlFragment(rawUrl: string): string | undefined {
40
+ let fragment: string;
42
41
 
43
42
  try {
44
- const hash = new URL(rawUrl).hash;
43
+ fragment = new URL(rawUrl).hash.slice(1);
44
+ } catch {
45
+ return undefined;
46
+ }
45
47
 
46
- if (hash) {
47
- const rawFragment = hash.slice(1);
48
+ if (!fragment) return undefined;
48
49
 
49
- try {
50
- fragment = decodeURIComponent(rawFragment);
51
- } catch {
52
- fragment = rawFragment;
53
- }
54
- }
50
+ try {
51
+ return decodeURIComponent(fragment);
55
52
  } catch {
56
- return {};
53
+ return fragment;
57
54
  }
55
+ }
56
+
57
+ /** A bounded potential HTML tab ID, not a source line/range. */
58
+ export function fragmentTabId(rawUrl: string): string | undefined {
59
+ const fragment = urlFragment(rawUrl);
60
+
61
+ return fragment && isFragmentTabId(fragment) ? fragment : undefined;
62
+ }
63
+
64
+ export function isFragmentTabId(fragment: string): boolean {
65
+ return /^[\w.:-]{1,80}$/u.test(fragment) && !SOURCE_LINE_ANCHOR.test(fragment);
66
+ }
67
+
68
+ /** Resolves heading and source-location URL fragments against a fetched document. */
69
+ export function resolveFragmentOffset(
70
+ document: CompleteDocument,
71
+ rawUrl: string,
72
+ ): ResolvedFragment {
73
+ const fragment = urlFragment(rawUrl);
58
74
 
59
75
  if (!fragment) return {};
60
76
 
61
- const lineAnchor = /^L(\d+)(?:C(\d+))?(?:-L?(\d+)(?:C(\d+))?)?$/i.exec(fragment);
77
+ const lineAnchor = SOURCE_LINE_ANCHOR.exec(fragment);
62
78
 
63
79
  if (lineAnchor) {
64
80
  const [, firstLine, firstColumn, lastLine, lastColumn] = lineAnchor;
@@ -19,7 +19,7 @@ function stripCompleteStyleElements(value: string): string {
19
19
  let cleaned = value;
20
20
 
21
21
  while (true) {
22
- const next = cleaned.replace(COMPLETE_STYLE_ELEMENT, "");
22
+ const next = cleaned.replaceAll(COMPLETE_STYLE_ELEMENT, "");
23
23
 
24
24
  if (next === cleaned) return cleaned;
25
25
  cleaned = next;
@@ -109,6 +109,6 @@ export function stripExtractedCssCruft(markdown: string): string {
109
109
 
110
110
  return output
111
111
  .join("\n")
112
- .replace(/\n{3,}/g, "\n\n")
112
+ .replaceAll(/\n{3,}/g, "\n\n")
113
113
  .trim();
114
114
  }