Skip to content

refactor: decompose monolithic modules + sliding-window crawler - #2

Merged
teng-lin merged 2 commits into
mainfrom
feature/refactor
Feb 8, 2026
Merged

teng-lin merged 2 commits into
mainfrom
feature/refactor

Conversation

@teng-lin

@teng-lin teng-lin commented Feb 8, 2026

Copy link
Copy Markdown
Owner

Summary

  • Decompose content-extractors.ts (1281 → ~400 lines) into 7 focused sub-modules: metadata, readability, selector, json-ld, next-data, text-density, and RSC extractors. Barrel re-exports preserve all existing import paths — zero test changes needed.
  • Decompose http-fetch.ts (1074 → ~700 lines) by extracting WP REST API logic into wp-rest-api.ts and Next.js data route logic into next-data-route.ts.
  • Replace crawler batch-wait (Promise.all) with sliding-window concurrency (Promise.race + Map<number, Promise>) for better throughput with non-uniform fetch times.
  • Promote RequestContext interface to shared fetch/types.ts.
  • Eliminate duplicate htmlToText by importing shared utility with || null semantic equivalence.
  • Extract attachRawHtml helper to reduce 7 repeated keepRawHtml patterns.

New files (9)

File Lines Purpose
src/extract/metadata-extractors.ts 78 Title, byline, excerpt, published time
src/extract/readability-extractor.ts 70 Mozilla Readability strategy
src/extract/selector-extractor.ts 86 CSS selector-based extraction
src/extract/json-ld-extractor.ts 177 JSON-LD / Schema.org extraction
src/extract/next-data-extractor.ts 419 Next.js __NEXT_DATA__ extraction
src/extract/text-density-extractor.ts 44 Text density heuristic
src/extract/rsc-extractor.ts 120 React Server Components extraction
src/fetch/wp-rest-api.ts 313 WP REST API fetch + parse
src/fetch/next-data-route.ts 76 Next.js /_next/data/ route fetch

Test plan

  • All 683 unit tests pass (zero test modifications)
  • npm run lint — 0 errors
  • npm run format:check — all files pass
  • npm run build — TypeScript strict mode compiles

🤖 Generated with Claude Code

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @teng-lin, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on significant refactoring efforts to improve the modularity, maintainability, and performance of the content extraction and HTTP fetching mechanisms. By decomposing large files into smaller, focused units and upgrading the crawler's concurrency model, the codebase becomes more organized and efficient. These changes aim to streamline development and enhance the system's ability to handle diverse web content more effectively.

Highlights

  • Module Decomposition: The monolithic content-extractors.ts file has been broken down into seven specialized sub-modules (metadata, readability, selector, json-ld, next-data, text-density, and RSC extractors) to enhance modularity and maintainability. Similarly, http-fetch.ts has been refactored by extracting WordPress REST API and Next.js data route logic into dedicated files (wp-rest-api.ts and next-data-route.ts).
  • Crawler Concurrency Model: The crawler's batch-wait mechanism (Promise.all) has been replaced with a more efficient sliding-window concurrency model using Promise.race and a Map to manage inflight requests. This change allows for immediate processing of completed requests, improving throughput, especially with non-uniform fetch times.
  • Shared Request Context: The RequestContext interface has been promoted to a shared fetch/types.ts file, making it more broadly accessible and standardized across fetching utilities.
  • Code Duplication Reduction: Duplicate htmlToText utility functions have been eliminated by importing a single shared version. Additionally, an attachRawHtml helper has been extracted to reduce repetitive patterns for attaching raw HTML to fetch results.
Changelog
  • src/crawl/crawler.ts
    • Removed the collectBatch utility function.
    • Replaced the Promise.all based batch processing with a sliding-window concurrency model using Promise.race and a Map to manage inflight requests, allowing for dynamic slot freeing upon request completion.
  • src/extract/content-extractors.ts
    • Decomposed into seven new sub-modules, moving specific extraction strategies and related helpers to their own files.
    • Removed direct imports of Readability, @wrtnlabs/web-content-extractor, and various metadata/selector constants.
    • Added barrel re-exports for all public symbols from the new sub-modules to maintain existing import paths and minimize breaking changes.
    • Updated composeMetadata to use the new JsonLdMetadata type from json-ld-extractor.ts.
    • Removed numerous functions and constants whose logic has been relocated to dedicated extraction files.
  • src/extract/json-ld-extractor.ts
    • Added new file containing logic for JSON-LD structured data extraction, including functions for author extraction, flattening JSON-LD items, article type detection, parsing JSON-LD items, and script parsing.
    • Includes tryJsonLdExtraction, extractJsonLdMetadata, and detectIsAccessibleForFree.
  • src/extract/metadata-extractors.ts
    • Added new file containing helper functions for extracting common metadata such as extractPublishedTime, extractTitle, extractSiteName, and generateExcerpt.
  • src/extract/next-data-extractor.ts
    • Added new file containing logic for extracting content from Next.js __NEXT_DATA__ script tags.
    • Includes functions for extracting text from HTML, extracting bylines from author arrays, handling content blocks, and the main tryNextDataExtraction and extractNextBuildId functions.
  • src/extract/readability-extractor.ts
    • Added new file containing the tryReadability function for content extraction using Mozilla Readability.
  • src/extract/rsc-extractor.ts
    • Added new file containing logic for extracting content from React Server Components (RSC) streaming payloads.
    • Includes isNaturalLanguage and tryNextRscExtraction functions.
  • src/extract/selector-extractor.ts
    • Added new file containing the trySelectorExtraction function for CSS selector-based content extraction, along with CONTENT_SELECTORS and REMOVE_SELECTORS.
  • src/extract/text-density-extractor.ts
    • Added new file containing the tryTextDensityExtraction function for content extraction using text density analysis.
  • src/fetch/http-fetch.ts
    • Removed imports and calls related to WordPress REST API and Next.js data route logic, which are now handled by dedicated modules.
    • Removed the RequestContext interface definition, now located in src/fetch/types.ts.
    • Removed the htmlToText import, now using a shared utility from ../extract/utils.js.
    • Removed numerous functions related to WordPress REST API and Next.js data route handling, as their logic has been moved.
    • Updated tryNextDataRoute to utilize the new fetchNextDataRoute helper.
    • Introduced a new attachRawHtml helper function to centralize logic for attaching raw HTML to results when recording is enabled, reducing code repetition.
    • Updated calls to various fallback functions (tryNextDataFallback, tryWpRestApiFallback, tryPrismContentApiFallback, tryWpAjaxContentFallback) to use the new attachRawHtml helper.
  • src/fetch/next-data-route.ts
    • Added new file containing buildNextDataRouteUrl and fetchNextDataRoute for handling Next.js data route fetching and extraction.
  • src/fetch/types.ts
    • Moved the RequestContext interface definition from src/fetch/http-fetch.ts to this shared types file, promoting better organization.
  • src/fetch/wp-rest-api.ts
    • Added new file containing logic for WordPress REST API interactions.
    • Includes functions like detectPmcListOrder, fetchPmcListItems, resolveWpField, resolveWpPost, hasWpApiTruncationMarker, tryWpRestApiExtraction, enrichWpMetadata, extractSlugFromUrl, and resolveWpApiUrl.
Activity
  • The pull request was created by teng-lin.
  • All 683 unit tests passed without requiring any modifications.
  • npm run lint reported 0 errors, indicating adherence to code style and quality standards.
  • npm run format:check confirmed that all files passed formatting checks.
  • npm run build successfully compiled the project in TypeScript strict mode.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly refactors the project by decomposing monolithic content-extractors.ts and http-fetch.ts modules into smaller, more maintainable sub-modules, and optimizes crawling throughput with a new sliding-window implementation using Promise.race. However, a critical Cross-Site Scripting (XSS) vulnerability was identified in the new json-ld-extractor.ts due to a lack of sanitization and improper handling of HTML tags in the textContent field; this strategy needs to be updated to match existing robust extraction methods. Furthermore, a high-severity suggestion has been made to enhance the new crawler logic with robust error handling, including logging non-critical failures at a debug level for traceability, to prevent potential crashes.

Comment thread src/extract/json-ld-extractor.ts Outdated
Comment on lines +67 to +77
(item.articleBody as string) ?? (item.text as string) ?? (item.description as string);
if (!content) return null;

return {
title: (item.headline as string) ?? (item.name as string) ?? null,
byline: extractAuthorFromJsonLd(item.author),
content,
textContent: content,
excerpt: (item.description as string) ?? null,
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The json-ld extraction strategy extracts article content from application/ld+json script tags but fails to sanitize the extracted HTML or properly extract plain text for the textContent field.

While other strategies like next-data explicitly check for HTML and apply sanitizeHtml and extractTextFromHtml, the json-ld strategy returns the raw string from the JSON-LD articleBody, text, or description fields for both content and textContent.

Furthermore, json-ld is included in SKIP_CLEANUP_METHODS in src/extract/content-extractors.ts, meaning it bypasses the cleanExtractedHtml step. If an attacker-controlled page provides malicious HTML within a JSON-LD script, this tool will return that unsanitized HTML in the content field. If a consumer of this library renders this content as HTML, it leads to a Cross-Site Scripting (XSS) vulnerability. Additionally, the textContent field will contain raw HTML tags instead of plain text, which may break downstream logic expecting plain text.

Recommended remediation: Check if the extracted content contains HTML, and if so, apply sanitizeHtml to the content field and use htmlToText (or extractTextFromHtml) for the textContent field.

References
  1. Sanitize HTML content constructed from external API responses to prevent XSS by removing dangerous tags such as <script>, <style>, and <iframe>.

@teng-lin

teng-lin commented Feb 8, 2026

Copy link
Copy Markdown
Owner Author

Re: JSON-LD XSS concern (gemini-code-assist)

This is pre-existing behavior on main, not introduced by this refactor PR. The parseJsonLdItem function and SKIP_CLEANUP_METHODS exclusion for json-ld are unchanged — the code was simply moved from content-extractors.ts to json-ld-extractor.ts.

That said, the observation is valid as a pre-existing concern. JSON-LD articleBody fields from publisher-embedded structured data can contain HTML. In practice, this data comes from the page's own <script type="application/ld+json"> tags (same-origin), so the XSS risk is limited to cases where the page itself is already compromised. However, sanitizing the content would be a good defensive improvement — tracked as a follow-up.

@gemini-code-assist

Copy link
Copy Markdown

Thanks for the clarification, @teng-lin! I understand that the JSON-LD XSS concern is pre-existing and not introduced by this refactor. It's great to hear that you're tracking it as a follow-up for sanitization. Appreciate the diligence!

- Decompose content-extractors.ts (1281 → ~400 lines) into 7 focused
  sub-modules: metadata, readability, selector, json-ld, next-data,
  text-density, and RSC extractors. Barrel re-exports preserve all
  existing import paths.
- Decompose http-fetch.ts (1074 → ~700 lines) by extracting WP REST API
  logic into wp-rest-api.ts and Next.js data route logic into
  next-data-route.ts.
- Replace crawler batch-wait (Promise.all) with sliding-window
  concurrency (Promise.race + Map) for better throughput with
  non-uniform fetch times.
- Promote RequestContext interface to shared fetch/types.ts.
- Eliminate duplicate htmlToText by importing shared utility.
- Extract attachRawHtml helper to reduce repeated keepRawHtml patterns.

All 683 tests pass unchanged — no test modifications needed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
JSON-LD articleBody/text fields can contain raw HTML with script tags,
event handlers, and dangerous URI schemes. Apply sanitizeHtml to strip
dangerous elements and htmlToText to produce clean textContent, matching
the pattern used by next-data-extractor.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@teng-lin
teng-lin merged commit c65fbee into main Feb 8, 2026
5 checks passed
@teng-lin
teng-lin deleted the feature/refactor branch February 8, 2026 18:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant