searchfetch 3.3.4 → 4.1.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/README.md +147 -120
- package/package.json +32 -28
- package/src/browser.js +213 -0
- package/src/compose.js +126 -0
- package/src/extract.js +233 -0
- package/src/index.js +45 -0
- package/src/markdown.js +50 -0
- package/src/server.js +174 -0
- package/src/templates.js +273 -0
- package/templates/crates-package.json +1 -1
- package/templates/devto.json +1 -1
- package/templates/docker-hub.json +1 -1
- package/templates/docs-page.json +1 -1
- package/templates/docs-rs.json +1 -1
- package/templates/duckduckgo-lite-search.json +49 -0
- package/templates/duckduckgo-search.json +3 -1
- package/templates/github-issue.json +1 -1
- package/templates/github-repo.json +1 -1
- package/templates/gitlab.json +1 -1
- package/templates/go-pkg.json +1 -1
- package/templates/google-search.json +3 -1
- package/templates/javadoc.json +1 -1
- package/templates/mdn-web-docs.json +1 -1
- package/templates/npm-package.json +1 -1
- package/templates/pypi-package.json +1 -1
- package/templates/raw.json +1 -1
- package/templates/reddit.json +1 -1
- package/templates/wikipedia.json +1 -1
- package/templates/youtube.json +1 -1
- package/index.js +0 -1276
- package/lib/output.js +0 -9
- package/lib/selectors.js +0 -27
- package/templates/__init__.py +0 -1
package/README.md
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
|
-
# SearchFetch
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- **Browser rendering:** CloakBrowser runs Chromium
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
- **
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
# SearchFetch
|
|
2
|
+
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server that gives AI agents web search and page
|
|
4
|
+
fetching through a stealth browser. Pages are rendered with JavaScript, stripped of noise, and
|
|
5
|
+
returned as compact Markdown.
|
|
6
|
+
|
|
7
|
+
- **Browser rendering:** [CloakBrowser](https://github.com/CloakHQ/CloakBrowser) runs Chromium
|
|
8
|
+
with humanized input. Each fetch uses an isolated browser context. Sites may still demand
|
|
9
|
+
logins or challenges.
|
|
10
|
+
- **Fault tolerance:** relaunches a disconnected browser and retries timeouts, network failures
|
|
11
|
+
and HTTP 429 (honoring `Retry-After`, capped at 30 s) once. Built-in search engines fall back
|
|
12
|
+
to DuckDuckGo HTML and then DuckDuckGo Lite.
|
|
13
|
+
- **Token-efficient output:** scripts, styles, SVGs, inline styles and embedded `data:` images
|
|
14
|
+
are removed before conversion; images, media and fonts are blocked at the network layer.
|
|
15
|
+
- **Template-driven extraction:** JSON templates for GitHub, GitLab, npm, PyPI, crates.io,
|
|
16
|
+
docs.rs, Docker Hub, Wikipedia, MDN, Reddit, YouTube, DEV, pkg.go.dev, Javadoc and generic
|
|
17
|
+
documentation sites. Custom templates can be passed inline.
|
|
18
|
+
- **Two runtimes:** Python (`uvx`, Python 3.11.5+) or Node.js (`npx`, Node 24+), with the same
|
|
19
|
+
tools, templates and output. The first run downloads the browser binary.
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
No manual install is needed. Point your MCP client at `uvx` or `npx`:
|
|
22
24
|
|
|
23
25
|
```json
|
|
24
26
|
{
|
|
@@ -31,112 +33,137 @@ You do not need to install this repository manually. Configure your agent to use
|
|
|
31
33
|
}
|
|
32
34
|
```
|
|
33
35
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
|
63
|
-
|
|
|
64
|
-
| `
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
`
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
36
|
+
For Node.js, use `"command": "npx", "args": ["-y", "searchfetch"]`. In Cursor, add a `command`
|
|
37
|
+
server with `uvx searchfetch` or `npx -y searchfetch`.
|
|
38
|
+
|
|
39
|
+
## Tools
|
|
40
|
+
|
|
41
|
+
Both tools are read-only. Failures are returned as MCP tool errors.
|
|
42
|
+
|
|
43
|
+
### `websearch`
|
|
44
|
+
|
|
45
|
+
| Parameter | Type | Default | Description |
|
|
46
|
+
| ------------- | ------------ | -------------- | --------------------------------------------------------------------------------- |
|
|
47
|
+
| `query` | string | _required_ | Search query (must not be blank). |
|
|
48
|
+
| `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, a search template name, or an inline JSON template. |
|
|
49
|
+
| `region` | string/null | `null` | Region-language code such as `"us-en"`. DuckDuckGo: `kl`; Google: `gl` and `hl`. |
|
|
50
|
+
| `safe_search` | boolean/null | `null` | `true` or `false` sets the engine's safe search; `null` keeps the engine default. |
|
|
51
|
+
| `max_results` | integer | `10` | Maximum results (positive). |
|
|
52
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
53
|
+
|
|
54
|
+
Results are a numbered list of titles, URLs and snippets. When an engine fails or returns no
|
|
55
|
+
results, the next template in its `fallback` chain is tried (`google` → `duckduckgo-search` →
|
|
56
|
+
`duckduckgo-lite-search`), and a `[websearch: …]` note at the top of the output explains why.
|
|
57
|
+
|
|
58
|
+
### `webfetch`
|
|
59
|
+
|
|
60
|
+
| Parameter | Type | Default | Description |
|
|
61
|
+
| ------------- | ------- | ---------- | ------------------------------------------------------------------- |
|
|
62
|
+
| `url` | string | _required_ | Absolute `http`/`https` URL. |
|
|
63
|
+
| `template` | string | `"auto"` | `"auto"` (detect by URL), a template name, or inline JSON template. |
|
|
64
|
+
| `start_index` | integer | `0` | Start offset in Unicode code points (non-negative). |
|
|
65
|
+
| `max_length` | integer | `10000` | Maximum code points to return (positive). |
|
|
66
|
+
| `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
|
|
67
|
+
|
|
68
|
+
Output ends with a footer naming the template and the character window, plus the next
|
|
69
|
+
`start_index` when more content remains. Pages that match no template are converted whole after
|
|
70
|
+
removing navigation, headers, footers, sidebars, dialogs and media (`template="auto (fallback)"`).
|
|
71
|
+
The `raw` template converts the full `<body>` with no removal.
|
|
72
|
+
|
|
73
|
+
## Templates
|
|
74
|
+
|
|
75
|
+
Built-in templates live in [`templates/`](templates/) and are shared by both runtimes. Page
|
|
76
|
+
templates: `github-repo`, `github-issue`, `npm-package`, `pypi-package`, `crates-package`,
|
|
77
|
+
`docs-rs`, `javadoc`, `docs-page`, `docker-hub`, `wikipedia`, `gitlab`, `reddit`,
|
|
78
|
+
`mdn-web-docs`, `devto`, `go-pkg`, `youtube`, `raw`. Search templates: `google-search`,
|
|
79
|
+
`duckduckgo-search`, `duckduckgo-lite-search`.
|
|
80
|
+
|
|
81
|
+
Templates are validated when they are loaded or passed inline:
|
|
82
|
+
|
|
83
|
+
| Field | Description |
|
|
84
|
+
| ----------------- | ------------------------------------------------------------------------------------------------ |
|
|
85
|
+
| `name` | Required unique name (inline templates default to `"custom"`). |
|
|
86
|
+
| `sections` | Required list of sections (see below). |
|
|
87
|
+
| `order` | Precedence for `auto` detection; lower wins. |
|
|
88
|
+
| `url_patterns` | Regular expressions (compatible with JavaScript and Python) that select the template for `auto`. |
|
|
89
|
+
| `remove` | CSS selectors removed before extraction. Defaults to scripts, styles, SVG, nav, footer, iframes. |
|
|
90
|
+
| `source_url` | Raw Markdown source tried first, e.g. `"{url}.md"`; HTML responses are ignored. |
|
|
91
|
+
| `cookies` | Playwright cookies added to the browser context. |
|
|
92
|
+
| `block_resources` | Resource types blocked when `block_media` is on. Default: `image`, `media`, `font`. |
|
|
93
|
+
| `url_template` | Search URL with `{placeholders}`; makes the template usable by `websearch`. |
|
|
94
|
+
| `url_params` | Per placeholder: `required`, `default`, and `encode: "url"`. |
|
|
95
|
+
| `engine` | `"duckduckgo"` or `"google"`: how `region` and `safe_search` map to URL parameters. |
|
|
96
|
+
| `fallback` | Name of the search template to try when this one fails. |
|
|
97
|
+
|
|
98
|
+
Each section has a `name`, a `selector` (empty selects `<body>`), and optionally `format` (`text`, `markdown`,
|
|
99
|
+
`attribute` with `attribute`, or `html`), `transform` (one or a list of `strip`,
|
|
100
|
+
`decode_google_url`, `decode_ddg_url`, `json_parse`, `resolve_href`), `required`, `multiple`,
|
|
101
|
+
`max_items`, and `children` (fields extracted from inside each matched element).
|
|
102
|
+
|
|
103
|
+
Selectors separated by top-level commas are ordered fallbacks: the first selector that matches
|
|
104
|
+
wins, and an empty fallback selects the current element. Children search inside their parent
|
|
105
|
+
element and its ancestors, never neighbouring results, so a missing field stays missing. Missing
|
|
106
|
+
`required` sections or fields are reported as errors.
|
|
107
|
+
|
|
108
|
+
A records section whose first item has `Author`/`User` and `Comment`/`Body` fields is rendered as
|
|
109
|
+
a comment thread; other records render as indented `Key: value` blocks.
|
|
110
|
+
|
|
111
|
+
## Development
|
|
97
112
|
|
|
98
113
|
```bash
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
#
|
|
104
|
-
npm
|
|
105
|
-
npm run
|
|
106
|
-
npm run
|
|
107
|
-
|
|
108
|
-
# Lint
|
|
109
|
-
npm run lint # runs all linters
|
|
110
|
-
npm run lint:js # ESLint
|
|
111
|
-
npm run lint:py # Ruff
|
|
112
|
-
|
|
113
|
-
# Format
|
|
114
|
-
npm run format # auto-format all source files
|
|
115
|
-
npm run format:check # check formatting without changes
|
|
116
|
-
|
|
117
|
-
# MCP inspector (for manual testing)
|
|
118
|
-
npm run inspector-js # test with MCP Inspector (Node.js)
|
|
119
|
-
npm run inspector-py # test with MCP Inspector (Python)
|
|
114
|
+
npm ci && uv sync --locked --extra dev
|
|
115
|
+
git config core.hooksPath .githooks # optional: format, lint and unit tests before commits
|
|
116
|
+
|
|
117
|
+
npm test # Node (node:test) and Python (pytest) unit tests
|
|
118
|
+
npm run lint # ESLint and Ruff
|
|
119
|
+
npm run format # Prettier and Ruff format (format:check to verify)
|
|
120
|
+
npm run e2e # real browser against local fixtures, plus the packed npm and wheel builds
|
|
121
|
+
npm run check # everything CI runs
|
|
122
|
+
npm run inspect:node # MCP Inspector (inspect:py for Python)
|
|
120
123
|
```
|
|
121
124
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
## Architecture
|
|
125
|
+
### Layout
|
|
125
126
|
|
|
126
|
-
|
|
127
|
+
| Path | Contents |
|
|
128
|
+
| ---------------------------- | ------------------------------------------------------------------------- |
|
|
129
|
+
| `src/` | Node.js runtime (`index.js` is the `searchfetch` executable). |
|
|
130
|
+
| `searchfetch/` | Python package (`python -m searchfetch` or the `searchfetch` script). |
|
|
131
|
+
| `templates/` | Shared templates; bundled into the npm package and the Python wheel. |
|
|
132
|
+
| `tests/fixtures/` | Shared fixtures that keep both runtimes' extraction and output identical. |
|
|
133
|
+
| `tests/node`, `tests/python` | Unit tests. |
|
|
134
|
+
| `tests/e2e/` | MCP end-to-end tests over stdio against a local HTTP server. |
|
|
127
135
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
4. Remove configured elements, extract section fields, apply transforms, and compose Markdown. Page templates may first try a raw Markdown source URL.
|
|
132
|
-
5. Paginate page output using Unicode code points. Search requests can fall back from Google to DuckDuckGo HTML and then Lite; output names any fallback engine.
|
|
136
|
+
The runtimes mirror each other module for module (`templates`, `extract`, `markdown`, `compose`,
|
|
137
|
+
`browser`, `server`). Any change to one should be made to the other, with a shared fixture if
|
|
138
|
+
the behavior is observable.
|
|
133
139
|
|
|
134
|
-
|
|
140
|
+
### Releasing
|
|
135
141
|
|
|
136
|
-
|
|
142
|
+
Bump `version` in both `package.json` and `pyproject.toml` (then `npm install` and `uv lock`),
|
|
143
|
+
commit, and push a matching tag:
|
|
137
144
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
145
|
+
```sh
|
|
146
|
+
git tag -a v4.1.1 -m "v4.1.1" && git push origin main v4.1.1
|
|
147
|
+
```
|
|
141
148
|
|
|
142
|
-
|
|
149
|
+
The Publish workflow checks that the tag matches both versions, runs lint and unit tests, stages
|
|
150
|
+
the npm release, publishes to PyPI, and then creates the GitHub Release with generated notes. To
|
|
151
|
+
retry a tag, run the workflow manually from the Actions tab with that tag.
|
|
152
|
+
|
|
153
|
+
Both registries use trusted publishing (OIDC), so no tokens are stored in the repository. The npm
|
|
154
|
+
trusted publisher (`maxylev/searchfetch`, workflow `publish.yml`) allows staged publishing only:
|
|
155
|
+
CI runs `npm stage publish` with automatic provenance, and the version goes live after a
|
|
156
|
+
maintainer approves it with 2FA on npmjs.com or with `npm stage list searchfetch` and
|
|
157
|
+
`npm stage approve <stage-id>`. PyPI publishes from the `pypi` environment.
|
|
158
|
+
|
|
159
|
+
### Limits
|
|
160
|
+
|
|
161
|
+
- HTML-to-Markdown conversion uses turndown (Node) and markdownify (Python). They agree on
|
|
162
|
+
common content, but edge cases such as tables differ.
|
|
163
|
+
- After the DOM is ready, each fetch waits up to five seconds for network activity to settle.
|
|
164
|
+
Pages that keep rendering after that may return partial content.
|
|
165
|
+
- CloakBrowser is held at 0.6.x in both runtimes: 0.7 requires a license key (free with email,
|
|
166
|
+
one concurrent session) on every launch and fails without a terminal unless
|
|
167
|
+
`CLOAKBROWSER_LICENSE_KEY` is set, which would break zero-config `uvx`/`npx` use.
|
|
168
|
+
- E2E tests use local fixtures. Live search-engine availability and third-party page layouts
|
|
169
|
+
change over time and need separate live checks.
|
package/package.json
CHANGED
|
@@ -1,50 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "searchfetch",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Fault-tolerant MCP
|
|
3
|
+
"version": "4.1.0",
|
|
4
|
+
"description": "Fault-tolerant MCP server for stealth web search and page fetching",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Max",
|
|
5
7
|
"type": "module",
|
|
6
8
|
"bin": {
|
|
7
|
-
"searchfetch": "index.js"
|
|
9
|
+
"searchfetch": "src/index.js"
|
|
8
10
|
},
|
|
9
11
|
"files": [
|
|
10
|
-
"
|
|
11
|
-
"templates/"
|
|
12
|
-
"lib/"
|
|
12
|
+
"src/",
|
|
13
|
+
"templates/"
|
|
13
14
|
],
|
|
14
|
-
"publishConfig": {
|
|
15
|
-
"access": "public"
|
|
16
|
-
},
|
|
17
15
|
"repository": {
|
|
18
16
|
"type": "git",
|
|
19
17
|
"url": "git+https://github.com/maxylev/searchfetch.git"
|
|
20
18
|
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
21
22
|
"scripts": {
|
|
22
|
-
"start": "node
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"test": "npm run test:
|
|
26
|
-
"test:
|
|
27
|
-
"test:py": "uv run --locked --extra dev pytest
|
|
28
|
-
"lint": "npm run lint:
|
|
29
|
-
"lint:
|
|
23
|
+
"start": "node src/index.js",
|
|
24
|
+
"inspect:node": "npx @modelcontextprotocol/inspector node src/index.js",
|
|
25
|
+
"inspect:py": "npx @modelcontextprotocol/inspector uv run searchfetch",
|
|
26
|
+
"test": "npm run test:node && npm run test:py",
|
|
27
|
+
"test:node": "node --test \"tests/node/*.test.js\"",
|
|
28
|
+
"test:py": "uv run --locked --extra dev pytest",
|
|
29
|
+
"lint": "npm run lint:node && npm run lint:py",
|
|
30
|
+
"lint:node": "eslint . --max-warnings=0",
|
|
30
31
|
"lint:py": "uv run --locked --extra dev ruff check .",
|
|
31
|
-
"format": "prettier --write
|
|
32
|
-
"format:check": "prettier --check
|
|
32
|
+
"format": "prettier --write . && uv run --locked --extra dev ruff format .",
|
|
33
|
+
"format:check": "prettier --check . && uv run --locked --extra dev ruff format --check .",
|
|
33
34
|
"e2e": "npm run e2e:node && npm run e2e:py",
|
|
34
|
-
"e2e:node": "node
|
|
35
|
-
"e2e:py": "uv run python
|
|
35
|
+
"e2e:node": "node tests/e2e/node.mjs",
|
|
36
|
+
"e2e:py": "uv run --locked python tests/e2e/python.py",
|
|
37
|
+
"check": "scripts/ci-check.sh"
|
|
36
38
|
},
|
|
37
39
|
"dependencies": {
|
|
38
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
40
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
39
41
|
"cheerio": "^1.2.0",
|
|
40
|
-
"cloakbrowser": "^0.5
|
|
41
|
-
"playwright-core": "^1.
|
|
42
|
-
"turndown": "^7.2.
|
|
43
|
-
"zod": "^4.6.
|
|
42
|
+
"cloakbrowser": "^0.6.5",
|
|
43
|
+
"playwright-core": "^1.65.1",
|
|
44
|
+
"turndown": "^7.2.5",
|
|
45
|
+
"zod": "^4.6.7"
|
|
44
46
|
},
|
|
45
47
|
"devDependencies": {
|
|
46
|
-
"eslint": "^10.
|
|
47
|
-
"
|
|
48
|
+
"@eslint/js": "^10.0.1",
|
|
49
|
+
"eslint": "^10.16.0",
|
|
50
|
+
"globals": "^17.14.0",
|
|
51
|
+
"prettier": "^3.10.1"
|
|
48
52
|
},
|
|
49
53
|
"engines": {
|
|
50
54
|
"node": ">=24.0.0"
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared stealth browser and page fetching.
|
|
3
|
+
*
|
|
4
|
+
* One CloakBrowser instance is reused; every fetch attempt gets an isolated context so cookies
|
|
5
|
+
* and storage never leak between requests. Mirrors `searchfetch/browser.py`.
|
|
6
|
+
*/
|
|
7
|
+
import * as cheerio from "cheerio";
|
|
8
|
+
import { launch } from "cloakbrowser";
|
|
9
|
+
import { cleanSourceMarkdown, isMarkdown } from "./markdown.js";
|
|
10
|
+
import { validateUrl } from "./templates.js";
|
|
11
|
+
|
|
12
|
+
export const NAVIGATION_TIMEOUT_MS = 15_000;
|
|
13
|
+
export const SOURCE_TIMEOUT_MS = 10_000;
|
|
14
|
+
export const NETWORK_IDLE_TIMEOUT_MS = 5_000;
|
|
15
|
+
export const MAX_ATTEMPTS = 2;
|
|
16
|
+
export const RATE_LIMIT_DELAY_MS = 2_000;
|
|
17
|
+
export const MAX_RATE_LIMIT_DELAY_MS = 30_000;
|
|
18
|
+
export const NETWORK_RETRY_DELAY_MS = 500;
|
|
19
|
+
export const DEFAULT_BLOCKED_RESOURCES = ["image", "media", "font"];
|
|
20
|
+
|
|
21
|
+
const LAUNCH_ARGS = ["--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage"];
|
|
22
|
+
|
|
23
|
+
export class BrowserManager {
|
|
24
|
+
#browser = null;
|
|
25
|
+
#launching = null;
|
|
26
|
+
#launcher;
|
|
27
|
+
|
|
28
|
+
/** `launcher` is injectable so tests can avoid starting a real browser. */
|
|
29
|
+
constructor(launcher = launch) {
|
|
30
|
+
this.#launcher = launcher;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Return the connected browser, launching (once, even under concurrency) when needed. */
|
|
34
|
+
async get() {
|
|
35
|
+
if (this.#browser?.isConnected()) return this.#browser;
|
|
36
|
+
this.#launching ??= this.#launcher({ headless: true, humanize: true, args: LAUNCH_ARGS })
|
|
37
|
+
.then((browser) => {
|
|
38
|
+
this.#browser = browser;
|
|
39
|
+
browser.on("disconnected", () => {
|
|
40
|
+
if (this.#browser === browser) this.#browser = null;
|
|
41
|
+
});
|
|
42
|
+
return browser;
|
|
43
|
+
})
|
|
44
|
+
.finally(() => {
|
|
45
|
+
this.#launching = null;
|
|
46
|
+
});
|
|
47
|
+
return this.#launching;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Close the browser, waiting for an in-flight launch so it cannot outlive shutdown. */
|
|
51
|
+
async close() {
|
|
52
|
+
const browser = await (this.#launching ?? this.#browser);
|
|
53
|
+
this.#browser = null;
|
|
54
|
+
await browser?.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class HttpStatusError extends Error {
|
|
59
|
+
constructor(status, url, retryAfterMs = null) {
|
|
60
|
+
super(`HTTP ${status} when fetching ${url}`);
|
|
61
|
+
this.name = "HttpStatusError";
|
|
62
|
+
this.status = status;
|
|
63
|
+
this.retryAfterMs = retryAfterMs;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Parse a Retry-After header (seconds or HTTP date) into a capped delay in milliseconds. */
|
|
68
|
+
export function parseRetryAfterMs(value, now = Date.now()) {
|
|
69
|
+
if (!value) return RATE_LIMIT_DELAY_MS;
|
|
70
|
+
const seconds = Number(value);
|
|
71
|
+
const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now;
|
|
72
|
+
if (!Number.isFinite(delay)) return RATE_LIMIT_DELAY_MS;
|
|
73
|
+
return Math.min(Math.max(delay, 0), MAX_RATE_LIMIT_DELAY_MS);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const DENIED_TITLES = [
|
|
77
|
+
"access denied",
|
|
78
|
+
"are you a human",
|
|
79
|
+
"are you a robot",
|
|
80
|
+
"ddos protection",
|
|
81
|
+
"forbidden",
|
|
82
|
+
"one more step",
|
|
83
|
+
"security check",
|
|
84
|
+
"sorry, you have been blocked",
|
|
85
|
+
"unusual traffic",
|
|
86
|
+
"verify you are human",
|
|
87
|
+
];
|
|
88
|
+
const DENIED_BODY = [
|
|
89
|
+
"bots use duckduckgo too",
|
|
90
|
+
"our systems have detected unusual traffic",
|
|
91
|
+
"sorry, you have been blocked",
|
|
92
|
+
"to continue, please type the characters",
|
|
93
|
+
];
|
|
94
|
+
/** Only conclusive on short pages; long articles may legitimately mention these phrases. */
|
|
95
|
+
const DENIED_SHORT_BODY = ["access denied", "are you a robot", "verify you are human"];
|
|
96
|
+
const SHORT_BODY_LENGTH = 1200;
|
|
97
|
+
|
|
98
|
+
/** Heuristically detect CAPTCHA, bot-check and block pages. */
|
|
99
|
+
export function isAccessDenied($) {
|
|
100
|
+
const title = $("title").text().toLowerCase();
|
|
101
|
+
const body = $("body").text().replace(/\s+/g, " ").trim().toLowerCase();
|
|
102
|
+
return (
|
|
103
|
+
DENIED_TITLES.some((phrase) => title.includes(phrase)) ||
|
|
104
|
+
DENIED_BODY.some((phrase) => body.includes(phrase)) ||
|
|
105
|
+
(body.length < SHORT_BODY_LENGTH && DENIED_SHORT_BODY.some((phrase) => body.includes(phrase)))
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const TRANSIENT_ERROR =
|
|
110
|
+
/net::|ERR_|navigation|navigating|connection|target closed|browser has been closed/i;
|
|
111
|
+
|
|
112
|
+
/** Rate limits, timeouts and network/browser failures are worth one more attempt. */
|
|
113
|
+
export function retryDelayMs(err) {
|
|
114
|
+
if (err instanceof HttpStatusError) {
|
|
115
|
+
return err.status === 429 ? (err.retryAfterMs ?? RATE_LIMIT_DELAY_MS) : null;
|
|
116
|
+
}
|
|
117
|
+
if (err?.name === "TimeoutError" || TRANSIENT_ERROR.test(err?.message ?? "")) {
|
|
118
|
+
return NETWORK_RETRY_DELAY_MS;
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
124
|
+
|
|
125
|
+
/** Open a page in a fresh context with template cookies and resource blocking applied. */
|
|
126
|
+
async function openPage(browser, template, blockMedia) {
|
|
127
|
+
const context = await browser.newContext();
|
|
128
|
+
try {
|
|
129
|
+
if (template?.cookies?.length) await context.addCookies(template.cookies);
|
|
130
|
+
const page = await context.newPage();
|
|
131
|
+
const blocked = new Set(template?.block_resources ?? DEFAULT_BLOCKED_RESOURCES);
|
|
132
|
+
if (blockMedia && blocked.size > 0) {
|
|
133
|
+
await page.route("**/*", (route) =>
|
|
134
|
+
blocked.has(route.request().resourceType()) ? route.abort() : route.continue(),
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
return { context, page };
|
|
138
|
+
} catch (err) {
|
|
139
|
+
await context.close();
|
|
140
|
+
throw err;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function fetchHtmlOnce(browserManager, url, template, blockMedia) {
|
|
145
|
+
const { context, page } = await openPage(await browserManager.get(), template, blockMedia);
|
|
146
|
+
try {
|
|
147
|
+
// Check the status before waiting for rendering so a slow page cannot hide an HTTP error.
|
|
148
|
+
const response = await page.goto(url, {
|
|
149
|
+
waitUntil: "domcontentloaded",
|
|
150
|
+
timeout: NAVIGATION_TIMEOUT_MS,
|
|
151
|
+
});
|
|
152
|
+
const status = response?.status() ?? 0;
|
|
153
|
+
if (status >= 400) {
|
|
154
|
+
const retryAfter =
|
|
155
|
+
status === 429 ? parseRetryAfterMs(response.headers()["retry-after"]) : null;
|
|
156
|
+
throw new HttpStatusError(status, url, retryAfter);
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
await page.waitForLoadState("networkidle", { timeout: NETWORK_IDLE_TIMEOUT_MS });
|
|
160
|
+
} catch (err) {
|
|
161
|
+
// Long polling must not prevent extraction of an already loaded document.
|
|
162
|
+
if (err.name !== "TimeoutError") throw err;
|
|
163
|
+
}
|
|
164
|
+
const html = await page.content();
|
|
165
|
+
if (isAccessDenied(cheerio.load(html))) {
|
|
166
|
+
throw new Error(`Access denied: CAPTCHA or block page detected at ${url}.`);
|
|
167
|
+
}
|
|
168
|
+
return html;
|
|
169
|
+
} finally {
|
|
170
|
+
await context.close();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Render `url` and return its HTML, retrying rate limits and transient failures once. */
|
|
175
|
+
export async function fetchHtml(browserManager, url, template, blockMedia) {
|
|
176
|
+
validateUrl(url);
|
|
177
|
+
for (let attempt = 1; ; attempt++) {
|
|
178
|
+
try {
|
|
179
|
+
return await fetchHtmlOnce(browserManager, url, template, blockMedia);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
const delay = retryDelayMs(err);
|
|
182
|
+
if (attempt >= MAX_ATTEMPTS || delay === null) throw err;
|
|
183
|
+
await sleep(delay);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Best-effort fetch of a raw Markdown source (e.g. `page.md`). Returns the cleaned Markdown, or
|
|
190
|
+
* null when the source is missing, is HTML, or does not look like Markdown.
|
|
191
|
+
*/
|
|
192
|
+
export async function fetchSourceMarkdown(browserManager, url, template, blockMedia) {
|
|
193
|
+
validateUrl(url);
|
|
194
|
+
let opened;
|
|
195
|
+
try {
|
|
196
|
+
opened = await openPage(await browserManager.get(), template, blockMedia);
|
|
197
|
+
const response = await opened.page.goto(url, {
|
|
198
|
+
waitUntil: "domcontentloaded",
|
|
199
|
+
timeout: SOURCE_TIMEOUT_MS,
|
|
200
|
+
});
|
|
201
|
+
if (!response || response.status() >= 400) return null;
|
|
202
|
+
const contentType = (response.headers()["content-type"] ?? "").toLowerCase();
|
|
203
|
+
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
const text = cleanSourceMarkdown(await response.text());
|
|
207
|
+
return isMarkdown(text) ? text : null;
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
} finally {
|
|
211
|
+
await opened?.context.close();
|
|
212
|
+
}
|
|
213
|
+
}
|