crawlforge-mcp-server 6.4.0 → 6.6.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/CLAUDE.md +5 -5
- package/README.md +7 -6
- package/package.json +2 -1
- package/server.js +83 -15
- package/src/cli/commands/browser.js +77 -0
- package/src/cli/index.js +3 -1
- package/src/core/ActionExecutor.js +185 -7
- package/src/core/AuthManager.js +26 -0
- package/src/core/ChangeTracker.js +25 -8
- package/src/core/browser/SessionStore.js +331 -0
- package/src/core/browser/snapshot.js +346 -0
- package/src/core/llm/LLMManager.js +86 -6
- package/src/core/processing/PDFProcessor.js +3 -1
- package/src/server/fallbackHints.js +4 -0
- package/src/server/inlineThreshold.js +31 -1
- package/src/server/requestContext.js +26 -5
- package/src/server/toolFilter.js +2 -2
- package/src/server/transports/streamableHttp.js +38 -8
- package/src/skills/agent-skills/crawlforge-batch-automation/SKILL.md +9 -2
- package/src/skills/agent-skills/crawlforge-batch-automation/references/actions.md +50 -4
- package/src/skills/agent-skills/crawlforge-browser-sessions/SKILL.md +178 -0
- package/src/skills/agent-skills/crawlforge-getting-started/SKILL.md +7 -4
- package/src/skills/agent-skills/crawlforge-getting-started/references/cli.md +6 -1
- package/src/skills/agent-skills/crawlforge-getting-started/references/credits.md +4 -0
- package/src/skills/installer.js +1 -1
- package/src/tools/advanced/BrowserSessionTool.js +476 -0
- package/src/tools/advanced/ScrapeWithActionsTool.js +10 -1
- package/src/tools/crawl/mapSite.js +81 -7
- package/src/tools/extract/extractEmbeddedState.js +18 -2
- package/src/tools/extract/extractStructured.js +4 -0
- package/src/tools/extract/processDocument.js +94 -1
- package/src/tools/scrape/_brandingExtractor.js +23 -5
- package/src/tools/scrape/unifiedScrape.js +8 -1
- package/src/tools/search/redditSearch.js +24 -17
- package/src/utils/hiddenContent.js +67 -2
- package/src/utils/redditHosts.js +123 -0
- package/src/utils/robotsGate.js +27 -3
|
@@ -258,6 +258,9 @@ export class ExtractStructuredTool {
|
|
|
258
258
|
if (result?.method === 'llm') {
|
|
259
259
|
extractionResult = result;
|
|
260
260
|
extractionMethod = 'llm';
|
|
261
|
+
// A salvaged cut-off response: the rows are real, the caller must
|
|
262
|
+
// know the list is not the whole table (R21, 2026-09-09).
|
|
263
|
+
if (result.warning) warnings.push(result.warning);
|
|
261
264
|
} else {
|
|
262
265
|
llmErrorMessage = result?.error || 'LLM did not return usable JSON';
|
|
263
266
|
}
|
|
@@ -433,6 +436,7 @@ export class ExtractStructuredTool {
|
|
|
433
436
|
},
|
|
434
437
|
extractionNotes,
|
|
435
438
|
provenance,
|
|
439
|
+
...(extractionResult.partial ? { partial: true } : {}),
|
|
436
440
|
...(warnings?.length ? { warnings } : {})
|
|
437
441
|
};
|
|
438
442
|
|
|
@@ -118,6 +118,57 @@ const ProcessDocumentResult = z.object({
|
|
|
118
118
|
error: z.string().optional()
|
|
119
119
|
});
|
|
120
120
|
|
|
121
|
+
/**
|
|
122
|
+
* What a fetched body is, from its Content-Type, magic bytes and URL:
|
|
123
|
+
* 'pdf', 'docx', 'binary' (something this tool cannot read) or 'html'
|
|
124
|
+
* (HTML, XML, JSON and plain text all go through the page pipeline).
|
|
125
|
+
* @param {string} contentType
|
|
126
|
+
* @param {Buffer} buffer
|
|
127
|
+
* @param {string} [url]
|
|
128
|
+
* @returns {'pdf'|'docx'|'binary'|'html'}
|
|
129
|
+
*/
|
|
130
|
+
export function sniffDocumentKind(contentType = '', buffer, url = '') {
|
|
131
|
+
const type = String(contentType).split(';')[0].trim().toLowerCase();
|
|
132
|
+
const head = buffer.subarray(0, 8).toString('latin1');
|
|
133
|
+
let path = String(url).toLowerCase();
|
|
134
|
+
try { path = new URL(url).pathname.toLowerCase(); } catch { /* keep the raw string */ }
|
|
135
|
+
|
|
136
|
+
if (type === 'application/pdf' || head.startsWith('%PDF')) return 'pdf';
|
|
137
|
+
|
|
138
|
+
const zip = head.startsWith('PK\u0003\u0004');
|
|
139
|
+
if (
|
|
140
|
+
type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
|
|
141
|
+
(zip && (path.endsWith('.docx') || buffer.includes('word/document.xml')))
|
|
142
|
+
) return 'docx';
|
|
143
|
+
|
|
144
|
+
if (zip) return 'binary';
|
|
145
|
+
if (/^(image|audio|video|font)\//.test(type)) return 'binary';
|
|
146
|
+
if (/^application\/(x-)?(zip|gzip|tar|7z|rar|msword|vnd\.)/.test(type)) return 'binary';
|
|
147
|
+
const textual = type.startsWith('text/') || /html|xml|json|javascript/.test(type);
|
|
148
|
+
if (!textual && buffer.subarray(0, 512).includes(0)) return 'binary';
|
|
149
|
+
return 'html';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Decode a text body by its Content-Type charset, else the <meta charset>
|
|
154
|
+
* it declares, else UTF-8.
|
|
155
|
+
* @param {Buffer} buffer
|
|
156
|
+
* @param {string} contentType
|
|
157
|
+
* @returns {string}
|
|
158
|
+
*/
|
|
159
|
+
export function decodeTextBody(buffer, contentType = '') {
|
|
160
|
+
let charset = (/charset=["']?([\w-]+)/i.exec(contentType) || [])[1];
|
|
161
|
+
if (!charset) {
|
|
162
|
+
const head = buffer.subarray(0, 4096).toString('latin1');
|
|
163
|
+
charset = (/<meta[^>]+charset=["']?([\w-]+)/i.exec(head) || [])[1];
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
return new TextDecoder(charset || 'utf-8').decode(buffer);
|
|
167
|
+
} catch {
|
|
168
|
+
return buffer.toString('utf8');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
121
172
|
export class ProcessDocumentTool {
|
|
122
173
|
constructor() {
|
|
123
174
|
this.pdfProcessor = new PDFProcessor();
|
|
@@ -340,7 +391,30 @@ export class ProcessDocumentTool {
|
|
|
340
391
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
341
392
|
}
|
|
342
393
|
|
|
343
|
-
|
|
394
|
+
// What came back decides how it is read, not the sourceType the caller
|
|
395
|
+
// guessed: a .docx fetched as 'url' was run through the HTML pipeline
|
|
396
|
+
// and returned its ZIP bytes as page text, success:true (R21,
|
|
397
|
+
// 2026-09-09). PDFs reach their parser the same way.
|
|
398
|
+
const contentType = response.headers.get('content-type') || '';
|
|
399
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
400
|
+
const kind = sniffDocumentKind(contentType, buffer, source);
|
|
401
|
+
if (kind === 'pdf') {
|
|
402
|
+
result.documentType = 'pdf';
|
|
403
|
+
await this.processPDFDocument(result, buffer, 'pdf_buffer', options, identity);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
if (kind === 'docx') {
|
|
407
|
+
result.documentType = 'docx';
|
|
408
|
+
await this.processDocxBuffer(result, buffer, options);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (kind === 'binary') {
|
|
412
|
+
throw new Error(
|
|
413
|
+
`${contentType.split(';')[0] || 'This'} content is not a document this tool reads: ` +
|
|
414
|
+
'process_document reads PDF, DOCX, HTML and plain text.'
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
html = decodeTextBody(buffer, contentType);
|
|
344
418
|
pageTitle = this.extractTitleFromHTML(html);
|
|
345
419
|
}
|
|
346
420
|
|
|
@@ -349,6 +423,25 @@ export class ProcessDocumentTool {
|
|
|
349
423
|
await this.processFetchedHtml(result, html, source, options);
|
|
350
424
|
}
|
|
351
425
|
|
|
426
|
+
/**
|
|
427
|
+
* Read a Word document: its text (and markdown when asked) via mammoth.
|
|
428
|
+
* @param {Object} result - Result object to populate
|
|
429
|
+
* @param {Buffer} buffer - the .docx bytes
|
|
430
|
+
* @param {Object} options - Processing options
|
|
431
|
+
*/
|
|
432
|
+
async processDocxBuffer(result, buffer, options) {
|
|
433
|
+
const mammoth = (await import('mammoth')).default;
|
|
434
|
+
const raw = await mammoth.extractRawText({ buffer });
|
|
435
|
+
result.content = { text: (raw.value || '').trim() };
|
|
436
|
+
if (options.outputFormat === 'markdown') {
|
|
437
|
+
const md = await mammoth.convertToMarkdown({ buffer });
|
|
438
|
+
result.content.markdown = md.value || '';
|
|
439
|
+
}
|
|
440
|
+
result.title = null;
|
|
441
|
+
const notes = (raw.messages || []).map((m) => m.message).filter(Boolean);
|
|
442
|
+
if (notes.length > 0) result.warnings = [...(result.warnings || []), ...notes.slice(0, 5)];
|
|
443
|
+
}
|
|
444
|
+
|
|
352
445
|
/**
|
|
353
446
|
* Process a local non-PDF file (sourceType 'file'): read it from disk and
|
|
354
447
|
* run it through the same content-processing pipeline used for web pages.
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { safeFetch } from '../../utils/ssrfGuard.js';
|
|
18
|
+
import { mediaAppliesToScreen } from '../../utils/hiddenContent.js';
|
|
18
19
|
|
|
19
20
|
const GENERIC_FAMILIES = new Set([
|
|
20
21
|
'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui',
|
|
@@ -123,19 +124,36 @@ export async function collectCssSources($, pageUrl, opts) {
|
|
|
123
124
|
let inlineStyleEls = 0;
|
|
124
125
|
let cssText = '';
|
|
125
126
|
|
|
127
|
+
// Print (and other non-screen) stylesheets never paint a screen render, so
|
|
128
|
+
// neither branding nor the hidden-content pass may read them. `media:
|
|
129
|
+
// 'unconditional-screen'` also drops sheets gated on a media query.
|
|
130
|
+
const unconditional = opts.media === 'unconditional-screen';
|
|
131
|
+
const applies = (el) => mediaAppliesToScreen($(el).attr('media'), { unconditional });
|
|
132
|
+
|
|
126
133
|
$('style').each((_, el) => {
|
|
134
|
+
if (!applies(el)) return;
|
|
127
135
|
const t = $(el).html();
|
|
128
136
|
if (t) { cssText += '\n' + t; styleBlocks++; }
|
|
129
137
|
});
|
|
130
138
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
139
|
+
// Inline style="" attributes are folded in as universal rules so branding
|
|
140
|
+
// can mine their colours and fonts. They are NOT visibility rules: one
|
|
141
|
+
// element carrying style="display:none" became `*{display:none}`, and the
|
|
142
|
+
// hidden-content pass then deleted every element small enough to pass its
|
|
143
|
+
// bulk guard — irs.gov's tax-bracket page came back as its header (R21,
|
|
144
|
+
// 2026-09-09). That pass reads inline styles per element itself, so it
|
|
145
|
+
// asks for `inlineStyles: false`.
|
|
146
|
+
if (opts.inlineStyles !== false) {
|
|
147
|
+
$('[style]').each((_, el) => {
|
|
148
|
+
const t = $(el).attr('style');
|
|
149
|
+
if (t) { cssText += '\n*{' + t + '}'; inlineStyleEls++; }
|
|
150
|
+
});
|
|
151
|
+
}
|
|
135
152
|
|
|
136
153
|
if (opts.fetchLinkedCss) {
|
|
137
154
|
const hrefs = [];
|
|
138
155
|
$('link[rel~="stylesheet"][href]').each((_, el) => {
|
|
156
|
+
if (!applies(el)) return;
|
|
139
157
|
const href = $(el).attr('href');
|
|
140
158
|
if (href) hrefs.push(resolveUrl(href, pageUrl));
|
|
141
159
|
});
|
|
@@ -404,7 +422,7 @@ function extractTokens(cssText, cssVariables) {
|
|
|
404
422
|
* Extract the full branding object from a loaded cheerio $.
|
|
405
423
|
* @param {import('cheerio').CheerioAPI} $
|
|
406
424
|
* @param {string} pageUrl
|
|
407
|
-
* @param {{ fetchLinkedCss?: boolean, maxStylesheets?: number, perFileTimeoutMs?: number, timeoutMs?: number, overallTimeoutMs?: number, stylesheetConcurrency?: number }} [opts]
|
|
425
|
+
* @param {{ fetchLinkedCss?: boolean, maxStylesheets?: number, perFileTimeoutMs?: number, timeoutMs?: number, overallTimeoutMs?: number, stylesheetConcurrency?: number, media?: 'screen'|'unconditional-screen', inlineStyles?: boolean }} [opts]
|
|
408
426
|
* @returns {Promise<object>}
|
|
409
427
|
*/
|
|
410
428
|
export async function extractBranding($, pageUrl, opts = {}) {
|
|
@@ -542,7 +542,14 @@ export class UnifiedScrapeTool {
|
|
|
542
542
|
// Themes split visibility rules across many component sheets — the
|
|
543
543
|
// rule hiding Shopify's sold-out badge sits at index 12 of 38 on a
|
|
544
544
|
// stock Dawn storefront, so a cap of 10 silently misses it.
|
|
545
|
-
maxStylesheets: 20
|
|
545
|
+
maxStylesheets: 20,
|
|
546
|
+
// Only sheets a screen render applies unconditionally: a
|
|
547
|
+
// media="print" sheet hid every screen element of irs.gov's
|
|
548
|
+
// tax-bracket page and left the print logo (R21, 2026-09-09).
|
|
549
|
+
media: 'unconditional-screen',
|
|
550
|
+
// stripHiddenFromDom reads style="" per element; folded into
|
|
551
|
+
// universal rules they hid the whole page (R21).
|
|
552
|
+
inlineStyles: false
|
|
546
553
|
});
|
|
547
554
|
css = collected.cssText || '';
|
|
548
555
|
}
|
|
@@ -15,11 +15,14 @@
|
|
|
15
15
|
* cross-subreddit full-text search, but has known post-2023 archive gaps
|
|
16
16
|
* and recurring outages.
|
|
17
17
|
*
|
|
18
|
-
* Routing:
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
18
|
+
* Routing: Arctic Shift first, PullPush second. A scoped search queries
|
|
19
|
+
* Arctic Shift and, if that fails, PullPush. An unscoped keyword search finds
|
|
20
|
+
* posts through a site-restricted web search and reads them — or searches
|
|
21
|
+
* their comments — in Arctic Shift by id, then falls back to PullPush's own
|
|
22
|
+
* full-text search. Thread mode is Arctic Shift only. PullPush has refused
|
|
23
|
+
* automated clients since August 2026, so the fallback usually reports that
|
|
24
|
+
* refusal; it stays second for whenever it answers again. Both archives are
|
|
25
|
+
* free and need no credentials.
|
|
23
26
|
*
|
|
24
27
|
* Optional official-API path: if the user sets REDDIT_CLIENT_ID and
|
|
25
28
|
* REDDIT_CLIENT_SECRET (their own Reddit app), posts/thread requests can read
|
|
@@ -101,9 +104,8 @@ export class RedditSearchTool {
|
|
|
101
104
|
// Lazily constructed on first official-path use; overridable for tests.
|
|
102
105
|
this._officialAdapter = options.officialAdapter || null;
|
|
103
106
|
|
|
104
|
-
// Web discovery serves the one shape
|
|
105
|
-
// across all of Reddit
|
|
106
|
-
// and PullPush stopped serving automated clients in August 2026.
|
|
107
|
+
// Web discovery serves the one shape Arctic Shift cannot: a keyword search
|
|
108
|
+
// across all of Reddit, which it requires a subreddit or author scope for.
|
|
107
109
|
this.searchAdapter = options.searchAdapter || null;
|
|
108
110
|
this.searchApiKey = options.searchApiKey || null;
|
|
109
111
|
this.searchApiBaseUrl = options.searchApiBaseUrl || null;
|
|
@@ -179,13 +181,16 @@ export class RedditSearchTool {
|
|
|
179
181
|
order = ['pullpush'];
|
|
180
182
|
} else {
|
|
181
183
|
// auto: prefer the user's own official API (live, authoritative) when it
|
|
182
|
-
// can serve this request, then
|
|
183
|
-
// PullPush
|
|
184
|
-
// 429 "This website does not
|
|
185
|
-
//
|
|
184
|
+
// can serve this request, then the community archives — Arctic Shift
|
|
185
|
+
// first, PullPush second (owner's call, 2026-09-10). PullPush has refused
|
|
186
|
+
// automated clients since August 2026 — 429 "This website does not
|
|
187
|
+
// provide free scraping resources for agents", or a Cloudflare 403
|
|
188
|
+
// challenge — so the fallback is one un-retried request that usually
|
|
189
|
+
// reports that refusal after the real Arctic Shift error, and answers
|
|
190
|
+
// when PullPush is serving again. Thread mode has no second source.
|
|
186
191
|
const archives = v.mode === 'thread' ? ['arctic_shift']
|
|
187
|
-
: arcticPossible ? ['arctic_shift']
|
|
188
|
-
: discoveryPossible ? ['web_discovery']
|
|
192
|
+
: arcticPossible ? ['arctic_shift', 'pullpush']
|
|
193
|
+
: discoveryPossible ? ['web_discovery', 'pullpush']
|
|
189
194
|
: [];
|
|
190
195
|
order = officialPossible ? ['reddit_api', ...archives] : archives;
|
|
191
196
|
}
|
|
@@ -252,7 +257,7 @@ export class RedditSearchTool {
|
|
|
252
257
|
? 'Reddit-wide comment search: posts were found with a site-restricted web search, then each post\'s comments were searched for the keywords in the Arctic Shift archive, in post relevance order.'
|
|
253
258
|
: 'Reddit-wide keyword search: posts were found with a site-restricted web search, then read from the Arctic Shift archive by ID.',
|
|
254
259
|
'Results are ordered by web-search relevance, not by score or date.',
|
|
255
|
-
'Arctic Shift cannot keyword-search across all of Reddit
|
|
260
|
+
'Arctic Shift cannot keyword-search across all of Reddit — scope the search to a subreddit or author to query the archive directly.',
|
|
256
261
|
];
|
|
257
262
|
if (v.after || v.before) {
|
|
258
263
|
// Silently dropping a date filter would return results the caller
|
|
@@ -489,12 +494,14 @@ export class RedditSearchTool {
|
|
|
489
494
|
if (response.status === 429) {
|
|
490
495
|
const reset = response.headers?.get?.('x-ratelimit-reset');
|
|
491
496
|
// PullPush's 429 body states its actual policy ("does not provide free
|
|
492
|
-
// scraping resources for agents...") — pass that through verbatim.
|
|
497
|
+
// scraping resources for agents...") — pass that through verbatim. That
|
|
498
|
+
// policy refusal is not a transient throttle: retrying it only spends the
|
|
499
|
+
// delay, which matters now that PullPush is the automatic second source.
|
|
493
500
|
let detail = '';
|
|
494
501
|
try { detail = (await response.json())?.error ?? ''; } catch { /* no body */ }
|
|
495
502
|
throw Object.assign(
|
|
496
503
|
new Error(`rate limited (429)${reset ? `, retry in ${reset}s` : ''}${detail ? ` — ${detail}` : ''}`),
|
|
497
|
-
{ retryable:
|
|
504
|
+
{ retryable: !/does not provide free scraping/i.test(detail) },
|
|
498
505
|
);
|
|
499
506
|
}
|
|
500
507
|
if (!response.ok) {
|
|
@@ -83,6 +83,38 @@ function stripConditionalBlocks(css) {
|
|
|
83
83
|
return out;
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Split a selector list on its top-level commas only. A naive split cut
|
|
88
|
+
* irs.gov's `.callout:has(> .a, .b, p, ul, h2, h3, table)` into bare `p`,
|
|
89
|
+
* `ul`, `h2`, `h3` and `table` rules carrying its `display:none !important`,
|
|
90
|
+
* and the stripper then deleted the article body (R21, 2026-09-09).
|
|
91
|
+
* @param {string} list
|
|
92
|
+
* @returns {string[]}
|
|
93
|
+
*/
|
|
94
|
+
export function splitSelectorList(list) {
|
|
95
|
+
const out = [];
|
|
96
|
+
let depth = 0;
|
|
97
|
+
let quote = null;
|
|
98
|
+
let start = 0;
|
|
99
|
+
for (let i = 0; i < list.length; i++) {
|
|
100
|
+
const ch = list[i];
|
|
101
|
+
if (quote) {
|
|
102
|
+
if (ch === '\\') i++;
|
|
103
|
+
else if (ch === quote) quote = null;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (ch === '"' || ch === "'") quote = ch;
|
|
107
|
+
else if (ch === '(' || ch === '[') depth++;
|
|
108
|
+
else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
|
|
109
|
+
else if (ch === ',' && depth === 0) {
|
|
110
|
+
out.push(list.slice(start, i));
|
|
111
|
+
start = i + 1;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
out.push(list.slice(start));
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
86
118
|
/** True when cheerio cannot meaningfully evaluate the selector. */
|
|
87
119
|
function isUnsupportedSelector(selector) {
|
|
88
120
|
return (
|
|
@@ -91,7 +123,7 @@ function isUnsupportedSelector(selector) {
|
|
|
91
123
|
// case and these rules would hide content every real visitor sees.
|
|
92
124
|
/(^|[\s.#\[])no-js(\b|[.\[])/.test(selector) ||
|
|
93
125
|
selector.includes('::') ||
|
|
94
|
-
/:(hover|focus|focus-within|focus-visible|active|target|checked|disabled|placeholder|before|after|root|host|where|is|not\()/i.test(selector) ||
|
|
126
|
+
/:(hover|focus|focus-within|focus-visible|active|target|checked|disabled|placeholder|before|after|root|host|where|is|not\(|has\()/i.test(selector) ||
|
|
95
127
|
selector.includes('@') ||
|
|
96
128
|
selector.length === 0
|
|
97
129
|
);
|
|
@@ -199,7 +231,7 @@ export function collectVisibilitySelectors(css) {
|
|
|
199
231
|
|
|
200
232
|
const important = /!\s*important/i.test(body);
|
|
201
233
|
|
|
202
|
-
for (const raw of selectorList
|
|
234
|
+
for (const raw of splitSelectorList(selectorList)) {
|
|
203
235
|
const selector = raw.trim();
|
|
204
236
|
if (isUnsupportedSelector(selector) || NEVER_REMOVE.has(selector)) continue;
|
|
205
237
|
const entry = { selector, spec: specificity(selector), order, important };
|
|
@@ -249,12 +281,45 @@ function renderedSize($, el) {
|
|
|
249
281
|
export function inlineStyleText($) {
|
|
250
282
|
const parts = [];
|
|
251
283
|
$('style').each((_, el) => {
|
|
284
|
+
// A <style media="print"> block is only consulted when printing.
|
|
285
|
+
if (!mediaAppliesToScreen($(el).attr('media'), { unconditional: true })) return;
|
|
252
286
|
const text = $(el).html();
|
|
253
287
|
if (text) parts.push(text);
|
|
254
288
|
});
|
|
255
289
|
return parts.join('\n');
|
|
256
290
|
}
|
|
257
291
|
|
|
292
|
+
/**
|
|
293
|
+
* Whether a stylesheet's `media` attribute applies to a screen render.
|
|
294
|
+
*
|
|
295
|
+
* `<link rel="stylesheet" media="print">` is consulted only when printing.
|
|
296
|
+
* irs.gov's tax-bracket page ships one that hides every screen element and
|
|
297
|
+
* shows a print-only logo; read as screen CSS it emptied the page to that logo
|
|
298
|
+
* (R21, 2026-09-09). Absent or empty, `all`, `screen` and `not print` apply.
|
|
299
|
+
* `print`, `speech` and the other non-screen types, and `not screen`/`not all`,
|
|
300
|
+
* do not. With `unconditional: true` a media QUERY (`screen and (max-width:
|
|
301
|
+
* 600px)`, a bare `(prefers-color-scheme: dark)`) does not apply either — the
|
|
302
|
+
* hidden-content pass ignores @media blocks for the same reason.
|
|
303
|
+
*
|
|
304
|
+
* @param {string|undefined} media - the attribute value
|
|
305
|
+
* @param {{ unconditional?: boolean }} [options]
|
|
306
|
+
* @returns {boolean}
|
|
307
|
+
*/
|
|
308
|
+
export function mediaAppliesToScreen(media, { unconditional = false } = {}) {
|
|
309
|
+
const value = (media || '').trim().toLowerCase();
|
|
310
|
+
if (!value) return true;
|
|
311
|
+
return value.split(',').some((part) => {
|
|
312
|
+
const query = part.trim();
|
|
313
|
+
if (!query) return false;
|
|
314
|
+
if (unconditional && query.includes('(')) return false;
|
|
315
|
+
if (query.startsWith('(')) return true; // a bare feature query: type "all"
|
|
316
|
+
const m = query.match(/^(?:(not|only)\s+)?([a-z-]+)/);
|
|
317
|
+
if (!m) return true;
|
|
318
|
+
const screenType = m[2] === 'all' || m[2] === 'screen';
|
|
319
|
+
return m[1] === 'not' ? !screenType : screenType;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
258
323
|
/**
|
|
259
324
|
* Remove browser-invisible content from a cheerio document, in place.
|
|
260
325
|
*
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* redditHosts — reddit.com is never fetched.
|
|
3
|
+
*
|
|
4
|
+
* reddit.com refuses every non-browser client (403, and the stealth browsers
|
|
5
|
+
* too — the block is IP/TLS-reputation based), so a scrape or fetch_url
|
|
6
|
+
* against it always fails and leaves the caller guessing. Reddit is served by
|
|
7
|
+
* reddit_search, which reads the same posts and comments from the Arctic
|
|
8
|
+
* Shift community archive (PullPush second). A reddit.com target is therefore
|
|
9
|
+
* refused before any network work, with the reddit_search call that gets the
|
|
10
|
+
* same data spelled out — derived from the URL where the URL says enough.
|
|
11
|
+
*
|
|
12
|
+
* Runs inside the pre-fetch gate (robotsGate.js), so every fetching tool and
|
|
13
|
+
* both browser paths get it without knowing. Not overridable: respect_robots
|
|
14
|
+
* is about robots.txt, and fetching reddit.com fails whatever the caller sends.
|
|
15
|
+
*
|
|
16
|
+
* Mirrors the website's `src/lib/tools/reddit-hosts.ts` — same rule, same
|
|
17
|
+
* message — so a reddit.com URL is answered identically on both surfaces.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export class UseRedditSearchError extends Error {
|
|
21
|
+
constructor(url) {
|
|
22
|
+
const call = redditSearchCallFor(url);
|
|
23
|
+
const nextStep = Object.keys(call).length
|
|
24
|
+
? `reddit_search(${JSON.stringify(call)})`
|
|
25
|
+
: 'reddit_search with a query, subreddit or author — or mode "thread" with a post\'s link_id';
|
|
26
|
+
super(
|
|
27
|
+
`${hostOf(url)} is not fetched: reddit.com refuses every non-browser client, stealth browsers included, ` +
|
|
28
|
+
`so this call would fail. Reddit is served by reddit_search (5 credits), which reads the same posts ` +
|
|
29
|
+
`and comments from the Arctic Shift community archive. Next step: ${nextStep}`
|
|
30
|
+
);
|
|
31
|
+
this.name = 'UseRedditSearchError';
|
|
32
|
+
this.code = 'USE_REDDIT_SEARCH';
|
|
33
|
+
this.url = url;
|
|
34
|
+
this.redditSearchCall = call;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The hostname of a URL, lowercased, or null if it will not parse. */
|
|
39
|
+
function hostOf(url) {
|
|
40
|
+
try {
|
|
41
|
+
return new URL(url).hostname.toLowerCase().replace(/\.$/, '');
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* True for reddit.com and its subdomains (www, old, new, np, sh …) and for the
|
|
49
|
+
* bare redd.it short-link host. The media hosts (i.redd.it, v.redd.it,
|
|
50
|
+
* preview.redd.it) serve files to any client and are left alone.
|
|
51
|
+
* @param {string} url
|
|
52
|
+
*/
|
|
53
|
+
export function isRedditUrl(url) {
|
|
54
|
+
const host = hostOf(url);
|
|
55
|
+
if (!host) return false;
|
|
56
|
+
return host === 'reddit.com' || host.endsWith('.reddit.com') || host === 'redd.it';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The reddit_search call that answers a reddit.com URL, or {} when the URL
|
|
61
|
+
* names nothing reddit_search can be pointed at (the front page, a wiki, a
|
|
62
|
+
* settings page).
|
|
63
|
+
*
|
|
64
|
+
* /r/{sub}/comments/{id}/…, /comments/{id}, /gallery/{id}, redd.it/{id}
|
|
65
|
+
* → mode "thread", link_id
|
|
66
|
+
* /r/{sub}/search?q=… → query scoped to the subreddit
|
|
67
|
+
* /search?q=… → an unscoped query
|
|
68
|
+
* /r/{sub}[/new|/top|…] → the subreddit's posts
|
|
69
|
+
* /user/{name} or /u/{name}[/comments] → the author's posts (or comments)
|
|
70
|
+
* ?type=comment → mode "comments"
|
|
71
|
+
* @param {string} url
|
|
72
|
+
* @returns {{ mode?: string, query?: string, subreddit?: string, author?: string, link_id?: string }}
|
|
73
|
+
*/
|
|
74
|
+
export function redditSearchCallFor(url) {
|
|
75
|
+
let parsed;
|
|
76
|
+
try {
|
|
77
|
+
parsed = new URL(url);
|
|
78
|
+
} catch {
|
|
79
|
+
return {};
|
|
80
|
+
}
|
|
81
|
+
const segments = parsed.pathname
|
|
82
|
+
.split('/')
|
|
83
|
+
.filter(Boolean)
|
|
84
|
+
.map((segment) => {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(segment);
|
|
87
|
+
} catch {
|
|
88
|
+
return segment;
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
if (parsed.hostname.toLowerCase() === 'redd.it') {
|
|
93
|
+
return segments[0] ? { mode: 'thread', link_id: segments[0] } : {};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// A post's id follows "comments" or "gallery" wherever it sits in the path;
|
|
97
|
+
// a permalink to one comment still reads as its thread.
|
|
98
|
+
const idAt = segments.findIndex((segment) => segment === 'comments' || segment === 'gallery');
|
|
99
|
+
if (idAt !== -1 && segments[idAt + 1]) {
|
|
100
|
+
return { mode: 'thread', link_id: segments[idAt + 1] };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const call = {};
|
|
104
|
+
if (segments[0] === 'r' && segments[1]) call.subreddit = segments[1];
|
|
105
|
+
if ((segments[0] === 'user' || segments[0] === 'u') && segments[1]) {
|
|
106
|
+
call.author = segments[1];
|
|
107
|
+
if (segments[2] === 'comments') call.mode = 'comments';
|
|
108
|
+
}
|
|
109
|
+
const query = parsed.searchParams.get('q')?.trim();
|
|
110
|
+
if (query) call.query = query;
|
|
111
|
+
if (parsed.searchParams.get('type') === 'comment') call.mode = 'comments';
|
|
112
|
+
return call;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Throw UseRedditSearchError for a reddit.com target. Call before any network
|
|
117
|
+
* work — the point is that reddit.com never gets a request, not even for its
|
|
118
|
+
* robots.txt.
|
|
119
|
+
* @param {string} url
|
|
120
|
+
*/
|
|
121
|
+
export function assertNotRedditUrl(url) {
|
|
122
|
+
if (isRedditUrl(url)) throw new UseRedditSearchError(url);
|
|
123
|
+
}
|
package/src/utils/robotsGate.js
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
|
|
20
20
|
import { RobotsChecker } from './robotsChecker.js';
|
|
21
21
|
import { assertHostAllowed } from './hostBlocklist.js';
|
|
22
|
+
import { assertNotRedditUrl } from './redditHosts.js';
|
|
22
23
|
import { identityHeaders, resolveUserAgent } from './fetchIdentity.js';
|
|
23
24
|
import { throttleHost } from './hostRateLimiter.js';
|
|
24
25
|
import { recordComplianceEvent, apiKeyId } from './complianceAudit.js';
|
|
@@ -75,8 +76,13 @@ export async function robotsPreflight(url, options = {}) {
|
|
|
75
76
|
// costs the caller nothing: we refused, we fetched nothing.
|
|
76
77
|
try {
|
|
77
78
|
assertHostAllowed(url);
|
|
79
|
+
// reddit.com refuses every non-browser client, so it is never fetched and
|
|
80
|
+
// the caller is pointed at reddit_search instead. Also not overridable.
|
|
81
|
+
assertNotRedditUrl(url);
|
|
78
82
|
} catch (error) {
|
|
79
|
-
if (error?.code === 'HOST_BLOCKED'
|
|
83
|
+
if (error?.code === 'HOST_BLOCKED' || error?.code === 'USE_REDDIT_SEARCH') {
|
|
84
|
+
markPreflightRefusal(error.code);
|
|
85
|
+
}
|
|
80
86
|
throw error;
|
|
81
87
|
}
|
|
82
88
|
|
|
@@ -178,11 +184,29 @@ export async function preflightFetch(url, options = {}) {
|
|
|
178
184
|
return {
|
|
179
185
|
headers: outboundHeaders(decision.userAgent, signature),
|
|
180
186
|
userAgent: decision.userAgent,
|
|
181
|
-
warnings: decision.warnings,
|
|
187
|
+
warnings: [...decision.warnings, ...crawlDelayWarning(url, decision.crawlDelayMs)],
|
|
182
188
|
overridden: decision.overridden
|
|
183
189
|
};
|
|
184
190
|
}
|
|
185
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Name a long Crawl-delay, so a slow multi-page call reads as compliance
|
|
194
|
+
* rather than a stall: eff.org asks every agent for 30 s, and a 10-page
|
|
195
|
+
* llms.txt run took 13 minutes with nothing in the response saying why (R21,
|
|
196
|
+
* 2026-09-09).
|
|
197
|
+
* @param {string} url
|
|
198
|
+
* @param {number} crawlDelayMs
|
|
199
|
+
* @returns {string[]}
|
|
200
|
+
*/
|
|
201
|
+
function crawlDelayWarning(url, crawlDelayMs) {
|
|
202
|
+
if (!(crawlDelayMs >= 5000)) return [];
|
|
203
|
+
let host = url;
|
|
204
|
+
try { host = new URL(url).host; } catch { /* keep the raw url */ }
|
|
205
|
+
return [
|
|
206
|
+
`robots.txt on ${host} asks for a ${Math.round(crawlDelayMs / 1000)} s crawl delay; requests to it are spaced by that much, so a multi-page call takes about that long per page.`
|
|
207
|
+
];
|
|
208
|
+
}
|
|
209
|
+
|
|
186
210
|
/**
|
|
187
211
|
* The gate for browser paths. Same decision as {@link preflightFetch}, minus
|
|
188
212
|
* the identity and signature headers — those belong on an HTTP fetch, not on a
|
|
@@ -213,7 +237,7 @@ export async function browserPreflight(url, options = {}) {
|
|
|
213
237
|
}
|
|
214
238
|
|
|
215
239
|
await throttleHost(url, { crawlDelayMs: decision.crawlDelayMs });
|
|
216
|
-
return decision.warnings;
|
|
240
|
+
return [...decision.warnings, ...crawlDelayWarning(url, decision.crawlDelayMs)];
|
|
217
241
|
}
|
|
218
242
|
|
|
219
243
|
/** Test/diagnostic hook: drop every cached robots.txt. */
|